\n image_text = soup.find('div', {'class': 'entry'}).get_text()\n print('image_text: ' + image_text)\n img_path = save_image_from_url(img_link, image_index, new_folder)\n\n image_text = image_text.strip()\n if image_text != '':\n # I want the text printed in the same image size as the last downloaded image\n # so I extract the size from it.\n im = Image.open(img_path)\n image_size = im.size # (width,height) tuple\n # get the image from the flask utility\n try:\n get_image_from_text2pic(image_text, image_size, image_index, new_folder)\n except RequestException as ex:\n print(\"Exception connecting to text2pic\")\n print(ex)\n # next loop step\n current_page = next_link\n page_index += 1\n image_index += 1\n except RequestException as ex: # this covers everything\n print(\"Couldn´t get page\" + current_page)\n print(ex)\n break\n except Exception as inst:\n print(type(inst)) # the exception instance\n print(inst.args) # arguments stored in .args\n print(inst) # __str__ allows args to be printed directly,\n # but may be overridden in exception subclasses#\n # end of chapter loop\n # create zip\n compress_folder(new_folder)\n delete_folder(new_folder)\n\n\ndef get_image_from_text2pic(text, size, image_index, new_folder):\n \"\"\"\n\n Sends some text to the text2pic service that embeds the text in a series\n of images of the given size\n\n The images are named using the image_index so they will appear after\n the original image\n\n :param text: the text to put into images\n :param size: the image size\n :param image_index: current image index\n :param new_folder: destination folder to store images\n :return:\n \"\"\"\n text2pic_host = 'http://localhost:5000'\n # compose input json for text2pic\n w_margin = size[0] * 0.15\n h_margin = size[1] * 0.15\n data = {'text': text, 'width': size[0], 'height': size[1],\n 'margin-width': w_margin, 'margin-height': h_margin,\n 'font': 'arial.ttf', 'font-size': 32}\n json_data = json.dumps(data)\n headers = {'Content-type': 'application/json'}\n img_request = requests.post(text2pic_host + '/text2pic', headers=headers, data=json_data, stream=True)\n if img_request.status_code == 200:\n # get json body and iterate\n # the json response is an array of image relative urls\n json_resp = img_request.json()\n for item in json_resp['images']:\n current_img_url = text2pic_host + item['filename']\n save_image_from_url(current_img_url, image_index, new_folder, True)\n else:\n # bad request\n print('Error in text from ' + image_index + ' image in chapter ' + new_folder + ')')\n print(img_request.text)\n\n\ndef get_end_of_chapter(start_url, next_chapter):\n page = requests.get(start_url)\n if page.status_code != requests.codes.ok:\n return ''\n\n soup = BeautifulSoup(page.text, \"html.parser\")\n # get the url for the \"Next page\" link\n next_link = soup.find('a', href=True, string=next_chapter)\n if next_link:\n next_link = next_link['href']\n else:\n next_link = ''\n return next_link\n", "sub_path": "comiccrawl/chapterthread.py", "file_name": "chapterthread.py", "file_ext": "py", "file_size_in_byte": 5525, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "comiccrawl.utils.make_new_folder", "line_number": 35, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 41, "usage_type": "call"}, {"api_name": "requests.codes", "line_number": 42, "usage_type": "attribute"}, {"api_name": "bs4.BeautifulSoup", "line_number": 45, "usage_type": "call"}, {"api_name": "comiccrawl.utils.save_image_from_url", "line_number": 61, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 67, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 67, "usage_type": "name"}, {"api_name": "requests.RequestException", "line_number": 72, "usage_type": "name"}, {"api_name": "requests.RequestException", "line_number": 79, "usage_type": "name"}, {"api_name": "comiccrawl.compress.compress_folder", "line_number": 90, "usage_type": "call"}, {"api_name": "comiccrawl.utils.delete_folder", "line_number": 91, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 116, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 118, "usage_type": "call"}, {"api_name": "comiccrawl.utils.save_image_from_url", "line_number": 125, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 133, "usage_type": "call"}, {"api_name": "requests.codes", "line_number": 134, "usage_type": "attribute"}, {"api_name": "bs4.BeautifulSoup", "line_number": 137, "usage_type": "call"}]}
+{"seq_id": "199421809", "text": "# -*- coding: utf-8 -*-\n#\n# This file is part of hepcrawl.\n# Copyright (C) 2015, 2016, 2017 CERN.\n#\n# hepcrawl is a free software; you can redistribute it and/or modify it\n# under the terms of the Revised BSD License; see LICENSE file for\n# more details.\n\n\"\"\"Spider for PHENIX.\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nfrom urlparse import urljoin\n\nfrom scrapy import Request\nfrom scrapy.spiders import XMLFeedSpider\n\nfrom ..items import HEPRecord\nfrom ..loaders import HEPLoader\nfrom ..utils import ParsedItem\n\n\nclass PhenixSpider(XMLFeedSpider):\n\n \"\"\"PHENIX crawler\n\n Scrapes theses metadata from `PHENIX experiment web page`_.\n\n 1. ``PhenixSpider.parse()`` iterates through every record on the html page and yields\n a ``HEPRecord``.\n\n Examples:\n ::\n\n $ scrapy crawl phenix\n\n Using source file and output directory::\n\n $ scrapy crawl phenix -a source_file=file://`pwd`/tests/responses/phenix/test_list.html -s \"JSON_OUTPUT_DIR=tmp/\"\n\n .. _PHENIX experiment web page:\n http://www.phenix.bnl.gov/WWW/talk/theses.php\n \"\"\"\n\n name = 'phenix'\n start_urls = [\"http://www.phenix.bnl.gov/WWW/talk/theses.php\"]\n domain = \"http://www.phenix.bnl.gov\"\n iterator = \"html\"\n itertag = \"//table//td/ul/li\"\n\n def __init__(self, source_file=None, *args, **kwargs):\n \"\"\"Construct PHENIX spider\"\"\"\n super(PhenixSpider, self).__init__(*args, **kwargs)\n self.source_file = source_file\n\n def start_requests(self):\n \"\"\"You can also run the spider on local test files\"\"\"\n if self.source_file:\n yield Request(self.source_file)\n elif self.start_urls:\n for url in self.start_urls:\n yield Request(url)\n\n @staticmethod\n def parse_datablock(node):\n \"\"\"Get data out of the text block where there's\n title, affiliation and year\n \"\"\"\n datablock = node.xpath(\"./text()\").extract()[0]\n datalist = datablock.strip().split(\",\")\n\n thesis_type = None\n if \"Ph.D.\" in datablock:\n thesis_type = \"PhD\"\n\n title = datablock.split('\"')[1]\n datalist = [el for el in datalist if \"archive\" not in el]\n year = datalist.pop().strip()\n affline = datalist.pop().strip()\n stop_words = {\"Ph.D.\", \"Master\", \"thesis\", \"at\"}\n affiliation = \" \".join(\n [w for w in affline.split() if w not in stop_words])\n\n return title, year, affiliation, thesis_type\n\n def get_authors(self, node):\n \"\"\"Return authors dictionary \"\"\"\n author = node.xpath(\"./b/text()\").extract()\n authors = []\n _, _, affiliation, _ = self.parse_datablock(node)\n\n for aut in author:\n authors.append({\n 'raw_name': aut,\n 'affiliations': [{\"value\": affiliation}]\n })\n\n return authors\n\n def add_fft_file(self, pdf_files, file_access, file_type):\n \"\"\"Create a structured dictionary and add to ``files`` item.\"\"\"\n file_dicts = []\n for link in pdf_files:\n file_dict = {\n \"access\": file_access,\n \"description\": self.name.title(),\n \"url\": urljoin(self.domain, link),\n \"type\": file_type,\n }\n file_dicts.append(file_dict)\n return file_dicts\n\n def parse_node(self, response, node):\n \"\"\"Parse PHENIX web page into a ``HEPrecord``.\"\"\"\n record = HEPLoader(item=HEPRecord(), selector=node, response=response)\n title, year, _, thesis_type = self.parse_datablock(node)\n\n if not thesis_type:\n return None\n\n pdf_files = node.xpath(\".//a/@href\").extract()\n record.add_value('additional_files', self.add_fft_file(pdf_files, \"HIDDEN\", \"Fulltext\"))\n record.add_value('authors', self.get_authors(node))\n record.add_value('date_published', year)\n record.add_value('thesis', {'degree_type': thesis_type})\n record.add_value('title', title)\n record.add_value('urls', self.start_urls)\n record.add_value('source', 'PHENIX')\n record.add_value('collections', ['HEP', 'THESIS'])\n\n parsed_item = ParsedItem(\n record=record.load_item(),\n record_format='hepcrawl',\n )\n\n return parsed_item\n", "sub_path": "hepcrawl/spiders/phenix_spider.py", "file_name": "phenix_spider.py", "file_ext": "py", "file_size_in_byte": 4350, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "scrapy.spiders.XMLFeedSpider", "line_number": 24, "usage_type": "name"}, {"api_name": "scrapy.Request", "line_number": 60, "usage_type": "call"}, {"api_name": "scrapy.Request", "line_number": 63, "usage_type": "call"}, {"api_name": "urlparse.urljoin", "line_number": 108, "usage_type": "call"}, {"api_name": "loaders.HEPLoader", "line_number": 116, "usage_type": "call"}, {"api_name": "items.HEPRecord", "line_number": 116, "usage_type": "call"}, {"api_name": "utils.ParsedItem", "line_number": 132, "usage_type": "call"}]}
+{"seq_id": "31223550", "text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport os\nimport sys\nimport random\n\nimport librosa\nimport numpy as np\nimport tensorflow as tf\n\nfrom utils import audio_process\n\n\nQUANTIZATION_CHANNELS = 256\nMU = QUANTIZATION_CHANNELS - 1\n'''\n VCTK specifications:\n - 109 native speakers of English with various accents.\n - Each speaker reads out about 400 stences: most of which were selected from a newspaper\n plus Rainbow Passage and an elicitation paragraph intended to identify the speaker's\n accents.\n - 96 kHz versions of the recordings.\n'''\n\n\n\n# The maximum value in VCTK waveforms is 1.1599158.\n# The minimum value in VCTK waveforms is -1.1816651.\nMAX = 1.2\n\n\ndef get_dataset_list(dir_name):\n audio_file_names = []\n txt_file_names = []\n audio_full_paths = {}\n txt_full_paths = {}\n dataset_list = []\n for [path, dir, files] in os.walk(dir_name):\n for file_name in files:\n ext = os.path.splitext(file_name)[-1]\n if ext == \".wav\":\n full_file_name = path + \"/\" + file_name\n full_file_name_ = full_file_name.split(\"/\")\n file_name_ = (\"/\" +\n full_file_name_[-2] +\n \"/\" +\n full_file_name_[-1]).replace(\".wav\", \"\")\n audio_full_paths[file_name_] = full_file_name\n audio_file_names.append(file_name_)\n elif ext == \".txt\":\n full_file_name = path + \"/\" + file_name\n full_file_name_ = full_file_name.split(\"/\")\n file_name_ = (\"/\" +\n full_file_name_[-2] +\n \"/\" +\n full_file_name_[-1]).replace(\".txt\", \"\")\n txt_full_paths[file_name_] = full_file_name\n txt_file_names.append(file_name_)\n audio_file_names = set(audio_file_names)\n txt_file_names = set(txt_file_names)\n file_names = list(audio_file_names & txt_file_names)\n file_names.sort()\n for file_name in file_names:\n file_name_ = file_name.split(\"/\")\n audio_full_path = audio_full_paths[file_name]\n txt_full_path = txt_full_paths[file_name]\n dataset_list.append({\"audio_file_path\": audio_full_path,\n \"txt_file_path\": txt_full_path,\n \"personal_id\": file_name_[1]})\n return dataset_list\n\n\ndef get_char_dict(dataset_list):\n txt_file_names = [data[\"txt_file_path\"] for data in dataset_list]\n char_dict = set()\n for file_name in txt_file_names:\n with open(file=file_name, mode=\"rt\", encoding=\"utf-8\") as f:\n for line in f:\n char_dict.update(set(line))\n char_dict = list(set(char_dict))\n reverse_dict = {char_dict[i]: i for i in range(len(char_dict))}\n return char_dict, reverse_dict\n\n\ndef get_id_dict(dataset_list):\n id_dict = [data[\"personal_id\"] for data in dataset_list]\n id_dict = list(set(id_dict))\n reverse_id_dict = {id_dict[i]: i for i in range(len(id_dict))}\n return id_dict, reverse_id_dict\n\n\ndef get_txt(file_path):\n txt_list = []\n with open(file=file_path, mode=\"rt\", encoding=\"utf-8\") as f:\n for line in f:\n txt_list.append(line)\n txt_ = \" \".join(txt_list)\n return txt_\n\n\nclass DatasetLoader(object):\n def __init__(self,\n dir_name,\n batch_size,\n samplinig_rate,\n quantization_channels,\n sample_size,\n silence_threshold):\n self.dir_name = dir_name\n self.dataset_list = get_dataset_list(self.dir_name)\n self.batch_size = batch_size\n self.quantization_channels = quantization_channels\n self.sample_size = sample_size\n self.silence_threshold = silence_threshold\n # For batch generating or training. Not implemented yet\n self.audio_cutting = False\n self.max_ = MAX\n self.mu = quantization_channels - 1\n self.sampling_rate = samplinig_rate\n self.num_data = len(self.dataset_list)\n self.char_dict, self.reverse_dict = get_char_dict(self.dataset_list)\n self.txt_one_hot_table = np.eye(len(self.char_dict))\n self.id_dict, self.reverse_id_dict= get_id_dict(self.dataset_list)\n self.id_one_hot_table = np.eye(len(self.id_dict))\n\n def generate_data(self):\n while True:\n random_dataset_list = self.dataset_list[:]\n random.shuffle(random_dataset_list)\n for dataset in random_dataset_list:\n file_path = dataset[\"audio_file_path\"]\n audio, _ = librosa.load(file_path,\n sr=self.sampling_rate)\n # For batch generating or training. Not implemented yet\n if self.audio_cutting:\n length = np.shape(audio)[0]\n if length >= self.sample_size:\n audio = audio[:self.sample_size]\n else:\n audio = np.pad(audio, pad_width=[0, self.sample_size - length],\n mode=\"constant\")\n if self.silence_threshold is not None:\n audio = audio_process.remove_silence(audio=audio,\n threshold=self.silence_threshold)\n id_ = self.id_encode(dataset[\"personal_id\"])\n yield audio, id_, file_path\n\n def get_batch_(self):\n random_batch_idx = np.random.choice(a=self.num_data,\n size=self.batch_size,\n replace=False)\n dataset_list_ = []\n for i in random_batch_idx:\n dataset_list_.append(self.dataset_list[i])\n audio_batch = []\n for i in random_batch_idx:\n audio, _ = librosa.load(self.dataset_list[i][\"audio_file_path\"],\n sr=self.sampling_rate)\n quantized_audio = audio_process.quantization(audio,\n self.quantization_channels,\n MAX,\n self.mu)\n one_hot_audio = audio_process.audio_one_hot_encoding(quantized_audio,\n self.quantization_channels)\n audio_batch.append(one_hot_audio)\n txt_batch = []\n for i in random_batch_idx:\n txt_ = get_txt(file_path=self.dataset_list[i][\"txt_file_path\"])\n txt_one_hot = []\n for ch in txt_:\n one_hot = self.txt_one_hot_encoding(ch)\n txt_one_hot.append(one_hot)\n txt_batch.append(txt_one_hot)\n id_batch = []\n for i in random_batch_idx:\n id_ = self.id_one_hot_encoding(self.dataset_list[i][\"personal_id\"])\n id_batch.append(id_)\n return dataset_list_, \\\n np.asarray(audio_batch), \\\n np.asarray(txt_batch), \\\n np.asarray(id_batch)\n\n def create_dataset(self):\n self.dataset = tf.data.Dataset.\\\n from_generator(generator=self.generate_data,\n output_types=(tf.float32,\n tf.float32,\n tf.string),\n output_shapes=(tf.TensorShape([None]),\n tf.TensorShape([len(self.id_dict)]),\n None))\n self.next_audio_batch, self.next_id_batch, self.next_file_paths = \\\n self.dataset.batch(self.batch_size).make_one_shot_iterator().get_next()\n\n def get_next_batch(self):\n return self.next_audio_batch, self.next_id_batch, self.next_file_paths\n\n def txt_one_hot_encoding(self, character):\n return self.txt_one_hot_table[self.reverse_dict[character]]\n\n def id_encode(self, id):\n return self.id_one_hot_table[self.reverse_id_dict[id]]\n\n def id_decode(self, one_hot):\n return self.id_dict[int(np.argmax(one_hot))]\n\n def get_char_dict(self):\n return self.char_dict\n\n def get_id_dict(self):\n return self.id_dict\n\n def get_id_cardinality(self):\n return len(self.id_dict)\n\n def generate_audio_from_one_hot(self, one_hot):\n print(\"not implemented\")\n\n\n", "sub_path": "dataset_loader.py", "file_name": "dataset_loader.py", "file_ext": "py", "file_size_in_byte": 8578, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "os.walk", "line_number": 39, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path", "line_number": 41, "usage_type": "attribute"}, {"api_name": "numpy.eye", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.eye", "line_number": 125, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 130, "usage_type": "call"}, {"api_name": "librosa.load", "line_number": 133, "usage_type": "call"}, {"api_name": "numpy.shape", "line_number": 137, "usage_type": "call"}, {"api_name": "numpy.pad", "line_number": 141, "usage_type": "call"}, {"api_name": "utils.audio_process.remove_silence", "line_number": 144, "usage_type": "call"}, {"api_name": "utils.audio_process", "line_number": 144, "usage_type": "name"}, {"api_name": "numpy.random.choice", "line_number": 150, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 150, "usage_type": "attribute"}, {"api_name": "librosa.load", "line_number": 158, "usage_type": "call"}, {"api_name": "utils.audio_process.quantization", "line_number": 160, "usage_type": "call"}, {"api_name": "utils.audio_process", "line_number": 160, "usage_type": "name"}, {"api_name": "utils.audio_process.audio_one_hot_encoding", "line_number": 164, "usage_type": "call"}, {"api_name": "utils.audio_process", "line_number": 164, "usage_type": "name"}, {"api_name": "numpy.asarray", "line_number": 180, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 181, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 182, "usage_type": "call"}, {"api_name": "tensorflow.data.Dataset.from_generator", "line_number": 185, "usage_type": "call"}, {"api_name": "tensorflow.data", "line_number": 185, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 187, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 188, "usage_type": "attribute"}, {"api_name": "tensorflow.string", "line_number": 189, "usage_type": "attribute"}, {"api_name": "tensorflow.TensorShape", "line_number": 190, "usage_type": "call"}, {"api_name": "tensorflow.TensorShape", "line_number": 191, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 206, "usage_type": "call"}]}
+{"seq_id": "98294964", "text": "import re\nimport requests\nfrom bs4 import BeautifulSoup\nfrom fake_useragent import UserAgent\nimport sqlite3\nimport random\n\nimport socket \nsocket.setdefaulttimeout(15)\n\ndef crawl():\n\tconn = sqlite3.connect('proxy.db')\n\tcs = conn.cursor()\n\tcs.execute('''\n\t\tcreate table if not exists proxy (\n\t\t\thost varchar(20),\n\t\t\tport varchar(10),\n\t\t\tproto varchar (10),\n\t\t\tunique(host, port, proto)\n\t\t)\n\t''')\n\txici(conn, cs)\n\tcn(conn, cs)\n\ndef xici(conn, cs):\n\t\n\tua = UserAgent().random\n\theaders = {'user-agent': ua}\n\trsp = requests.get('http://www.xicidaili.com/', headers=headers)\n\tif rsp.status_code == 200:\n\t\tprint(\"成功爬取西刺 !\")\n\t\n\tsoup = BeautifulSoup(rsp.text, 'html.parser')\n\tfor i in soup.find_all('tr', class_=\"subtitle\"):\n\t\ti.decompose()\n\t\t\n\ttrs = soup.find_all('tr', class_=re.compile(r'\\s*'))\n\tfor tr in trs:\n\t\ttds = tr.find_all('td')\n\t\thost = tds[1].text\n\t\tport = tds[2].text\n\t\tproto = tds[5].text\n\t\tif proto == 'socks4/5':\n\t\t\tcontinue\n\t\tcs.execute('insert or ignore into proxy(host, port, proto) values (?, ?, ?)',\n\t\t\t(host, port, proto))\n\t\tconn.commit()\n\t\n\t\ndef cn(conn, cs):\n\tua = UserAgent().random\n\theaders = {\"user-agent\": ua}\n\ttry:\n\t\tr = requests.get(\"http://cn-proxy.com/\", headers=headers, timeout=15)\n\texcept Exception:\n\t\tprint('无法翻墙,爬取 cn-proxy 失败!')\n\t\tcs.close()\n\t\tconn.close()\n\t\treturn\n\n\tif r.status_code == 200:\n\t\tprint(\"成功爬取 cn-proxy !\")\n\n\tsoup = BeautifulSoup(r.text, \"html.parser\")\n\n\tfor tbody in soup.find_all(\"tbody\"):\n\t\tfor tr in tbody.find_all(\"tr\"):\n\t\t\ttds = tr.find_all(\"td\")\n\t\t\thost = tds[0].text\n\t\t\tport = tds[1].text\n\t\t\tcs.execute(\n\t\t\t\t\"insert or ignore into proxy (host, port, proto) values (?, ?, ?)\", (host, port, 'http')\n\t\t\t)\n\t\t\tconn.commit()\n\n\tcs.close()\n\tconn.close()\n\n\t\ndef get():\n\tconn = sqlite3.connect(\"proxy.db\")\n\tcs = conn.cursor()\n\tcs.execute(\"select * from proxy\")\n\trecord = random.choice(cs.fetchall())\n\n\tproxies = {\n\t\t\"http\": \"{}://{}:{}\".format(record[2], record[0], record[1]),\n\t\t\"https\": \"{}://{}:{}\".format(record[2], record[0], record[1]),\n\t}\n\n\ttry:\n\t\tr = requests.get(\"https://www.baidu.com/\", proxies=proxies, timeout=15)\n\texcept Exception:\n\t\tcs.execute(\"delete from proxy where host=?\", (record[0],))\n\t\tconn.commit()\n\t\treturn get()\n\t\t\n\tcs.close()\n\tconn.close()\n\treturn proxies\n\t\nif __name__ == '__main__':\n\tcrawl()", "sub_path": "proxy.py", "file_name": "proxy.py", "file_ext": "py", "file_size_in_byte": 2300, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "socket.setdefaulttimeout", "line_number": 9, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 12, "usage_type": "call"}, {"api_name": "fake_useragent.UserAgent", "line_number": 27, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 29, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 33, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 37, "usage_type": "call"}, {"api_name": "fake_useragent.UserAgent", "line_number": 51, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 54, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 64, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 81, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 84, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 92, "usage_type": "call"}]}
+{"seq_id": "545117311", "text": "from keras.models import Model\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers.convolutional import Conv2D, ZeroPadding2D\nfrom keras.layers.pooling import MaxPooling2D, AveragePooling2D\nfrom keras.optimizers import Adam\nfrom keras.models import Sequential\nimport numpy\nimport pandas\nimport sys\n\n# build model\nmodel = Sequential()\nmodel.add(Conv2D(filters = 64, kernel_size=(5,5), padding = 'valid', input_shape = (48, 48, 1), activation='relu')) \nmodel.add(ZeroPadding2D(padding = (2, 2), data_format = 'channels_last'))\nmodel.add(MaxPooling2D(pool_size = (5, 5), strides = (2, 2)))\nmodel.add(ZeroPadding2D(padding = (1, 1), data_format = 'channels_last'))\nmodel.add(Conv2D(64, (3, 3), activation = 'relu'))\nmodel.add(ZeroPadding2D(padding = (1, 1), data_format = 'channels_last'))\nmodel.add(Conv2D(64, (3, 3), activation = 'relu'))\nmodel.add(AveragePooling2D(pool_size = (3, 3), strides=(2, 2)))\nmodel.add(ZeroPadding2D(padding = (1, 1), data_format = 'channels_last'))\nmodel.add(Conv2D(128, (3, 3), activation = 'relu'))\nmodel.add(ZeroPadding2D(padding = (1, 1), data_format = 'channels_last'))\nmodel.add(Conv2D(128, (3, 3), activation = 'relu'))\nmodel.add(ZeroPadding2D(padding = (1, 1), data_format = 'channels_last'))\nmodel.add(AveragePooling2D(pool_size = (3, 3), strides = (2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(1024, activation = 'relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1024, activation = 'relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(7, activation = 'softmax'))\nmodel.summary()\n\n# read in data and split data\nx_item = []\ntmp = pandas.read_csv(sys.argv[1], usecols=[1]).values.tolist()\nfor i in tmp:\n\tx_item.append(i[0].split(' '))\nx_item = numpy.array(x_item).reshape(-1,48,48,1)\ntmp = pandas.read_csv(sys.argv[1], usecols=[0])\ntmp = numpy.array(tmp)\ny_item = numpy.zeros((len(tmp), 7))\nfor i in range(0, len(tmp)):\n\ty_item[i][tmp[i][0]] = 1\n\n# set learning rate and crossentropy\nopt = Adam(lr = 0.00001)\nmodel.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])\nmodel.fit(x = x_item, y = y_item, epochs = 150, batch_size = 128)\n\n# save the model\nmodel.save('./model.h5') ", "sub_path": "CNN/train.py", "file_name": "train.py", "file_ext": "py", "file_size_in_byte": 2145, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "keras.models.Sequential", "line_number": 12, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.Conv2D", "line_number": 13, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.ZeroPadding2D", "line_number": 14, "usage_type": "call"}, {"api_name": "keras.layers.pooling.MaxPooling2D", "line_number": 15, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.ZeroPadding2D", "line_number": 16, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.Conv2D", "line_number": 17, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.ZeroPadding2D", "line_number": 18, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.Conv2D", "line_number": 19, "usage_type": "call"}, {"api_name": "keras.layers.pooling.AveragePooling2D", "line_number": 20, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.ZeroPadding2D", "line_number": 21, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.Conv2D", "line_number": 22, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.ZeroPadding2D", "line_number": 23, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.Conv2D", "line_number": 24, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.ZeroPadding2D", "line_number": 25, "usage_type": "call"}, {"api_name": "keras.layers.pooling.AveragePooling2D", "line_number": 26, "usage_type": "call"}, {"api_name": "keras.layers.Flatten", "line_number": 27, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 28, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 29, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 30, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 31, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 32, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 37, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 37, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 40, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 41, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 41, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 43, "usage_type": "call"}, {"api_name": "keras.optimizers.Adam", "line_number": 48, "usage_type": "call"}]}
+{"seq_id": "382694606", "text": "import xarray as xr\nimport pandas as pd\nimport numpy as np\nimport xskillscore as xs\n\nimport json\nimport cartopy.crs as ccrs\nimport matplotlib.pyplot as plt\n\nfrom S2S.local_configuration import config\nfrom S2S.graphics import latex, graphics\n\nfrom matplotlib.colors import BoundaryNorm\n\nfrom S2S.data_handler import ERA5, BarentsWatch\nfrom S2S.process import Hindcast, Observations, Grid2Point\nfrom S2S import models\nimport S2S.scoring as sc\n\ndef plus_minus_15_days(t_start,t_end):\n if t_start[1]==1:\n t_start = (t_start[0]-1,12,15)\n else:\n t_start = (t_start[0],t_start[1]-1,15)\n\n if t_end[1]==12:\n t_end = (t_end[0]+1,1,15)\n else:\n t_end = (t_end[0],t_end[1]+1,15)\n\n return t_start,t_end\n\n# bounds = (0,28,55,75)\nbounds = (0,28,55,75)\nvar = 'sst'\n\nclim_t_start = (2000,1,1)\nclim_t_end = (2021,1,4)\n\nsteps = pd.to_timedelta([9,16,23,30,37],'D')\n\nhigh_res = True\n\nmparser = {\n '1':'JAN','2':'FEB','3':'MAR',\n '4':'APR','5':'MAY','6':'JUN',\n '7':'JUL','8':'AUG','9':'SEP',\n '10':'OCT','11':'NOV','12':'DEC'\n }\nmonths = ['01','02','03','04','05','06','07','08','09','10','11','12']\n\nmae_fc, mae_clim, mae_pers = [], [], []\n################################################################################\nbw = BarentsWatch().load('all',no=0).sortby('time')[var]\n\nt_start = (2020,12,1) #can start with 8\nt_end = (2021,1,1)\nmodel = 'CY47R1'\n\nhh = Hindcast(\n var,\n (2020,1,23),\n (2020,1,24),\n bounds,\n high_res=high_res,\n steps=steps,\n process=False,\n download=False,\n split_work=False,\n )\nadd_month = hh.add_month\nsmaller_than = hh.smaller_than\ndel hh\n\n# assign new end time, one month after start time\nt_end = add_month(t_start)\n\n# until end time is reached; load one month at the time\nwhile smaller_than(t_end,(2021,4,1)):\n\n month = str(t_start[1])\n print(month)\n\n nk = []\n for loc in bw.location.values:\n\n fname = config['NORKYST'] +\\\n 'NorKyst800_' +\\\n str(loc) +\\\n '.nc'\n\n nk.append(xr.open_dataset(fname)[var].drop('radius'))\n nk = xr.concat(nk,'location')\n\n ts,te = plus_minus_15_days(t_start,t_end)\n hindcast = Hindcast(\n var,\n ts,\n te,\n bounds,\n high_res = high_res,\n steps = steps,\n process = True,\n download = False,\n split_work = False,\n period = [nk.time.min(),nk.time.max()]\n )\n print([nk.time.min(),nk.time.max()])\n # update times to the next month\n t_start = t_end\n t_end = add_month(t_end)\n\n observations = Observations(\n name='NorKyst-800',\n observations=nk,\n forecast=hindcast,\n process=True\n )\n del nk\n\n hindcast = Grid2Point(observations,hindcast)\\\n .correlation(step_dependent=True)\n\n mae_fc = xs.mae(\n hindcast.data_a.mean('member'),\n observations.data_a,\n dim=[]\n )\n\n mae_fc = mae_fc.where(mae_fc.time.dt.month==int(month),drop=True)\\\n .mean('time',skipna=True)\n\n crps_fc = sc.crps_ensemble(observations.data_a,hindcast.data_a)\n\n crps_fc = crps_fc.where(crps_fc.time.dt.month==int(month),drop=True)\\\n .mean('time',skipna=True)\n\n crps_clim = xs.crps_gaussian(\n observations.data_a,\n xr.zeros_like(observations.data_a),\n xr.ones_like(observations.data_a),\n dim=[]\n )\n\n crps_clim = crps_clim.where(crps_clim.time.dt.month==int(month),drop=True)\\\n .mean('time',skipna=True)\n\n del hindcast\n\n pers = models.persistence(\n init_value = observations.init_a,\n observations = observations.data_a\n )\n\n mae_pers = xs.mae(\n pers,\n observations.data_a,\n dim=[]\n )\n\n mae_pers = mae_pers.where(mae_pers.time.dt.month==int(month),drop=True)\\\n .mean('time',skipna=True)\n\n del pers\n\n mae_clim = xs.mae(\n xr.zeros_like(observations.data_a),\n observations.data_a,\n dim=[]\n )\n\n mae_clim = mae_clim.where(mae_clim.time.dt.month==int(month),drop=True)\\\n .mean('time',skipna=True)\n\n del observations\n\n for step in steps:\n\n for ref_fc,lab in zip([mae_clim,mae_pers],['CLIM','PERS']):\n\n latex.set_style(style='white')\n fig,ax = plt.subplots(1,1,\\\n figsize=latex.set_size(width=345,subplots=(1,1),fraction=0.95),\\\n subplot_kw=dict(projection=ccrs.NorthPolarStereo()))\n\n ss = ( 1 - mae_fc/ref_fc ).sel(step=step)\n\n cmap = latex.skill_cmap().reversed()\n levels = np.arange(-1.,1.05,0.05)\n norm = BoundaryNorm(levels,cmap.N)\n\n cs = ax.scatter(\n ss.lon.values,\n ss.lat.values,\n c=ss.values,\n s=1.1,\n cmap=cmap,\n norm=norm,\n alpha=0.95,\n transform=ccrs.PlateCarree()\n )\n ax.coastlines(resolution='10m', color='grey',\\\n linewidth=0.2)\n ax.set_title(mparser[month] + ' MAEss EC vs. '+lab+', NorKyst, lt:'\\\n +str(step.days))\n fig.colorbar(cs,ax=ax)\n graphics.save_fig(fig,\n model+'mae_skill_map_NorKyst_month'+month+lab+str(step.days)\n )\n\n latex.set_style(style='white')\n fig,ax = plt.subplots(1,1,\\\n figsize=latex.set_size(width=345,subplots=(1,1),fraction=0.95),\\\n subplot_kw=dict(projection=ccrs.NorthPolarStereo()))\n\n ss = ( 1 - crps_fc/crps_clim ).sel(step=step)\n\n cmap = latex.skill_cmap().reversed()\n levels = np.arange(-1.,1.05,0.05)\n norm = BoundaryNorm(levels,cmap.N)\n\n cs = ax.scatter(\n ss.lon.values,\n ss.lat.values,\n c=ss.values,\n s=1.1,\n cmap=cmap,\n norm=norm,\n alpha=0.95,\n transform=ccrs.PlateCarree()\n )\n ax.coastlines(resolution='10m', color='grey',\\\n linewidth=0.2)\n ax.set_title(mparser[month] + ' CRPss EC vs. CLIM, NorKyst, lt:'\\\n +str(step.days))\n fig.colorbar(cs,ax=ax)\n graphics.save_fig(fig,\n model+'crps_skill_map_NorKyst_month'+month+'CLIM'+str(step.days)\n )\n", "sub_path": "scripts/Henrik/skill_on_norkyst_CY47R1.py", "file_name": "skill_on_norkyst_CY47R1.py", "file_ext": "py", "file_size_in_byte": 7655, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "pandas.to_timedelta", "line_number": 40, "usage_type": "call"}, {"api_name": "S2S.data_handler.BarentsWatch", "line_number": 54, "usage_type": "call"}, {"api_name": "S2S.process.Hindcast", "line_number": 60, "usage_type": "call"}, {"api_name": "S2S.local_configuration.config", "line_number": 87, "usage_type": "name"}, {"api_name": "xarray.open_dataset", "line_number": 92, "usage_type": "call"}, {"api_name": "xarray.concat", "line_number": 93, "usage_type": "call"}, {"api_name": "S2S.process.Hindcast", "line_number": 96, "usage_type": "call"}, {"api_name": "S2S.process.Observations", "line_number": 113, "usage_type": "call"}, {"api_name": "S2S.process.Grid2Point", "line_number": 121, "usage_type": "call"}, {"api_name": "xskillscore.mae", "line_number": 124, "usage_type": "call"}, {"api_name": "S2S.scoring.crps_ensemble", "line_number": 133, "usage_type": "call"}, {"api_name": "S2S.scoring", "line_number": 133, "usage_type": "name"}, {"api_name": "xskillscore.crps_gaussian", "line_number": 138, "usage_type": "call"}, {"api_name": "xarray.zeros_like", "line_number": 140, "usage_type": "call"}, {"api_name": "xarray.ones_like", "line_number": 141, "usage_type": "call"}, {"api_name": "S2S.models.persistence", "line_number": 150, "usage_type": "call"}, {"api_name": "S2S.models", "line_number": 150, "usage_type": "name"}, {"api_name": "xskillscore.mae", "line_number": 155, "usage_type": "call"}, {"api_name": "xskillscore.mae", "line_number": 166, "usage_type": "call"}, {"api_name": "xarray.zeros_like", "line_number": 167, "usage_type": "call"}, {"api_name": "S2S.graphics.latex.set_style", "line_number": 181, "usage_type": "call"}, {"api_name": "S2S.graphics.latex", "line_number": 181, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 182, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 182, "usage_type": "name"}, {"api_name": "S2S.graphics.latex.set_size", "line_number": 183, "usage_type": "call"}, {"api_name": "S2S.graphics.latex", "line_number": 183, "usage_type": "name"}, {"api_name": "cartopy.crs.NorthPolarStereo", "line_number": 184, "usage_type": "call"}, {"api_name": "cartopy.crs", "line_number": 184, "usage_type": "name"}, {"api_name": "S2S.graphics.latex.skill_cmap", "line_number": 188, "usage_type": "call"}, {"api_name": "S2S.graphics.latex", "line_number": 188, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 189, "usage_type": "call"}, {"api_name": "matplotlib.colors.BoundaryNorm", "line_number": 190, "usage_type": "call"}, {"api_name": "cartopy.crs.PlateCarree", "line_number": 200, "usage_type": "call"}, {"api_name": "cartopy.crs", "line_number": 200, "usage_type": "name"}, {"api_name": "S2S.graphics.graphics.save_fig", "line_number": 207, "usage_type": "call"}, {"api_name": "S2S.graphics.graphics", "line_number": 207, "usage_type": "name"}, {"api_name": "S2S.graphics.latex.set_style", "line_number": 211, "usage_type": "call"}, {"api_name": "S2S.graphics.latex", "line_number": 211, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 212, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 212, "usage_type": "name"}, {"api_name": "S2S.graphics.latex.set_size", "line_number": 213, "usage_type": "call"}, {"api_name": "S2S.graphics.latex", "line_number": 213, "usage_type": "name"}, {"api_name": "cartopy.crs.NorthPolarStereo", "line_number": 214, "usage_type": "call"}, {"api_name": "cartopy.crs", "line_number": 214, "usage_type": "name"}, {"api_name": "S2S.graphics.latex.skill_cmap", "line_number": 218, "usage_type": "call"}, {"api_name": "S2S.graphics.latex", "line_number": 218, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 219, "usage_type": "call"}, {"api_name": "matplotlib.colors.BoundaryNorm", "line_number": 220, "usage_type": "call"}, {"api_name": "cartopy.crs.PlateCarree", "line_number": 230, "usage_type": "call"}, {"api_name": "cartopy.crs", "line_number": 230, "usage_type": "name"}, {"api_name": "S2S.graphics.graphics.save_fig", "line_number": 237, "usage_type": "call"}, {"api_name": "S2S.graphics.graphics", "line_number": 237, "usage_type": "name"}]}
+{"seq_id": "309319049", "text": "import sys\nfrom setuptools import setup, find_packages\n\ninstall_requires = ['requests']\nif sys.version_info < (3, 4):\n install_requires.append('enum34')\n\nsetup(\n name = 'netbluemind4',\n packages = find_packages(),\n version = '4.1.48893',\n description = 'Automatically generated client for BlueMind >= 4 REST API. Check netbluemind for older releases',\n author = 'BlueMind team',\n author_email = 'contact@bluemind.net',\n url = 'http://git.blue-mind.net/bluemind/',\n keywords = ['bluemind', 'rest', 'api', 'mail', 'groupware'],\n classifiers = [\n 'Development Status :: 5 - Production/Stable',\n 'Intended Audience :: Developers',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n ],\n install_requires=install_requires\n)\n", "sub_path": "pypi_install_script/netbluemind4-4.1.48893.tar/setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 814, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "sys.version_info", "line_number": 5, "usage_type": "attribute"}, {"api_name": "setuptools.setup", "line_number": 8, "usage_type": "call"}, {"api_name": "setuptools.find_packages", "line_number": 10, "usage_type": "call"}]}
+{"seq_id": "456025787", "text": "from typing import List\n\nclass Solution:\n def minPathSum(self, grid: List[List[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n dp = [[0 for _ in range(n)] for _ in range(m)]\n # Handle corner cases\n dp[0][0] = grid[0][0]\n if m == 1 and n > 1:\n for i in range(1, n):\n dp[0][i] = dp[0][i-1] + grid[0][i]\n \n elif n == 1 and m > 1:\n for i in range(1, m):\n dp[i][0] = dp[i-1][0] + grid[i][0]\n\n elif n > 1 and m > 1:\n # Handle boundary cases\n for i in range(1, n):\n dp[0][i] = dp[0][i-1] + grid[0][i]\n for i in range(1, m):\n dp[i][0] = dp[i-1][0] + grid[i][0]\n # DP\n for i in range(1, m):\n for j in range(1,n):\n dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]\n return dp[-1][-1]\n\nif __name__==\"__main__\":\n solution = Solution()\n grid = [[1,2,3],[4,5,6]]\n print(solution.minPathSum(grid=grid))", "sub_path": "leetcode/64_minimum_path_sum.py", "file_name": "64_minimum_path_sum.py", "file_ext": "py", "file_size_in_byte": 1047, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "typing.List", "line_number": 4, "usage_type": "name"}]}
+{"seq_id": "461938549", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 13 11:12:31 2019\n\n@author: Ankit\n\"\"\"\n\nimport json\nimport requests\nimport urllib.parse\nfrom pandas.io.json import json_normalize \nimport pandas as pd\nimport numpy as np\nimport copy\nfrom datetime import datetime\n\n#from flask import Flask , jsonify\n\n\n\nfrom aes256 import aes256\n\n#muffview\n\n \nclass Targetvalue:\n \n def ret(self , value,level,ulimit,llimit):\n \n value = int (value)\n level = int (level)\n ulimit = float(ulimit)\n llimit = float(llimit)\n #band = int(band)\n \n\n #url = \"https://er15.xyz:4436/api/Customers/GetCustDetailLabel?month=10&year=2019\"\n url = \"https://er15.xyz:4436/api/Customers/CRMLevelCustomerDetail?month=12&year=2019\"\n \n resp = requests.get(url)\n json_data = resp.json()\n \n if(json_data['Status'] =='OK'):\n redisAesKey = datetime.today().strftime('%Y%m%d') + \"1201\"\n jso = aes256().decrypt(json_data['Data'],redisAesKey)\n js = json.loads(jso)\n df = json_normalize(js)\n # df = df.loc[df['IsActive'] == True]\n \n # #json_data = requests.get(url).json()\n # json_data = resp.json()\n # df=json_normalize(json_data)\n \n \n #ACTIVE = df[(df.IsActive == True)]\n #INACTIVE = df[(df.IsActive == False)]\n #df=ACTIVE\n #print(df.head(2))\n df['SelfOrderPercentage']=((df['Selfordercount'])/(df['Selfordercount']+df['Salespersonordercount'])*100)\n df['SalesOrderPercentage']=(df['Salespersonordercount'])/(df['Selfordercount']+df['Salespersonordercount'])*100\n df.fillna(0)\n df = df.replace(np.NaN,0)\n df.rename(columns = {\"kkVolumn\":\"KKvolume\"},inplace = True)\n \n ###### LEVEL DEFINITIONS BEING DEFINED\n df.loc[df.Volume == 0, 'levels'] = 'Level 0'\n df.loc[df.Volume >= 1, 'levels'] = 'Level 1'\n df.loc[(df.Volume >= 10000) & (df.OrderCount >= 3) & (df.BrandCount >= 5), 'levels'] = 'Level 2'\n df.loc[(df.Volume >= 20000) & (df.OrderCount >= 5) & (df.BrandCount >= 10) & (df.KKvolume >= 2000), 'levels'] = 'Level 3'\n df.loc[(df.Volume >= 30000) & (df.OrderCount >= 8) & (df.BrandCount >= 20) & (df.KKvolume >= 8000) & ((df.Selfordercount/(df.Salespersonordercount+df.Selfordercount))*100 > 30), 'levels'] = 'Level 4'\n df.loc[(df.Volume >= 75000) & (df.OrderCount >= 12) & (df.BrandCount >= 40) & (df.KKvolume >= 15000) & ((df.Selfordercount/(df.Salespersonordercount+df.Selfordercount))*100 > 60), 'levels'] = 'Level 5'\n df.round(2)\n #\n l0=df[df['levels'] == 'Level 0']\n l1=df[df['levels'] == 'Level 1']\n l2=df[df['levels'] == 'Level 2']\n l3=df[df['levels'] == 'Level 3']\n l4=df[df['levels'] == 'Level 4']\n l5=df[df['levels'] == 'Level 5']\n \n \n \n l=[l0,l1,l2,l3,l4,l5]\n \n \n \n \n i=level\n \n if ( value == 0):\n l[i]['Target'] = 0\n \n # elif (value != 0 & percentage == 0):\n # l[i]['Target'] = [(int(j) + value) for j in l[i]['Volume']]\n \n else:\n \n l[i]['Target'] = [(int(j) + value) for j in l[i]['Volume']]\n \n \n l[i].sort_values(by='Volume', ascending=False)\n df1 = l[i][['SkCode','Cityid','WarehouseName','WarehouseId','levels','Volume','Target']]\n df1 = df1[(df1['Volume'] < ulimit) & (df1['Volume'] >= llimit) ]\n df1 = df1.sort_values(by='Volume', ascending=False)\n #df1['Band'] = band \n #df1= df1.to_json(orient='records')\n #df_list = df1.values.tolist()\n df1 = df1.to_dict('records')\n return df1\n \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "sub_path": "Targetvalue.py", "file_name": "Targetvalue.py", "file_ext": "py", "file_size_in_byte": 3861, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "requests.get", "line_number": 40, "usage_type": "call"}, {"api_name": "datetime.datetime.today", "line_number": 44, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 44, "usage_type": "name"}, {"api_name": "aes256.aes256", "line_number": 45, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 46, "usage_type": "call"}, {"api_name": "pandas.io.json.json_normalize", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.NaN", "line_number": 62, "usage_type": "attribute"}]}
+{"seq_id": "362913729", "text": "from tabulate import tabulate\n\njugadores = []\npuntajeParcial = [['1'],['2'],['3'],['4'],['5'],['6'],['E'],['F'],['P'],['G'],['GD'],['']]\n\ndef ingresoCantidadJug ():#Esta función es para obtener y retornar la cantidad de jugadores ingresada por el usuario.\n cantidad = int(input(\"Por favor, ingrese la cantidad de jugadores: \"))\n return cantidad\n\ndef ingresoNombres (cantidad):#Esta función sirva para agregar los nombres de los jugadores a la lista Vacía de jugadores\n for cantidad in range(0, cantidad):\n jugadores.append(input(\"Por favor ingrese nombre del jugador: \"))\n\ndef insertarColumnas (cantidad):#Sirve para agregar X cantidad de \"espacios\" agregando un 0 por cada jugador en cada \"Vagón\" de la lista puntajeParcial\n for t in range (0,cantidad):#Por ejemplo si ponemos 3 en cantidad se va a agregar 1 cero por iteración en los 12 vagones (de 1-6, E,F,P,G,GD y el espacio del resultado final)\n for posiciones in range (0,12):#Estos son los doce \"vagones\"\n puntajeParcial[posiciones].append(0)#acá agrega el valor 0 en el vagón X(cambia según la iteración)\n\ndef sumaPuntajeFinal(cantidad,puntajeParcial):# Se debe agregar esta función solo al final, porque si los valores están vacíos no se pueden sumar\n for nume in range(1, cantidad+1):# Debe estar completo el ingreso de los 11 valores por jugador, lo que no tenga completo se debe agregar 0\n resultado = ((puntajeParcial[0][nume])+(puntajeParcial[1][nume])+(puntajeParcial[2][nume])+\n (puntajeParcial[3][nume])+(puntajeParcial[4][nume])+(puntajeParcial[5][nume])+\n (puntajeParcial[6][nume])+(puntajeParcial[7][nume])+(puntajeParcial[8][nume])+\n (puntajeParcial[9][nume])+(puntajeParcial[10][nume]))\n puntajeParcial[11][nume] = (resultado)\n cadenaPuntaje =(\" PUNTAJE FINAL \")\n print(\"\\n\"+(cadenaPuntaje.center(50,\"=\")+\"\\n\"))\n mostrarPuntajeParcial()\n\ndef anotacion (nroJugador,categoria,puntos):#Esto es para ingresar los puntos, hay que cambiar las opciones a un diccionario para validar si hay un error de tipeo.\n #global categoria\n #global puntos\n #categoria = input(\"Ingrese categoria a anotar (Ingresando 1, 2, 3, 4, 5, 6, E, F, P, G, GD): \")\n #puntos = int(input(\"Ingrese cantidad de puntos obtenidos: \"))\n if categoria == 1:\n puntajeParcial[0][nroJugador] = puntos\n elif categoria == 2:\n puntajeParcial[1][nroJugador] = puntos\n elif categoria == 3:\n puntajeParcial[2][nroJugador] = puntos\n elif categoria == 4:\n puntajeParcial[3][nroJugador] = puntos\n elif categoria == 5:\n puntajeParcial[4][nroJugador] = puntos\n elif categoria == 6:\n puntajeParcial[5][nroJugador] = puntos\n elif categoria == 'E':\n puntajeParcial[6][nroJugador] = puntos\n elif categoria == 'F':\n puntajeParcial[7][nroJugador] = puntos\n elif categoria == 'P':\n puntajeParcial[8][nroJugador] = puntos\n elif categoria == 'G':\n puntajeParcial[9][nroJugador] = puntos\n elif categoria == 'GD':\n puntajeParcial[10][nroJugador] = puntos\n\ndef mostrarPuntajeParcial():#Esto muestra el tablero con los resultados parciales\n print(tabulate(puntajeParcial, jugadores))\n\ndef mostrarGanador (puntajeParcial,cantidad,jugadores):#Muestra que jugador ganó y con cuantos púntos\n listaPuntos = (puntajeParcial[11])\n soloPuntos = (puntajeParcial[11][1:])\n puntajeOrdenado = (sorted(soloPuntos,reverse=True))\n cadenaResultados = (\" RESULTADOS FINALES \")\n print(\"\\n\" + (cadenaResultados.center(50, \"*\") + \"\\n\"))\n for i in range(0,len(puntajeOrdenado)):\n ganador = (puntajeOrdenado[i])\n if ganador in listaPuntos:\n ordenGanadores = listaPuntos.index(ganador)\n print(\"En \", i + 1, \"puesto: \", (str(jugadores[ordenGanadores - 1])), \"con \", ganador, \"puntos\")\n", "sub_path": "tablero.py", "file_name": "tablero.py", "file_ext": "py", "file_size_in_byte": 3884, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "tabulate.tabulate", "line_number": 59, "usage_type": "call"}]}
+{"seq_id": "36259258", "text": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@File Name : PicPy\n@Author : LeeCQ\n@Date-Time : 2021/7/11 23:30\n\"\"\"\nfrom pathlib import Path\nfrom argparse import ArgumentParser\n\nfrom requests import post\n\n\ndef img_upload(file_path):\n _f = Path(file_path)\n files = {\"file\": (_f.name, _f.open('rb'), \"image/jpeg\")}\n return post('http://img.p.leecq.cn:8080/upload', files=files)\n\n\ndef args_from_cli():\n \"\"\"解析命令行参数\"\"\"\n p_args = ArgumentParser(description='Python图片上传接口')\n p_args.add_argument('file_path', help='文件的绝对路径')\n return p_args.parse_args()\n\n\ndef main():\n \"\"\"MAN\"\"\"\n _args = args_from_cli()\n _http = img_upload(_args.file_path)\n if _http.status_code == 200:\n return _http.text\n else:\n raise Exception(f'{_http.status_code}: {_http.text}')\n\n\nif __name__ == '__main__':\n print(main())\n", "sub_path": "client/PicPy.py", "file_name": "PicPy.py", "file_ext": "py", "file_size_in_byte": 886, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "pathlib.Path", "line_number": 15, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 17, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 22, "usage_type": "call"}]}
+{"seq_id": "434956878", "text": "__author__ = 'thor'\n\nfrom numpy import *\nimport numpy as np\nimport pandas as pd\nfrom collections import Counter, OrderedDict, defaultdict\nimport string\nimport random as rnd\nimport itertools\nfrom ut.util.uiter import all_subsets_of\n\nfrom ut.stats.bin_est.set_est import Shapley as Shapley_1\n\n# from ut.daf.manip import rollin_col\n\n\ndef compute_shapley_values_from_coalition_values(coalition_values, normalize=False):\n coalition_values = pd.DataFrame(index=coalition_values.keys(),\n data=coalition_values.values(),\n columns=['value'])\n se = Shapley_1(coalition_values, success='value')\n se.change_type_of_d_index(tuple)\n shapley_values = se.compute_shapley_values()\n if normalize:\n return _normalize_dict_values(shapley_values)\n else:\n return shapley_values\n\n\ndef _normalize_dict_values(d):\n value_sum = float(np.sum(d.values()))\n return {k: v / value_sum for k, v in d.items()}\n\n\ndef all_subsets_iterator(superset):\n return itertools.chain(\n *itertools.imap(lambda subset_size: itertools.combinations(superset, subset_size),\n range(1, len(superset))))\n\n\nclass ShapleyDataModel(object):\n def __init__(self, data=None, data_type=None):\n \"\"\"\n Inputs:\n * item_seperator will be used to construct string hashes from lists.\n You should choose a character that never shows up in the items, or you'll get problems.\n Other attributes:\n * coalition_obs is a Counter of coalitions\n * coalition_values is also a Counter of coalitions, but it counts not only\n the coalition_obs, but all non-empty subsets of the latter.\n \"\"\"\n self.coalition_obs = Counter()\n self.item_list = []\n self._coalition_size_map = None\n if data is not None:\n # if data_type not given, determine\n if data_type is None:\n if isinstance(data, Counter):\n data_type = 'coalition_obs'\n else:\n data_type = 'item_collections'\n\n # according to type, process and set data\n if data_type == 'coalition_obs':\n self.coalition_obs = data\n elif data_type == 'coalition_obs_collection':\n for d in data:\n self.absorb_coalition_obs(d)\n elif data_type == 'item_collections':\n for d in data:\n self.absorb_coalition(d)\n\n @staticmethod\n def coalition_of(iter_of_items):\n return tuple(unique(iter_of_items))\n\n def absorb_coalition(self, collection_of_items_of_single_coalition):\n \"\"\"\n Updates the self.coalition_obs with the input coalition (a list of items)\n \"\"\"\n self.coalition_obs.update([self.coalition_of(collection_of_items_of_single_coalition)])\n\n def absorb_coalition_obs(self, coalition_obs_dict):\n \"\"\"\n Updates the self.coalition_obs with the input dict of coalition: obs_value\n \"\"\"\n self.absorb_coalition_and_value(coalition_obs_dict.keys()[0], coalition_obs_dict.values()[0])\n\n def absorb_coalition_and_value(self, coalition, value):\n \"\"\"\n Updates the self.coalition_obs with the input dict of coalition: obs_value\n \"\"\"\n self.coalition_obs.update({self.coalition_of(coalition): value})\n\n def coalition_values(self, verbose=False):\n \"\"\"\n Computes the self.coalition_values attribute.\n To do this, we accumulate the counts of all subsets of each unique coalition.\n \"\"\"\n coalition_contributions = Counter(self.coalition_obs)\n\n if verbose:\n print(self.coalition_values)\n\n for coalition, count in self.coalition_obs.iteritems(): # for every coalition\n # ... get list corresponding to the key\n coalition = self._key_to_list(coalition)\n # ... get all non-empty strict subsets of this list, and assign the mother coalition count\n subset_counts = \\\n {self._list_to_key(sub_coalition): count\n for sub_coalition in all_subsets_iterator(coalition)}\n # ... update the coalition_values counter with these counts\n coalition_contributions.update(subset_counts)\n\n if verbose:\n print(\" after {} contributions:\\n {}\" \\\n .format(coalition, self.coalition_values))\n\n return coalition_contributions\n\n def coalition_size_map(self):\n if not self._coalition_size_map:\n self._coalition_size_map = defaultdict(dict)\n for coalition, count in self.coalition_obs.iteritems():\n self._coalition_size_map[len(coalition)].update({coalition: count})\n self._coalition_size_map = OrderedDict(sorted(self._coalition_size_map.items(), key=lambda t: t[0]))\n return self._coalition_size_map\n\n def mk_poset(self):\n d = defaultdict(list)\n _coalition_size_map = self.coalition_size_map()\n coalition_sizes = sorted(_coalition_size_map.keys())\n # TODO: Finish, if necessary\n\n def mk_item_list(self):\n self.item_list = unique(concatenate(self.coalition_obs.keys()))\n\n\ndef _test_shapley_data_model():\n list_of_coalitions = [['A', 'B', 'C'], ['A', 'C', 'B'], ['B', 'A', 'C'], ['A', 'A', 'B', 'C'],\n ['C', 'A'], ['B', 'C'], ['C', 'B'], ['C', 'B'], ['A']]\n dm = ShapleyDataModel() # initialize the data model\n\n for coalition in list_of_coalitions: # count the coalitions\n dm.absorb_coalition(coalition)\n assert dm.coalition_obs == Counter({('A', 'B', 'C'): 4, ('B', 'C'): 3, ('A',): 1, ('A', 'C'): 1}), \\\n \"Unexpected result for dm.coalition_obs\"\n\n\n print(\"All good in _test_shapley_data_model\")\n\n\ndef rand_shapley_values(items=3):\n if isinstance(items, int):\n items = ','.join(string.ascii_uppercase[:items]).split(',')\n if isinstance(items, list):\n items = {items[i]: 2**i for i in range(len(items))}\n return items\n\n\nclass LinearValuedCoalitionGenerator(object):\n def __init__(self, shapley_values=3, normalize=False):\n shapley_values = shapley_values or 3\n if not isinstance(shapley_values, dict):\n shapley_values = rand_shapley_values(items=shapley_values)\n self.shapley_values = shapley_values\n if normalize:\n self.shapley_values = _normalize_dict_values(self.shapley_values)\n\n @staticmethod\n def coalition_of(coalition):\n return tuple(sort(coalition))\n\n def coalition_value(self, coalition):\n return sum([self.shapley_values[item] for item in coalition])\n\n def rand_coalition(self):\n return self.coalition_of(rnd.sample(self.shapley_values.keys(), rnd.randint(1, len(self.shapley_values))))\n\n def rand_coalition_obs(self):\n coalition = self.rand_coalition()\n return {coalition: self.coalition_value(coalition)}\n\n def rand_coalition_obs_cum(self, n_draws=None):\n n_draws = n_draws or len(self.shapley_values) / 2\n coalition_obs = Counter()\n for x in itertools.starmap(self.rand_coalition_obs, itertools.repeat([], n_draws)):\n coalition_obs.update(x)\n return coalition_obs\n\n def coalition_values(self):\n return {self.coalition_of(coalition): self.coalition_value(coalition)\n for coalition in all_subsets_of(self.shapley_values.keys(), include_empty_set=False)}\n\n\n\n\n# class ShapleyDataModel_old(object):\n# def __init__(self, item_seperator=','):\n# \"\"\"\n# Inputs:\n# * item_seperator will be used to construct string hashes from lists.\n# You should choose a character that never shows up in the items, or you'll get problems.\n# Other attributes:\n# * coalition_obs is a Counter of coalitions\n# * coalition_values is also a Counter of coalitions, but it counts not only\n# the coalition_obs, but all non-empty subsets of the latter.\n# \"\"\"\n# self.coalition_obs = Counter()\n# self.coalition_values = None\n# self.item_seperator = item_seperator\n# self.contribution_df = None\n# self.item_list = []\n#\n# def absorb_coalition(self, coalition):\n# \"\"\"\n# Updates the self.coalition_obs with the input coalition (a list of items)\n# \"\"\"\n# self.coalition_obs.update([self._list_to_key(coalition)])\n#\n# def mk_coalition_size_map(self):\n#\n# d = defaultdict(list)\n# for coalition, count in self.coalition_obs.iteritems():\n# d[len(self._key_to_list(coalition))].append({coalition: count})\n# return d\n#\n# def mk_coalition_contributions(self, verbose=False):\n# \"\"\"\n# Computes the self.coalition_values attribute.\n# To do this, we accumulate the counts of all subsets of each unique coalition.\n# \"\"\"\n# # init with coalition_obs\n# self.coalition_values = Counter(self.coalition_obs)\n# if verbose:\n# print(self.coalition_values)\n# for coalition, count in self.coalition_obs.iteritems(): # for every coalition\n# # get list corresponding to the key\n# coalition = self._key_to_list(coalition)\n# # get all non-empty strict subsets of this list,\n# # and assign the mother coalition count\n# subset_counts = \\\n# {self._list_to_key(sub_coalition): count\n# for sub_coalition in all_subsets_iterator(coalition)}\n# # update the coalition_values counter with these counts\n# self.coalition_values.update(subset_counts)\n# if verbose:\n# print(\" after {} contributions:\\n {}\" \\\n# .format(coalition, self.coalition_values))\n#\n# def mk_item_list(self):\n# self.item_list = list(unique(self.item_seperator.join(dm.coalition_obs.keys()) \\\n# .split(self.item_seperator)))\n#\n# # def all_supersets_iterator(self, subset):\n#\n# # subset = dm\n#\n# def mk_contribution_df(self):\n# self._fill_counters()\n# self.contribution_df = \\\n# pd.DataFrame(index=self.coalition_values.keys(), columns=dm.item_list)\n# for coalition in self.contribution_df.index.values:\n# print self._remove_and_remain_dicts(coalition)\n# for rr in self._remove_and_remain_dicts(coalition):\n# # the contribution of each item is the total contribution\n# # minus what the contribution would be without this item\n# contribution = \\\n# self.coalition_values[coalition] \\\n# - self.coalition_values[rr['remaining']]\n# # enter this in the contribution_df\n# self.contribution_df.loc[coalition, rr['removed']] = contribution\n#\n# def _fill_counters(self):\n# \"\"\"\n# adds missing item combinations to counters, giving them 0 count\n# \"\"\"\n# self.mk_item_list()\n# zero_counts = {k: 0 for k in itertools.imap(self._list_to_key,\n# all_subsets_iterator(self.item_list))\n# }\n# self.coalition_obs.update(zero_counts)\n# self.coalition_values.update(zero_counts)\n#\n# def _list_to_key(self, coalition):\n# \"\"\"\n# Transforms a list of strings to a comma (or item_seperator) separated string\n# of unique items of the input list.\n# \"\"\"\n# return self.item_seperator.join(unique(coalition))\n#\n# def _key_to_list(self, coalition_key):\n# \"\"\"\n# Inverse of _list_to_key:\n# Returns a list from a character (item_seperator) seperated string of items.\n# \"\"\"\n# return coalition_key.split(self.item_seperator)\n#\n# def _remove_and_remain_dicts(self, superset):\n# \"\"\"\n# Returns a list of {removed, remaining} dicts listing all (keys of) superset - item\n# sets for every item in superset.\n# Returns an empty list if the input superset has only one element.\n# Example:\n# self._remove_and_remain_dicts('A,B,C')\n# returns\n# [{'remaining': 'B,C', 'removed': 'A'},\n# {'remaining': 'A,B', 'removed': 'C'},\n# {'remaining': 'A,C', 'removed': 'B'}]\n# \"\"\"\n# superset = set(self._key_to_list(superset))\n# if len(superset) > 1:\n# return [{'removed': x,\n# 'remaining': self._list_to_key(\n# list(superset.difference(x)))}\n# for x in superset]\n# else:\n# return list() # return empty list if superset has only one element\n#\n#\n# def _test_shapley_data_model():\n# list_of_coalitions = [['A', 'B', 'C'], ['A', 'C', 'B'], ['B', 'A', 'C'], ['A', 'A', 'B', 'C'],\n# ['C', 'A'], ['B', 'C'], ['C', 'B'], ['C', 'B'], ['A']]\n# dm = ShapleyDataModel_old() # initialize the data model\n#\n# for coalition in list_of_coalitions: # count the coalitions\n# dm.absorb_coalition(coalition)\n# assert dm.coalition_obs == Counter({'A,B,C': 4, 'B,C': 3, 'A': 1, 'A,C': 1}), \\\n# \"Unexpected result for dm.coalition_obs\"\n#\n# dm.mk_coalition_contributions()\n# assert dm.coalition_values \\\n# == Counter({'C': 8, 'B': 7, 'B,C': 7, 'A': 6, 'A,C': 5, 'A,B,C': 4, 'A,B': 4}), \\\n# \"Unexpected result for dm.coalition_values\"\n#\n# print(\"All good in _test_shapley_data_model\")\n", "sub_path": "stats/bin_est/shapley.py", "file_name": "shapley.py", "file_ext": "py", "file_size_in_byte": 13699, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "pandas.DataFrame", "line_number": 18, "usage_type": "call"}, {"api_name": "ut.stats.bin_est.set_est.Shapley", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 31, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 36, "usage_type": "call"}, {"api_name": "itertools.imap", "line_number": 37, "usage_type": "call"}, {"api_name": "itertools.combinations", "line_number": 37, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 52, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 58, "usage_type": "argument"}, {"api_name": "collections.Counter", "line_number": 100, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 123, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 126, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 130, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 146, "usage_type": "call"}, {"api_name": "string.ascii_uppercase", "line_number": 155, "usage_type": "attribute"}, {"api_name": "random.sample", "line_number": 178, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 178, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 186, "usage_type": "call"}, {"api_name": "itertools.starmap", "line_number": 187, "usage_type": "call"}, {"api_name": "itertools.repeat", "line_number": 187, "usage_type": "call"}, {"api_name": "ut.util.uiter.all_subsets_of", "line_number": 193, "usage_type": "call"}]}
+{"seq_id": "643197544", "text": "\"\"\" A class for testing a SSD model on a video file or webcam \"\"\"\nimport cv2\nfrom keras.applications.imagenet_utils import preprocess_input\nfrom keras.preprocessing import image\nimport numpy as np\nfrom model.ssd300MobileNet import SSD\nfrom model.utils.ssd_utils import BBoxUtility\nimport matplotlib.pyplot as plt\nfrom settings import *\nimport time\n\nclass MobileNetTest(object):\n \"\"\" Class for testing a trained SSD model on a video file and show the\n result in a window. Class is designed so that one VideoTest object\n can be created for a model, and the same object can then be used on\n multiple videos and webcams.\n\n Arguments:\n class_names: A list of strings, each containing the name of a class.\n The first name should be that of the background class\n which is not used.\n\n model: An SSD model. It should already be trained for\n images similar to the video to test on.\n\n input_shape: The shape that the model expects for its input,\n as a tuple, for example (300, 300, 3)\n\n bbox_util: An instance of the BBoxUtility class in ssd_utils.py\n The BBoxUtility needs to be instantiated with\n the same number of classes as the length of\n class_names.\n \"\"\"\n def __init__(self, class_names, weight_path, input_shape):\n self.class_names = class_names\n self.num_classes = len(class_names)\n self.input_shape = input_shape\n self.model = SSD(self.input_shape, num_classes=self.num_classes)\n self.model.load_weights(weight_path)\n self.model._make_predict_function()\n self.bbox_util = BBoxUtility(self.num_classes)\n\n # Create unique and somewhat visually distinguishable bright\n # colors for the different classes.\n self.class_colors = []\n for i in range(0, self.num_classes):\n # This can probably be written in a more elegant manner\n hue = 255 * i / self.num_classes\n col = np.zeros((1, 1, 3)).astype(\"uint8\")\n col[0][0][0] = hue\n col[0][0][1] = 128 # Saturation\n col[0][0][2] = 255 # Value\n cvcol = cv2.cvtColor(col, cv2.COLOR_HSV2BGR)\n col = (int(cvcol[0][0][0]), int(cvcol[0][0][1]), int(cvcol[0][0][2]))\n self.class_colors.append(col)\n\n def run(self, frame, frame_num, conf_thresh=0.6):\n \"\"\" Runs the test on a video (or webcam)\n\n # Arguments\n conf_thresh: Threshold of confidence. Any boxes with lower confidence\n are not visualized.\n \"\"\"\n output_list = list()\n im_size = (self.input_shape[0], self.input_shape[1])\n resized = cv2.resize(frame, im_size)\n orig_image = cv2.cvtColor(resized, cv2.COLOR_RGB2BGR)\n to_draw = resized\n\n # Use model to predict\n inputs = [image.img_to_array(orig_image)]\n tmp_inp = np.array(inputs)\n x = preprocess_input(tmp_inp)\n y = self.model.predict(x)\n results = self.bbox_util.detection_out(y)\n\n if len(results) > 0 and len(results[0]) > 0:\n # Interpret output, only one frame is used\n det_label = results[0][:, 0]\n det_conf = results[0][:, 1]\n det_xmin = results[0][:, 2]\n det_ymin = results[0][:, 3]\n det_xmax = results[0][:, 4]\n det_ymax = results[0][:, 5]\n\n top_indices = [i for i, conf in enumerate(det_conf) if conf >= conf_thresh]\n\n top_conf = det_conf[top_indices]\n top_label_indices = det_label[top_indices].tolist()\n top_xmin = det_xmin[top_indices]\n top_ymin = det_ymin[top_indices]\n top_xmax = det_xmax[top_indices]\n top_ymax = det_ymax[top_indices]\n\n output_list.append(frame_num)\n for i in range(top_conf.shape[0]):\n if (top_conf[i] < 0.9):\n continue\n xmin = int(round(top_xmin[i] * to_draw.shape[1]))\n ymin = int(round(top_ymin[i] * to_draw.shape[0]))\n xmax = int(round(top_xmax[i] * to_draw.shape[1]))\n ymax = int(round(top_ymax[i] * to_draw.shape[0]))\n\n # Draw the box on top of the to_draw image\n class_num = int(top_label_indices[i])\n cv2.rectangle(to_draw, (xmin, ymin), (xmax, ymax),\n self.class_colors[class_num], 2)\n text = self.class_names[class_num] + \" \" + ('%.2f' % top_conf[i])\n output_list.append(self.class_names[class_num])\n\n text_top = (xmin, ymin - 10)\n text_bot = (xmin + 80, ymin + 5)\n text_pos = (xmin + 5, ymin)\n cv2.rectangle(to_draw, text_top, text_bot, self.class_colors[class_num], -1)\n cv2.putText(to_draw, text, text_pos, cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 0), 1)\n\n cv2.imshow(\"SSD result\", to_draw)\n cv2.waitKey(10)\n\n def draw_fps(self, fps_time_slot):\n x_range = [index for index, value in enumerate(fps_time_slot)]\n y_fps = [value[1] for index, value in enumerate(fps_time_slot)]\n plt.ylim((0, 5))\n plt.plot(x_range, y_fps, c='r')\n plt.xlabel('time')\n plt.ylabel('fps')\n plt.show()\n\n\n", "sub_path": "mobilenettest.py", "file_name": "mobilenettest.py", "file_ext": "py", "file_size_in_byte": 5441, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "model.ssd300MobileNet.SSD", "line_number": 38, "usage_type": "call"}, {"api_name": "model.utils.ssd_utils.BBoxUtility", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 49, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 53, "usage_type": "call"}, {"api_name": "cv2.COLOR_HSV2BGR", "line_number": 53, "usage_type": "attribute"}, {"api_name": "cv2.resize", "line_number": 66, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 67, "usage_type": "call"}, {"api_name": "cv2.COLOR_RGB2BGR", "line_number": 67, "usage_type": "attribute"}, {"api_name": "keras.preprocessing.image.img_to_array", "line_number": 71, "usage_type": "call"}, {"api_name": "keras.preprocessing.image", "line_number": 71, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 72, "usage_type": "call"}, {"api_name": "keras.applications.imagenet_utils.preprocess_input", "line_number": 73, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 106, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 114, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 115, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 115, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 117, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 118, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 123, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 123, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 124, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 124, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 125, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 125, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "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"}]}
+{"seq_id": "56883559", "text": "#!/usr/bin/env python3\nfrom multiprocessing import Process, Value\nimport time\nimport sys\nimport xmlrpc.client\n\ndef call_rpc(errors, i, num):\n try:\n for j in range(0, num):\n s = xmlrpc.client.ServerProxy('https://localhost:8000')\n s.test(i)\n except Exception as Ex:\n errors.value += 1\n\ndef jobs_process(errors, process_n, num):\n for i in range(process_n):\n p = Process(target=call_rpc, args=(errors, i, num))\n p.start()\n\nif __name__ == '__main__':\n process_n, num_n = sys.argv[1:]\n errors = Value('i', 0)\n intprocess = int(process_n)\n num = int(num_n)\n start = time.time()\n jobs = Process(target=jobs_process, args=(errors, intprocess, num))\n jobs.start()\n jobs.join()\n took = time.time() - start\n print(\"Total jobs: %s\" % (process_n))\n print(\"RPC Errors: %s\" % (errors.value))\n print(\"Elapsed time: %s\" % (took))\n sys.exit(0)\n\n \n \n", "sub_path": "pileus-siml/OR/clientPerf2.py", "file_name": "clientPerf2.py", "file_ext": "py", "file_size_in_byte": 943, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "xmlrpc.client.client.ServerProxy", "line_number": 10, "usage_type": "call"}, {"api_name": "xmlrpc.client.client", "line_number": 10, "usage_type": "attribute"}, {"api_name": "xmlrpc.client", "line_number": 10, "usage_type": "name"}, {"api_name": "multiprocessing.Process", "line_number": 17, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 21, "usage_type": "attribute"}, {"api_name": "multiprocessing.Value", "line_number": 22, "usage_type": "call"}, {"api_name": "time.time", "line_number": 25, "usage_type": "call"}, {"api_name": "multiprocessing.Process", "line_number": 26, "usage_type": "call"}, {"api_name": "time.time", "line_number": 29, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 33, "usage_type": "call"}]}
+{"seq_id": "527266734", "text": "import matplotlib.pyplot as plt\nimport numpy as np\n\ndef read_file(filename):\n infile = open(filename,\"r\")\n first_line = infile.readline()\n if first_line[0] == \"|\":\n N = eval(first_line.split()[1][2:])\n epsilon_max = eval(first_line.split()[3][12:])\n epsilon_tot = eval(first_line.split()[5][12:])\n cpu_time = eval(first_line.split()[7][9:])\n log_10_h = eval(first_line.split()[9][10:])\n\n x = []; v = []; u = []\n infile.readline()\n for line in infile:\n inline = line.split()\n x.append(eval(inline[0]))\n v.append(eval(inline[1]))\n u.append(eval(inline[2]))\n if filename[7:10] == \"spe\":\n FLOPS = 7*N\n if filename[7:10] == \"gen\":\n FLOPS = N*11\n infile.close()\n return x,v,u,FLOPS,N,epsilon_max,epsilon_tot,cpu_time,log_10_h\n\n if first_line[0] == \"N\":\n N = []; epsilon_max = []; log_10_h = []; cpu_time = [];\n N.append(eval(first_line.split()[0][2:]))\n epsilon_max.append(eval(first_line.split()[1][12:]))\n log_10_h.append(eval(first_line.split()[2][10:]))\n cpu_time.append(eval(first_line.split()[3][9:]))\n for line in infile:\n N.append(eval(line.split()[0][2:]))\n epsilon_max.append(eval(line.split()[1][12:]))\n log_10_h.append(eval(line.split()[2][10:]))\n cpu_time.append(eval(line.split()[3][9:]))\n return N, epsilon_max, log_10_h, cpu_time\n\n\nfilenames_1 = [\"./data/genN10.txt\",\"./data/genN100.txt\",\"./data/genN1000.txt\",\\\n\"./data/speN10.txt\",\"./data/speN100.txt\",\"./data/speN1000.txt\"]\n\nfilenames_2 = [\"./data/gen_stats.txt\",\"./data/spe_stats.txt\"]\n\n\nfor filename in filenames_1:\n x,v,u,FLOPS,N,epsilon_max,epsilon_tot,cpu_time,log_10_h = read_file(filename)\n plt.xlabel(\"x\")\n plt.ylabel(\"u(x), v(x)\")\n\n plt.plot(x,v,label=r\"Numerical solution, $n={:}$ steps\".format(N))\n plt.plot(x,u,label=\"Analytic solution\")\n if filename[7:10] == \"spe\":\n type = \"Special algo\"\n if filename[7:10] == \"gen\":\n type = \"General algo\"\n #plt.title(r\"{:} $FLOPS={:}$\".format(type,FLOPS))\n plt.legend() ; plt.grid()\n argv = \"save\"\n if argv == \"plot\":\n plt.show()\n if argv == \"save\":\n plt.savefig(\"./figures/1b_{:}_{:}.png\".format(type[0:3],N))\n plt.clf()\n\nn_algos = []\ncpu_time_algos = []\nfor filename in filenames_2:\n N, epsilon_max, log_10_h, cpu_time = read_file(filename)\n cpu_time_algos.append(cpu_time)\n n_algos.append(N)\n plt.xlabel(r\"$log_{10}(h)$\")\n plt.ylabel(r\"$\\varepsilon$\")\n plt.plot(log_10_h,epsilon_max)\n if filename[7:10] == \"spe\":\n type = \"Special algo\"\n if filename[7:10] == \"gen\":\n type = \"General algo\"\n\n plt.title(\"{:}\".format(type))\n plt.grid(); #plt.legend()\n\n argv = \"save\"\n if argv == \"plot\":\n plt.show()\n if argv == \"save\":\n plt.savefig(\"./figures/1d_{:}_eps.png\".format(type[0:3]))\n plt.clf()\n\nfilenames = [\"./data/LU10.txt\",\"./data/LU100.txt\",\"./data/LU1000.txt\"]\ncpu_time_LU = []\nfor filename in filenames:\n infile = open(filename,\"r\")\n first_line = infile.readline().split()\n x = []; u = []; v = []\n for i in infile:\n line = i.split()\n x.append(eval(line[0]))\n v.append(eval(line[1]))\n u.append(eval(line[2]))\n cpu_time_LU.append(eval(first_line[-1][9:]))\n\n plt.plot(x,v,label=\"Numerical, n= {:}\".format(filename[9:11]))\n plt.plot(x,u,label=\"Analytic\")\n plt.xlabel(\"x\")\n plt.ylabel(\"u(x), v(x)\")\n plt.grid()\n plt.legend()\n plt.savefig(\"./figures/LU{:}.png\".format(len(x)-2))\n plt.clf()\n\nn = []\nfor i in range(1,8):\n n.append(int(i))\ncpu_time_gen = np.log10(cpu_time_algos[0])\ncpu_time_spe = np.log10(cpu_time_algos[1])\ncpu_time_LU = np.log10(cpu_time_LU)\n\nplt.plot(n,cpu_time_gen,label=\"General solution\")\nplt.plot(n,cpu_time_spe,label=\"Specialized solution\")\nplt.plot(n[0:3],cpu_time_LU,label=\"LU-decomposition\")\n\nplt.xlabel(\"n\")\nplt.ylabel(r\"$log_10$(CPU-time) [s]\")\nplt.xticks(ticks = n,labels=[r\"$10^1$\",r\"$10^2$\",r\"$10^3$\",r\"$10^4$\",r\"$10^5$\",r\"$10^6$\",r\"$10^7$\"])\nplt.legend()\nplt.savefig(\"./figures/CPU_times\")\nplt.clf()\n", "sub_path": "Project_1/reader.py", "file_name": "reader.py", "file_ext": "py", "file_size_in_byte": 4199, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "matplotlib.pyplot.xlabel", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 50, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "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.plot", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 54, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 60, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 60, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 60, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 63, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 63, "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.clf", "line_number": 66, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 66, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 74, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 74, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 75, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 75, "usage_type": "name"}, {"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.title", "line_number": 82, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 82, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 83, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 83, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 87, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 87, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 89, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 89, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 90, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 90, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 105, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 105, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 106, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 106, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 107, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 107, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 108, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 108, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 109, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 109, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 110, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 111, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 111, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 112, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 112, "usage_type": "name"}, {"api_name": "numpy.log10", "line_number": 117, "usage_type": "call"}, {"api_name": "numpy.log10", "line_number": 118, "usage_type": "call"}, {"api_name": "numpy.log10", "line_number": 119, "usage_type": "call"}, {"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.plot", "line_number": 123, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 123, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 125, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 125, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 126, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 126, "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.legend", "line_number": 128, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 128, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 129, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 129, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 130, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 130, "usage_type": "name"}]}
+{"seq_id": "239212899", "text": "# Copyright 2014-2020 Scalyr Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nBenchmarks which compare various compression algorithms.\n\nNOTE: We also want to measure CPU utilization for those benchmarks which means we should also run\nthem using \"time.process_time\" timer which contains sum of system and user CPU time and not wall\nclock time.\n\nThis way we get accurate CPU utilization information.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\n\nif False:\n from typing import Tuple\n from typing import Callable\n\nimport sys\nimport zlib\nimport bz2\nimport functools\n\nimport pytest\n\ntry:\n import snappy\nexcept ImportError:\n snappy = None\n\ntry:\n import zstandard\nexcept ImportError:\n zstandard = None\n\ntry:\n import brotli\nexcept ImportError:\n brotli = None\n\ntry:\n import lz4framed as lz4\nexcept ImportError:\n lz4 = None\n\n\nfrom .utils import read_bytes_from_log_fixture_file\nfrom .time_utils import process_time\n\n\n# fmt: off\n@pytest.mark.parametrize(\"log_tuple\",\n [\n (\"agent_debug_5_mb.log.gz\", 3 * 1024),\n (\"agent_debug_5_mb.log.gz\", 10 * 1024),\n (\"agent_debug_5_mb.log.gz\", 500 * 1024),\n (\"json_log_5_mb.log.gz\", 3 * 1024),\n (\"json_log_5_mb.log.gz\", 10 * 1024),\n (\"json_log_5_mb.log.gz\", 500 * 1024),\n (\"add_events_request_10_events.log.gz\", -1),\n (\"add_events_request_100_events.log.gz\", -1),\n (\"add_events_request_200_events.log.gz\", -1),\n (\"add_events_request_10_events_with_attributes.log.gz\", -1),\n (\"add_events_request_100_events_with_attributes.log.gz\", -1),\n (\"add_events_request_200_events_with_attributes.log.gz\", -1),\n ],\n ids=[\n \"agent_debug_log_3k\",\n \"agent_debug_log_10k\",\n \"agent_debug_log_500k\",\n \"json_log_3k\",\n \"json_log_10k\",\n \"json_log_500k\",\n \"add_events_10_events\",\n \"add_events_100_events\",\n \"add_events_200_events\",\n \"add_events_10_events_with_attributes\",\n \"add_events_100_events_with_attributes\",\n \"add_events_200_events_with_attributes\",\n ],\n)\n# fmt: on\n@pytest.mark.parametrize(\n \"compression_algorithm_tuple\",\n [\n (\"deflate\", {\"level\": 3}),\n (\"deflate\", {\"level\": 6}),\n (\"deflate\", {\"level\": 9}),\n (\"bz2\", {}),\n (\"snappy\", {}),\n (\"zstandard\", {\"level\": 3}),\n (\"zstandard\", {\"level\": 5}),\n (\"zstandard\", {\"level\": 10}),\n (\"zstandard\", {\"level\": 12}),\n (\"brotli\", {\"quality\": 3}),\n (\"brotli\", {\"quality\": 5}),\n (\"brotli\", {\"quality\": 8}),\n (\"lz4\", {}),\n ],\n ids=[\n \"deflate_level_3\",\n \"deflate_level_6_default\",\n \"deflate_level_9\",\n \"bz2\",\n \"snappy\",\n \"zstandard_level_3_default\",\n \"zstandard_level_5\",\n \"zstandard_level_10\",\n \"zstandard_level_12\",\n \"brotli_quality_3\",\n \"brotli_quality_5\",\n \"brotli_quality_8\",\n \"lz4\",\n ],\n)\n@pytest.mark.benchmark(group=\"compress\", timer=process_time)\ndef test_compress_bytes(benchmark, compression_algorithm_tuple, log_tuple):\n _test_compress_bytes(benchmark, compression_algorithm_tuple, log_tuple)\n\n\n# fmt: off\n@pytest.mark.parametrize(\"log_tuple\",\n [\n (\"agent_debug_5_mb.log.gz\", 3 * 1024),\n (\"agent_debug_5_mb.log.gz\", 10 * 1024),\n (\"agent_debug_5_mb.log.gz\", 500 * 1024),\n (\"json_log_5_mb.log.gz\", 3 * 1024),\n (\"json_log_5_mb.log.gz\", 10 * 1024),\n (\"json_log_5_mb.log.gz\", 500 * 1024),\n (\"add_events_request_10_events.log.gz\", -1),\n (\"add_events_request_100_events.log.gz\", -1),\n (\"add_events_request_200_events.log.gz\", -1),\n (\"add_events_request_10_events_with_attributes.log.gz\", -1),\n (\"add_events_request_100_events_with_attributes.log.gz\", -1),\n (\"add_events_request_200_events_with_attributes.log.gz\", -1),\n ],\n ids=[\n \"agent_debug_log_3k\",\n \"agent_debug_log_10k\",\n \"agent_debug_log_500k\",\n \"json_log_3k\",\n \"json_log_10k\",\n \"json_log_500k\",\n \"add_events_10_events\",\n \"add_events_100_events\",\n \"add_events_200_events\",\n \"add_events_10_events_with_attributes\",\n \"add_events_100_events_with_attributes\",\n \"add_events_200_events_with_attributes\",\n ],\n)\n@pytest.mark.parametrize(\"compression_algorithm_tuple\",\n [\n (\"deflate\", {\"level\": 3}),\n (\"deflate\", {\"level\": 6}),\n (\"deflate\", {\"level\": 9}),\n (\"bz2\", {}),\n (\"snappy\", {}),\n (\"zstandard\", {\"level\": 3}),\n (\"zstandard\", {\"level\": 5}),\n (\"zstandard\", {\"level\": 10}),\n (\"zstandard\", {\"level\": 12}),\n (\"brotli\", {\"quality\": 3}),\n (\"brotli\", {\"quality\": 5}),\n (\"brotli\", {\"quality\": 8}),\n (\"lz4\", {}),\n ],\n ids=[\n \"deflate_level_3\",\n \"deflate_level_6_default\",\n \"deflate_level_9\",\n \"bz2\",\n \"snappy\",\n \"zstandard_level_3_default\",\n \"zstandard_level_5\",\n \"zstandard_level_10\",\n \"zstandard_level_12\",\n \"brotli_quality_3\",\n \"brotli_quality_5\",\n \"brotli_quality_8\",\n \"lz4\",\n ],\n)\n# fmt: on\n@pytest.mark.benchmark(group=\"decompress\", timer=process_time)\ndef test_decompress_bytes(benchmark, compression_algorithm_tuple, log_tuple):\n _test_decompress_bytes(benchmark, compression_algorithm_tuple, log_tuple)\n\n\ndef _test_compress_bytes(benchmark, compression_algorithm_tuple, log_tuple):\n compression_algorithm, kwargs = compression_algorithm_tuple\n\n file_name, bytes_to_read = log_tuple\n data = read_bytes_from_log_fixture_file(file_name, bytes_to_read)\n\n compress_func, decompress_func = _get_compress_and_decompress_func(\n compression_algorithm, kwargs\n )\n\n def run_benchmark():\n # Work around for Python <= 3.6 where compress is not a keyword argument, but a regular argument\n if sys.version_info < (3, 6, 0) and compression_algorithm == \"deflate\":\n result = compress_func(data, kwargs[\"level\"])\n else:\n result = compress_func(data)\n return result\n\n result = benchmark.pedantic(run_benchmark, iterations=10, rounds=20)\n\n size_before_compression = len(data)\n size_after_compression = len(result)\n compression_ratio = float(size_before_compression) / size_after_compression\n\n benchmark.stats.size_before_compression = size_before_compression\n benchmark.stats.size_after_compression = size_after_compression\n benchmark.stats.stats.compression_ratio = compression_ratio\n\n assert result is not None\n # assert correctness\n assert size_after_compression < size_before_compression\n assert data == decompress_func(result)\n\n\ndef _test_decompress_bytes(benchmark, compression_algorithm_tuple, log_tuple):\n compression_algorithm, kwargs = compression_algorithm_tuple\n\n file_name, bytes_to_read = log_tuple\n data = read_bytes_from_log_fixture_file(file_name, bytes_to_read)\n\n compress_func, _ = _get_compress_and_decompress_func(compression_algorithm, kwargs)\n\n compressed_data = compress_func(data)\n assert compressed_data != data\n\n # NOTE: We intentionally request new decompression function so we get new zstandard context for\n # decompression (this way we avoid dictionary being already populated).\n _, decompress_func = _get_compress_and_decompress_func(\n compression_algorithm, kwargs\n )\n\n def run_benchmark():\n result = decompress_func(compressed_data)\n return result\n\n result = benchmark.pedantic(run_benchmark, iterations=10, rounds=20)\n\n size_before_decompression = len(compressed_data)\n size_after_decompression = len(result)\n\n assert result is not None\n # assert correctness\n assert result != compressed_data\n assert size_after_decompression > size_before_decompression\n assert data == result\n\n\ndef _get_compress_and_decompress_func(compression_algorithm, kwargs):\n # type: (str, dict) -> Tuple[Callable, Callable]\n if compression_algorithm == \"deflate\":\n if sys.version_info < (3, 6, 0):\n # Work around for Python <= 3.6 where compress is not a keyword argument, but a regular\n # argument\n compress_func = zlib.compress # type: ignore\n else:\n compress_func = functools.partial(zlib.compress, **kwargs) # type: ignore\n decompress_func = zlib.decompress # type: ignore\n elif compression_algorithm == \"bz2\":\n compress_func = functools.partial(bz2.compress, **kwargs) # type: ignore\n decompress_func = bz2.decompress # type: ignore\n elif compression_algorithm == \"snappy\":\n compress_func = functools.partial(snappy.compress, **kwargs) # type: ignore\n decompress_func = snappy.decompress # type: ignore\n elif compression_algorithm == \"zstandard\":\n compressor = zstandard.ZstdCompressor(**kwargs)\n decompressor = zstandard.ZstdDecompressor()\n compress_func = compressor.compress # type: ignore\n decompress_func = decompressor.decompress # type: ignore\n elif compression_algorithm == \"brotli\":\n compress_func = functools.partial(brotli.compress, **kwargs) # type: ignore\n decompress_func = brotli.decompress # type: ignore\n elif compression_algorithm == \"lz4\":\n compress_func = functools.partial(lz4.compress, **kwargs) # type: ignore\n decompress_func = lz4.decompress # type: ignore\n else:\n raise ValueError(\"Unsupported algorithm: %s\" % (compression_algorithm))\n\n return compress_func, decompress_func\n", "sub_path": "benchmarks/micro/test_compression_algorithms.py", "file_name": "test_compression_algorithms.py", "file_ext": "py", "file_size_in_byte": 10117, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "pytest.mark.parametrize", "line_number": 65, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 65, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 96, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 96, "usage_type": "attribute"}, {"api_name": "pytest.mark.benchmark", "line_number": 129, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 129, "usage_type": "attribute"}, {"api_name": "time_utils.process_time", "line_number": 129, "usage_type": "name"}, {"api_name": "pytest.mark.parametrize", "line_number": 135, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 135, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 165, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 165, "usage_type": "attribute"}, {"api_name": "pytest.mark.benchmark", "line_number": 198, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 198, "usage_type": "attribute"}, {"api_name": "time_utils.process_time", "line_number": 198, "usage_type": "name"}, {"api_name": "utils.read_bytes_from_log_fixture_file", "line_number": 207, "usage_type": "call"}, {"api_name": "sys.version_info", "line_number": 215, "usage_type": "attribute"}, {"api_name": "utils.read_bytes_from_log_fixture_file", "line_number": 241, "usage_type": "call"}, {"api_name": "sys.version_info", "line_number": 273, "usage_type": "attribute"}, {"api_name": "zlib.compress", "line_number": 276, "usage_type": "attribute"}, {"api_name": "functools.partial", "line_number": 278, "usage_type": "call"}, {"api_name": "zlib.compress", "line_number": 278, "usage_type": "attribute"}, {"api_name": "zlib.decompress", "line_number": 279, "usage_type": "attribute"}, {"api_name": "functools.partial", "line_number": 281, "usage_type": "call"}, {"api_name": "bz2.compress", "line_number": 281, "usage_type": "attribute"}, {"api_name": "bz2.decompress", "line_number": 282, "usage_type": "attribute"}, {"api_name": "functools.partial", "line_number": 284, "usage_type": "call"}, {"api_name": "snappy.compress", "line_number": 284, "usage_type": "attribute"}, {"api_name": "snappy.decompress", "line_number": 285, "usage_type": "attribute"}, {"api_name": "zstandard.ZstdCompressor", "line_number": 287, "usage_type": "call"}, {"api_name": "zstandard.ZstdDecompressor", "line_number": 288, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 292, "usage_type": "call"}, {"api_name": "brotli.compress", "line_number": 292, "usage_type": "attribute"}, {"api_name": "brotli.decompress", "line_number": 293, "usage_type": "attribute"}, {"api_name": "functools.partial", "line_number": 295, "usage_type": "call"}, {"api_name": "lz4framed.compress", "line_number": 295, "usage_type": "attribute"}, {"api_name": "lz4framed.decompress", "line_number": 296, "usage_type": "attribute"}]}
+{"seq_id": "202449053", "text": "class AppModel(models.Model):\n\n \"\"\"\n save时处理\n \"\"\"\n def create_thumbnail(self, image: ImageFieldFile):\n from PIL import Image\n from io import BytesIO\n from django.core.files.base import ContentFile\n thumbnail_size = 100, 120\n\n tiny_img = Image.open(image)\n tiny_img.thumbnail(thumbnail_size)\n tiny_img.save(image.file, format=tiny_img.format)\n f = BytesIO()\n tiny_img.save(f, format=tiny_img.format)\n image.save(image.name, ContentFile(f.getvalue()), save=False)\n\n\n\nclass DefectImageSerializer(serializers.ModelSerializer):\n\n def create(self, validated_data):\n create = super().create(validated_data)\n if not create.image:\n return create\n\n from PIL import Image\n from pathlib import Path\n from io import BytesIO\n thumbnail_size = 100, 120\n\n filepath = str(create.image.file)\n tiny_img = Image.open(filepath)\n tiny_img.thumbnail(thumbnail_size)\n\n file = Path(filepath)\n thumb_name = f'{file.stem}_thumbnail{file.suffix}'\n imgio = BytesIO()\n\n tiny_img.save(imgio, format=tiny_img.format)\n tiny_img.close()\n create.image_thumbnail.save(thumb_name, imgio)\n create.save()\n return create\n\n class Meta:\n model = models.DefectImage\n fields = '__all__'", "sub_path": "python_01/image/drf_image_create_thumbnail.py", "file_name": "drf_image_create_thumbnail.py", "file_ext": "py", "file_size_in_byte": 1380, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "PIL.Image.open", "line_number": 12, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 12, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 15, "usage_type": "call"}, {"api_name": "django.core.files.base.ContentFile", "line_number": 17, "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": "pathlib.Path", "line_number": 37, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 39, "usage_type": "call"}]}
+{"seq_id": "246925229", "text": "#importation des donnees order book en format json_data\n#construction d'une dataframe\n#rajout des colonnes volume total style somme execl\n#rajout d'une colonne detection des walls\n#enregistrement des donnees traitees dans data_treated.JSON\n\nimport json\nimport pandas as pd\nimport numpy as np\nimport sys\nimport os.path\nhomedir = os.path.expanduser(\"~\")\n################################################################################\n #fonctions\n################################################################################\n#lecture du fichier JSON\ndef dataquisition(data):\n with open(data) as json_data:\n data_dict = json.load(json_data)\n json_data.close()\n #transformation JSON en 2 dataframe\n bids = data_dict['bids']\n asks = data_dict['asks']\n #print(bids[1]['price'])\n listbids = []\n listasks = []\n\n #transformation en dictionnaire\n for bid in bids :\n listbids.append({'value' : float(bid['price']), 'bidsvolume' :float(bid['size'])})\n for ask in asks :\n listasks.append({'value' : float(ask['price']), 'asksvolume' :float(ask['size'])})\n\n #ajout de la liste de dicitonnaire dans les dataframes\n dfbids = pd.DataFrame(listbids)\n dfasks = pd.DataFrame(listasks)\n return [dfbids,dfasks]\n\n#calcul des volumes vente et achat\ndef calculVolumeGlobal (dfbids,dfasks):\n #calcul du volume global et detection des walls\n dfbids['bidstotalvolume'] = dfbids['bidsvolume'].cumsum(axis = 0)\n dfasks['askstotalvolume'] = dfasks['asksvolume'].cumsum(axis = 0)\n #le 0.1 correspond a 10% du volume global\n comparator = lambda x: 1000 if x>0.1 else 0\n\n\n askstotal = dfasks['askstotalvolume'].iloc[-1]\n dfasks['askswall'] = dfasks['asksvolume'].multiply(1/askstotal)\n dfasks['askswall'] = dfasks['askswall'].apply(comparator)\n\n bidstotal = dfbids['bidstotalvolume'].iloc[-1]\n dfbids['bidswall'] = dfbids['bidsvolume'].multiply(1/bidstotal)\n dfbids['bidswall'] = dfbids['bidswall'].apply(comparator)\n\n return [bidstotal, askstotal]\n#tendance\n #achat/vente/nondefini\ndef tendance (bidstotal,askstotal,seuilvente = 51,seuilachat = 51):\n TACHAT = 1\n TVENTE = 2\n TUNDEFINED = 3\n total = askstotal + bidstotal\n pourcentagevente = int(askstotal/total*100)\n pourcentageachat = int(bidstotal/total*100)\n\n _tendance = TUNDEFINED\n\n if pourcentagevente > seuilvente :\n _tendance = TVENTE\n if pourcentageachat > seuilachat and _tendance != TVENTE:\n _tendance = TACHAT\n\n return _tendance\n\n#filtreWall\ndef filtreWall(df,type):\n if (type == \"bids\"):\n dfbids_filtre = df.drop(df[df.bidswall == 1000].index)\n return dfbids_filtre\n if (type == \"asks\"):\n dfasks_filtre = df.drop(df[df.askswall == 1000].index)\n return dfasks_filtre\n else : print(\"erreur\")\n\n#placement_ordre\ndef placement_ordre(tendance,dfbids,dfasks):\n TACHAT = 1\n TVENTE = 2\n TUNDEFINED = 3\n\n def fAchat():\n dwall = dfbids.drop(dfbids[dfbids.bidswall != 1000].index)\n dwall = dwall.sort_values(by = 'value')\n if(dwall.empty):\n dwall = dfasks[\"value\"].iloc[-1]-0.00000001\n return[\"bid\",float(dwall)]\n else:\n #print dwall\n dwall = dwall[\"value\"].iloc[-1]\n return [\"bid\",float(dwall)-0.00000001]\n\n def fVente():\n #print(dfasks)\n dwall = dfasks.drop(dfasks[dfasks.askswall != 1000].index)\n\n if (dwall.empty):\n dwall = dfasks[\"value\"].iloc[0]+0.00000001\n return [\"ask\",float(dwall)]\n else:\n dwall = dwall.sort_values(by = 'value')\n dwall = dwall[\"value\"].iloc[0]\n return [\"ask\",float(dwall)+0.00000001]\n\n\n\n def fRien():\n return [\"undefined\",-1.0]\n\n switcher={\n TVENTE: fVente,\n TACHAT: fAchat,\n TUNDEFINED: fRien\n }\n func = switcher.get(tendance, lambda: \"argumentinvalide\")\n return func()\n\n################################################################################\n #programme\n################################################################################\nif __name__ == '__main__':\n import glob, os\n os.chdir(homedir+\"/server_crypto/orderbook_data/\")\n for file in glob.glob(\"*.json\"):\n timestamp = os.path.splitext(os.path.basename(file))[0]\n #aquisition des donnees\n [dfbids,dfasks] = dataquisition(file)\n #ajout des wall\n [askstotal,bidstotal] = calculVolumeGlobal(dfbids,dfasks)\n #print(dfbids)\n tendavantfiltrage = tendance(bidstotal,askstotal,50,50)\n #print(tendavantfiltrage)\n\n #filtrage des wall\n dfasks_filtre = filtreWall(dfasks,\"asks\")\n dfbids_filtre = filtreWall(dfbids,\"bids\")\n #tendance\n [askstotal_f,bidstotal_f] = calculVolumeGlobal(dfbids_filtre,dfasks_filtre)\n tendance_f = tendance(bidstotal_f,askstotal_f,50,50)\n\n #renvoi un tuple contenant l'action a executer (vendrvalorisation.pye/acheter/rien)\n #ainsi que prix a rentrer\n [_tendance, _prix] = placement_ordre(tendavantfiltrage,dfbids,dfasks)\n\n ##################################################################################\n #sauvegarde de l'algo\n\n import time\n now = int(time.time())\n date = now-now%60\n\n exists = os.path.isfile(homedir +'/server_crypto/data/algosignal_ws.json')\n def dataAlgo(_tendance,_prix):\n if exists:\n with open(homedir +'/server_crypto/data/algosignal_ws.json', 'r') as json_algo:\n algosignal = json.load(json_algo)\n algosignal[\"algosignal\"].append({\"tendance\":_tendance,\"prix\":_prix,\"time\":int(timestamp)})\n json_algo.close()\n algosignal[\"algosignal\"] = {frozenset(item.items()) : item for item in algosignal[\"algosignal\"]}.values()\n\n with open(homedir +'/server_crypto/data/algosignal_ws.json', 'w') as json_algo:\n json.dump(algosignal, json_algo)\n json_algo.close()\n #ajouter un element au fichier avec la date la tendnace et le prix\n else:\n with open(homedir +'/server_crypto/data/algosignal_ws.json', 'w') as json_algo:\n algosignal = {\"algosignal\":[{\"tendance\":_tendance,\"prix\":_prix,\"time\":int(timestamp)}]}\n json.dump(algosignal, json_algo)\n json_algo.close()\n\n def mergetlohcv():\n dates =[]\n match_tlohcv=[]\n with open(homedir +'/server_crypto/data/algosignal_ws.json', 'r') as data_lohcv:\n _signal = json.load(data_lohcv)\n for date in _signal[\"algosignal\"]:\n\n dates.append(int(date['time']))\n with open(homedir +'/server_crypto/data/data_received_tohlcv_ws.json', 'r') as data_lo:\n tlohc = json.load(data_lo)\n\n for ele in tlohc:\n\n if ele[\"time\"] in dates:\n match_tlohcv.append(ele)\n data_lo.close()\n data_lohcv.close()\n with open(homedir +'/server_crypto/data/algosignal_ws.json', 'w') as data_l:\n _signal[\"tohlcv\"] = match_tlohcv\n # match_tlohcv\n json.dump(_signal,data_l)\n\n ################################################################################\n dataAlgo(_tendance,_prix)\n mergetlohcv()\n #Affichage des donnees\n ################################################################################\n\n #concatenation de bids et asks + reindexage\n dfall = pd.concat([dfbids,dfasks],sort=False,ignore_index=True)\n dfall = dfall.sort_values(by=['value']).reset_index(drop = True).replace(0,value = np.nan)\n\n dfall_filtered = pd.concat([dfbids_filtre,dfasks_filtre],sort=False,ignore_index=True,)\n dfall_filtered = dfall_filtered.sort_values(by=['value']).reset_index(drop = True).replace(0,value = np.nan)\n #suppression des walls\n\n\n\n #dfall_filtered.to_json(homedir+\"/my-app/src/assets/data_treated_filtered.json\",orient = 'table',index = False)\n\n #dfall.to_json(homedir+\"/my-app/src/assets/data_treated.json\",orient = 'table',index = False)\n\n\n sys.exit()\n", "sub_path": "walldetection_websocket.py", "file_name": "walldetection_websocket.py", "file_ext": "py", "file_size_in_byte": 8485, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "os.path.path.expanduser", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 12, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 12, "usage_type": "name"}, {"api_name": "json.load", "line_number": 19, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 35, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 36, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 133, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 134, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 135, "usage_type": "call"}, {"api_name": "os.path", "line_number": 135, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 135, "usage_type": "call"}, {"api_name": "time.time", "line_number": 159, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 162, "usage_type": "call"}, {"api_name": "os.path", "line_number": 162, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 166, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 172, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 178, "usage_type": "call"}, {"api_name": "json.load", "line_number": 185, "usage_type": "call"}, {"api_name": "json.load", "line_number": 190, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 201, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 210, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 211, "usage_type": "attribute"}, {"api_name": "pandas.concat", "line_number": 213, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 214, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 224, "usage_type": "call"}]}
+{"seq_id": "112427530", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.optimize as op\nimport emcee\nimport corner\nimport yaml\nimport likelihood.uniform as l\nimport pickle\nimport utils as u\n\n# load MC samples, names of satellites\nsample = 'fritzplusMCs'\ntag = 'uniform_noMCsystem'\nMC_dwarfs = np.load('data/sampling/'+sample+'.npy')\nwith open('data/sampling/names_key.pkl', 'rb') as f:\n names = pickle.load(f)[sample]\nassert MC_dwarfs.shape[0] == len(names)\n\n\"\"\"\n# cut based on distances\ndists = MC_dwarfs[:,6,:]\ndists = np.median(dists, axis=1)\ninc = dists < 100\nMC_dwarfs = MC_dwarfs[inc]\n# \"\"\"\n\n\"\"\"\n# use satellites from Cautun & Frenk (2017)\ncautun = ['Sagittarius I', 'LMC', 'SMC', 'Draco I', 'Ursa Minor', 'Sculptor',\n 'Carina I', 'Fornax', 'Leo II', 'Leo I']\ncautun = np.array([names.index(sat) for sat in cautun])\nMC_dwarfs = MC_dwarfs[cautun]\n# \"\"\"\n\n# \"\"\"\n# ignore satellites by name\n# ignoresats = ['Horologium I', 'Carina II', 'Carina III', 'Hydrus I']\n# ignoresats = ['LMC', 'SMC']\nignoresats = ['Horologium I', 'Carina II', 'Carina III', 'Hydrus I', 'LMC',\n 'SMC']\nignore = [names.index(sat) for sat in ignoresats]\nMC_dwarfs = np.delete(MC_dwarfs, ignore, axis=0)\n# \"\"\"\n\n# data and covariances for each satellite\nMC_vels = MC_dwarfs[:,9:12,:]\nvels = np.mean(MC_vels, axis=2)\nvel_covs = np.array([np.cov(dwarf) for dwarf in MC_vels])\n\n# Initialize walkers by randomly sampling prior\nnwalkers = 100\np0 = l.sample_prior(nwalkers=nwalkers)\nndim = len(p0[0])\n\n# Set up and run MCMC\nsampler = emcee.EnsembleSampler(nwalkers, ndim, l.lnprob, args=(vels,vel_covs))\npos, prob, state = sampler.run_mcmc(p0, 500)\n\n# Look by eye at the burn-in\nstepnum = np.arange(0,500,1)+1\nstepnum = np.array([stepnum for i in range(nwalkers)])\nplt.plot(stepnum, sampler.chain[:,:,0]);\n\nprint(\"Mean acceptance fraction: {0:.3f}\"\n .format(np.mean(sampler.acceptance_fraction)))\n\n# if needed, reset and run chain for new sample\nsampler.reset()\npos, prob, state = sampler.run_mcmc(pos, 500)\n\n# Flatten the chain and remove burn-in\nburnin = 0\nsamples = sampler.chain[:, burnin:, :].reshape((-1, ndim))\n\n# Make corner plot\nfig = corner.corner(samples, labels=[r\"$v_r$\", r\"$v_\\theta$\", r\"$v_\\phi$\",\n r\"$\\sigma_r$\", r\"$\\sigma_\\theta$\", r\"$\\sigma_\\phi$\"],\n quantiles=[0.16, 0.5, 0.84],\n show_titles=True, title_kwargs={\"fontsize\": 12})\n\nfig.savefig('figures/cornerplots/'+tag+'.png', bbox_inches='tight')\nnp.save(u.SIM_DIR+'beta/mcmc/data/'+tag, samples)\n", "sub_path": "likelihood_uniform.py", "file_name": "likelihood_uniform.py", "file_ext": "py", "file_size_in_byte": 2533, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "numpy.load", "line_number": 14, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.delete", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.cov", "line_number": 48, "usage_type": "call"}, {"api_name": "likelihood.uniform.sample_prior", "line_number": 52, "usage_type": "call"}, {"api_name": "likelihood.uniform", "line_number": 52, "usage_type": "name"}, {"api_name": "emcee.EnsembleSampler", "line_number": 56, "usage_type": "call"}, {"api_name": "likelihood.uniform.lnprob", "line_number": 56, "usage_type": "attribute"}, {"api_name": "likelihood.uniform", "line_number": 56, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 61, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 62, "usage_type": "name"}, {"api_name": "numpy.mean", "line_number": 65, "usage_type": "call"}, {"api_name": "corner.corner", "line_number": 76, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 82, "usage_type": "call"}, {"api_name": "utils.SIM_DIR", "line_number": 82, "usage_type": "attribute"}]}
+{"seq_id": "501390061", "text": "import myread as load\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport cv2\r\nimport math as mt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nfrom scipy import ndimage\r\nimport filtertd as filt\r\nimport time\r\nimport peakutils\r\ndef getSymAngle(images):\r\n# output = load.xypt('data_dvslaser/bottle_wallet_phone.aedat')\r\n\r\n\t\r\n\tdisplayimages=[[0 for i in range(128)] for j in range(128)]\r\n\r\n\r\n\timages = ndimage.filters.median_filter(images,size = 3)\r\n\r\n\t# for i in range(128):\r\n\t# \tfor j in range(128):\r\n\t# \t\tdisplayimages[i][j]=images[127-i][j]\r\n\r\n\tfilteredimages=[[0 for i in range(128)] for j in range(128)]\r\n\tt1 = time.time()\r\n\tdistancetransformimage=ndimage.distance_transform_edt(np.logical_not(images))\r\n\tprint(time.time() - t1)\r\n\tsigma=5.0\r\n\tcomx=0.0\r\n\tcomy=0.0\r\n\ttotalevents=0\r\n\r\n\tfor i in range(128):\r\n\t\tfor j in range(128):\r\n\t\t\t# intensity=images[i][j]\r\n\t\t\tintensity= distancetransformimage[i][j]\r\n\t\t\tfilteredimages[i][j] = mt.exp(-(intensity/sigma)**2)\r\n\t\t\tcomx+=j*filteredimages[i][j]\r\n\t\t\tcomy+=i*filteredimages[i][j]\r\n\t\t\ttotalevents+=filteredimages[i][j]\r\n\r\n\tfilteredimages = np.array(filteredimages)\r\n\r\n\t# # for i in range(\r\n\r\n\tfor i in range(128):\r\n\t\tfor j in range(128):\r\n\t\t\tdisplayimages[i][j]=filteredimages[127-i][j]\r\n\r\n\r\n\t# for i in range(128):\r\n\t# \tfor j in range(128):\r\n\t# \t\tcomx+=j*filteredimages[i][j]\r\n\t# \t\tcomy+=i*filteredimages[i][j]\r\n\t# \t\ttotalevents+=filteredimages[i][j]\r\n\r\n\tcomx=mt.floor(comx/totalevents)\r\n\tcomy=mt.floor(comy/totalevents)\r\n\r\n\tS=[0 for i in range(36)]\r\n\tfor var in range(0,36):\r\n\t\ttheta=5*var\r\n\t\ttheta = 180-theta\r\n\t\tdenom=0\r\n\t\t# print(theta)\r\n\t\tfor i in range(128):\r\n\t\t\tfor j in range(128):\r\n\t\t\t\tp=i-comy\r\n\t\t\t\tq=j-comx\r\n\t\t\t\tradiantheta = theta*mt.pi/180\r\n\t\t\t\tnewx= 2*(comx+p*mt.sin(radiantheta)*mt.cos(radiantheta) + q*((mt.cos(radiantheta))**2)) - j\r\n\t\t\t\tnewy = 2*(comy+q*mt.sin(radiantheta)*mt.cos(radiantheta) + p*((mt.sin(radiantheta))**2)) - i\r\n\t\t\t\t\r\n\t\t\t\t# newx = (mt.cos(2*radiantheta)*i + mt.sin(2*radiantheta)*j) \r\n\t\t\t\t# newy = (mt.sin(2*radiantheta)*i - mt.cos(2*radiantheta)*j)\r\n\r\n\t\t\t\tnewx=int(newx)\r\n\t\t\t\tnewy=int(newy)\r\n\t\t\t\t# print(theta)\r\n\t\t\t\t# print(j,i)\r\n\t\t\t\t# print(newx,newy)\r\n\t\t\t\t# print(\"fwfe\")\r\n\r\n\t\t\t\tdenom += (filteredimages[i][j])**2\r\n\t\t\t\tif(newy>=0 and newy<128 and newx>=0 and newx<128):\r\n\t\t\t\t\t#print(filteredimages[i][j], \" \", filteredimages[newy][newx])\r\n\t\t\t\t\tS[var] += filteredimages[i][j]*filteredimages[newy][newx]\r\n\t\tS[var]=S[var]/denom\r\n\r\n\tS_Axis = []\r\n\tAngle = []\r\n\r\n\tprint(S)\r\n\thalf_length = int(((len(S)/2)-1))\r\n\r\n\tsnew = S+S[0:half_length]\r\n\tindexes = peakutils.indexes(snew, thres=0.05/max(snew))\r\n\r\n\tprint(indexes)\r\n\r\n\tfor idx in indexes:\r\n\t\tidx = idx % 36\r\n\t\tAngle.append(idx)\r\n\r\n\t# for i in range(0,36):\r\n\t# \tleft = S[i-1]\r\n\t# \tif (i == 35):\r\n\t# \t\tright = S[0]\r\n\t# \telse:\r\n\t# \t\tright = S[i+1]\r\n\t# \tif(S[i]>left and S[i]>right):\r\n\t# \t\tS_Axis.append(S[i])\r\n\t# \t\tAngle.append(i)\r\n\r\n\t# print(S)\r\n\r\n\t# sortedS = sorted(S_Axis)\r\n\t# largestS = sortedS[-1]\r\n\t# secondS = sortedS[-2]\r\n\t# # thirdS = sortedS[-3]\r\n\r\n\t# i1 = S_Axis.index(largestS)\r\n\t# i2 = S_Axis.index(secondS)\r\n\t# # i3 = S_Axis.index(thirdS)\r\n\r\n\t# print(\"First symmetry axis = \" , Angle[i1]*5)\r\n\t# print(\"Second symmetry axis = \", Angle[i2]*5)\r\n\t# print(\"Third symmetry axis = \", Angle[i3]*2)\r\n\r\n\r\n\t# displayimages= np.array(displayimages)\r\n\t# maxi =np.amax(displayimages)\r\n\t# # print(maxi)\r\n\t# displayimages= np.divide(displayimages,maxi)\r\n\t# cv2.namedWindow('image', cv2.WINDOW_NORMAL)\r\n\t# cv2.imshow('image', displayimages)\r\n\t# cv2.waitKey(0)\r\n\r\n\t# return(Angle[i1]*5, Angle[i2]*5)\r\n\r\n\twdk=[0 for i in range(len(Angle))]\r\n\tcounter=0\r\n\tfor var in Angle:\r\n\t\twk=[[0 for i in range(128)] for j in range(128)]\r\n\t\ttheta = 5*var\r\n\t\ttheta = 180 - theta\r\n\t\tfor i in range(128):\r\n\t\t\tfor j in range(128):\r\n\t\t\t\tp=i-comy\r\n\t\t\t\tq=j-comx\r\n\t\t\t\tradiantheta = theta*mt.pi/180\r\n\t\t\t\tnewx= 2*(comx+p*mt.sin(radiantheta)*mt.cos(radiantheta) + q*((mt.cos(radiantheta))**2)) - j\r\n\t\t\t\tnewy = 2*(comy+q*mt.sin(radiantheta)*mt.cos(radiantheta) + p*((mt.sin(radiantheta))**2)) - i\r\n\r\n\t\t\t\t# newx = (mt.cos(2*radiantheta)*i + mt.sin(2*radiantheta)*j) \r\n\t\t\t\t# newy = (mt.sin(2*radiantheta)*i - mt.cos(2*radiantheta)*j) \r\n\t\t\t\tnewx=int(newx)\r\n\t\t\t\tnewy=int(newy)\r\n\t\t\t\tif(newy>=0 and newy<128 and newx>=0 and newx<128):\r\n\t\t\t\t\twk[i][j]= filteredimages[i][j]*filteredimages[newy][newx]\r\n\r\n\t\twk = np.array(wk)\r\n\t\twk_disp = np.array(wk)\r\n\t\tmaxi =np.amax(wk_disp)\r\n\t\t# print(maxi)\r\n\t\twk_disp= np.divide(wk_disp,maxi)\r\n\t\tcv2.namedWindow('mirror', cv2.WINDOW_NORMAL)\r\n\t\tprint(theta)\r\n\t\tcv2.imshow('mirror', wk_disp)\r\n\t\tcv2.waitKey(0)\r\n\r\n\r\n\t\tdenom = 0\r\n\r\n\t\twk = cv2.Sobel(wk, cv2.CV_64F, 0, 1, ksize=3)\r\n\t\twk = np.abs(wk)\r\n\t\tfor y in range(128):\r\n\t\t\tfor x in range(128):\r\n\t\t\t\twkxy = wk[y][x]\r\n\t\t\t\tp = x - comx\r\n\t\t\t\tq = y - comy\r\n\t\t\t\tDist = np.abs((q-(p*mt.tan(radiantheta)))*mt.cos(radiantheta))\r\n\t\t\t\twdk[counter]+= Dist*wkxy\r\n\t\t\t\t# wdk[counter]+= wkxy*(y-x*mt.tan(radiantheta)+comx*mt.tan(radiantheta)-comy)/(1+(mt.tan(radiantheta))**2)\r\n\t\t\t\tdenom+=wkxy\r\n\t\twdk[counter]=wdk[counter]/(denom)\r\n\t\t# print(Angle[counter]*5, wdk[counter])\r\n\t\tcounter+=1\r\n\r\n\t# print(np.array(Angle)*5)\r\n\t# print(wdk)\r\n\r\n\r\n\r\n\r\n\t# wdk=[0 for i in range(len(maxima))]\r\n\t# counter=0\r\n\t# for var in maxima:\r\n\t# \ttheta=5*var\r\n\t# \tdenom=0\r\n\t# \tfor i in range(128):\r\n\t# \t\tfor j in range(128):\r\n\t# \t\t\twkxy = wk[i][j]\r\n\t# \t\t\twdk[counter]+= wkxy*(i-j*mt.tan(theta)+comx*mt.tan(theta)-comy)/(1+(mt.tan(theta))**2)\r\n\t# \t\t\tdenom+=wkxy\r\n\t# \twdk[counter]=wdk[counter]/denom\r\n\t# \tcounter+=1\r\n\r\n\t# print(\"hi\")\r\n\t# print(wdk)\r\n\r\n\r\n\tdisplayimages= np.array(filteredimages)\r\n\tmaxi =np.amax(filteredimages)\r\n\t# print(maxi)\r\n\tdisplayimages= np.divide(filteredimages,maxi)\r\n\tcv2.namedWindow('filtimage', cv2.WINDOW_NORMAL)\r\n\tcv2.imshow('filtimage', displayimages)\r\n\tcv2.waitKey(0)\r\n\r\n\tmin_dist = 100000\r\n\tmin_idx = -1\r\n\r\n\tprint(np.array(Angle) * 5)\r\n\tprint(wdk)\r\n\r\n\tfor i in range(len(wdk)):\r\n\t\tif (wdk[i] < min_dist):\r\n\t\t\tmin_dist = wdk[i]\r\n\t\t\tmin_idx = i\r\n\r\n\tprint(\"dist: \", min_dist, Angle[min_idx]*5)\r\n\treturn(Angle[min_idx]*5)\r\n\r\n\t\r\n", "sub_path": "VisionPickPlaceDemo/symmetry.py", "file_name": "symmetry.py", "file_ext": "py", "file_size_in_byte": 5997, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "scipy.ndimage.filters.median_filter", "line_number": 18, "usage_type": "call"}, {"api_name": "scipy.ndimage.filters", "line_number": 18, "usage_type": "attribute"}, {"api_name": "scipy.ndimage", "line_number": 18, "usage_type": "name"}, {"api_name": "time.time", "line_number": 25, "usage_type": "call"}, {"api_name": "scipy.ndimage.distance_transform_edt", "line_number": 26, "usage_type": "call"}, {"api_name": "scipy.ndimage", "line_number": 26, "usage_type": "name"}, {"api_name": "numpy.logical_not", "line_number": 26, "usage_type": "call"}, {"api_name": "time.time", "line_number": 27, "usage_type": "call"}, {"api_name": "math.exp", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 42, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 57, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 58, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 70, "usage_type": "attribute"}, {"api_name": "math.sin", "line_number": 71, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 71, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 72, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 72, "usage_type": "call"}, {"api_name": "peakutils.indexes", "line_number": 97, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 151, "usage_type": "attribute"}, {"api_name": "math.sin", "line_number": 152, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 152, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 153, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 153, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 162, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 163, "usage_type": "call"}, {"api_name": "numpy.amax", "line_number": 164, "usage_type": "call"}, {"api_name": "numpy.divide", "line_number": 166, "usage_type": "call"}, {"api_name": "cv2.namedWindow", "line_number": 167, "usage_type": "call"}, {"api_name": "cv2.WINDOW_NORMAL", "line_number": 167, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 169, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 170, "usage_type": "call"}, {"api_name": "cv2.Sobel", "line_number": 175, "usage_type": "call"}, {"api_name": "cv2.CV_64F", "line_number": 175, "usage_type": "attribute"}, {"api_name": "numpy.abs", "line_number": 176, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 182, "usage_type": "call"}, {"api_name": "math.tan", "line_number": 182, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 182, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 213, "usage_type": "call"}, {"api_name": "numpy.amax", "line_number": 214, "usage_type": "call"}, {"api_name": "numpy.divide", "line_number": 216, "usage_type": "call"}, {"api_name": "cv2.namedWindow", "line_number": 217, "usage_type": "call"}, {"api_name": "cv2.WINDOW_NORMAL", "line_number": 217, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 218, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 219, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 224, "usage_type": "call"}]}
+{"seq_id": "378034539", "text": "from numpy.random import seed\nseed(5)\nfrom tensorflow import set_random_seed\nset_random_seed(8)\n\n\nimport tensorflow as tf\nfrom keras.backend.tensorflow_backend import set_session\n#config = tf.ConfigProto()\n#config.gpu_options.per_process_gpu_memory_fraction = 1\n#set_session(tf.Session(config=config))\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nset_session(tf.Session(config=config))\n#import os\n#os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see issue #152\n#os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"\"\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\nfrom model import *\nfrom data import saveResult\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\nfrom PIL import Image\nimport keras as k\nfrom skimage import transform\nfrom loadImages import *\nimport operator\nfrom ctImageClass import *\n#os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\n\n#data_gen_args = dict(rotation_range=0.2,\n# width_shift_range=0.05,\n# height_shift_range=0.05,\n# shear_range=0.05,\n# zoom_range=0.05,\n# horizontal_flip=True,\n# fill_mode='nearest')\n\n\n\n#načtení všech obrázků ve složce\npathToImages = ['Q:\\Matula\\dataproKNS']\n \ndoYouWantToResizeImages = True\nnormalize = False\nres = (400, 400)\n\n\nimagesInArray = loadImages(pathToImages[0], normalize=normalize, imload=True, resize = doYouWantToResizeImages, size =res, train = True)\nmasksInArray = loadImages(pathToImages[0], normalize=normalize, maskload=True, resize = doYouWantToResizeImages, size =res, train = True)\nif len(pathToImages)>1:\n for path in pathToImages[1:]:\n imagesInArray = np.concatenate((imagesInArray ,loadImages(path, normalize=normalize, imload=True, resize = doYouWantToResizeImages, size=res, train = True)), axis = 0)\n masksInArray = np.concatenate((masksInArray, loadImages(path, normalize=normalize, maskload=True, resize = doYouWantToResizeImages, size=res, train = True)), axis = 0)\n \n\n \nwhitePixelCount = []\nfor i in range(0, len(masksInArray)):\n whitePixelCount.append(masksInArray[i].sum())\n#\nwhitePixelCount = sorted(enumerate(whitePixelCount), key=operator.itemgetter(1))\n#\nn = 2500\nmaxIndeces = [i[0] for i in whitePixelCount[len(whitePixelCount)-n-1: len(whitePixelCount)-1]]\npretrainMasks = []\npretrainIms = []\npretrainMasks = masksInArray[maxIndeces]\npretrainIms = imagesInArray[maxIndeces]\n\npretrainIms = np.expand_dims(pretrainIms, axis =3)\npretrainMasks = np.expand_dims(pretrainMasks, axis = 3)\n\n \n \nmasksInArray = np.expand_dims(masksInArray, axis =3)\nimagesInArray = np.expand_dims(imagesInArray, axis = 3)\n#myGene = trainGenerator(2,'data/membrane/train','image','label',data_gen_args,save_to_dir = None)\n#\nmodel = unet()\n#model_checkpoint = ModelCheckpoint('model_cartilage.hdf5', monitor='loss',verbose=1, save_best_only=True)\n#model.load_weights('weights_wo_green.h5')\n#model.fit_generator(myGene,steps_per_epoch=300,epochs=1,callbacks=[model_checkpoint])\n#tbCallBack = k.callbacks.TensorBoard(log_dir='./Graph', histogram_freq=0, write_graph=True, write_images=True)\n\n#from ctImageClass import *\n#\n#newmodel = imageDataGenerator(model=model, batchSize = 1)\n#newmodel.getPaths(pathToImages)\n#\n#newmodel.trainModel()\n\nmodel.fit(imagesInArray, masksInArray, epochs = 100, batch_size = 4)\n#model.save('pretrain.h5')\nmodel.save('jiriho_metaloartefakty.h5')\n\n#model = load_model('model_smarter_250e.h5')\npathToTestImages = ['Q:\\Matula\\pro_testy']\n\ntestImagesInArray = loadImages(pathToTestImages[0], normalize=normalize, imload=True, resize = doYouWantToResizeImages, size =res, test = True)\ntestMasksInArray = loadImages(pathToTestImages[0], normalize=normalize, maskload=True, resize = doYouWantToResizeImages, size =res, test = True)\nif len(pathToTestImages)>1:\n for path in pathToTestImages[1:]:\n testImagesInArray = np.concatenate((testImagesInArray ,loadImages(path, normalize=normalize, imload=True, resize = doYouWantToResizeImages, size=res, test = True)), axis = 0)\n testMasksInArray = np.concatenate((testMasksInArray, loadImages(path, normalize=normalize, maskload=True, resize = doYouWantToResizeImages, size=res, test = True)), axis = 0)\n\ntestMasksInArray = np.expand_dims(testMasksInArray, axis =3)\ntestImagesInArray = np.expand_dims(testImagesInArray, axis = 3)\n\nresults = model.predict(testImagesInArray,1,verbose=1)\nsaveResult(\"U:\\\\Skripty\\\\unet_code\\\\data\\\\membrane\\\\test_jiri3\",results)\n\n\n\n", "sub_path": "unet_code/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 4512, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "numpy.random.seed", "line_number": 2, "usage_type": "call"}, {"api_name": "tensorflow.set_random_seed", "line_number": 4, "usage_type": "call"}, {"api_name": "tensorflow.ConfigProto", "line_number": 13, "usage_type": "call"}, {"api_name": "keras.backend.tensorflow_backend.set_session", "line_number": 15, "usage_type": "call"}, {"api_name": "tensorflow.Session", "line_number": 15, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 20, "usage_type": "attribute"}, {"api_name": "operator.itemgetter", "line_number": 67, "usage_type": "call"}, {"api_name": "model.fit", "line_number": 98, "usage_type": "call"}, {"api_name": "model.save", "line_number": 100, "usage_type": "call"}, {"api_name": "model.predict", "line_number": 115, "usage_type": "call"}, {"api_name": "data.saveResult", "line_number": 116, "usage_type": "call"}]}
+{"seq_id": "487760786", "text": "from .producer import produceData\nfrom rest_framework.views import APIView\nfrom api.serializers import ProductSerializer\nfrom api.models import Product, User\nfrom rest_framework import viewsets\nfrom rest_framework.response import Response\nfrom rest_framework import status\nimport random\n# Create your views here.\n\nclass ProductViewSet(viewsets.ViewSet):\n def list(self,request):\n products= Product.objects.all()\n serializer=ProductSerializer(products,many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n \n def create(self,request):\n serializer=ProductSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n #producer\n produceData('product_created', serializer.data)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n \n def retrieve(self,request,pk=None):\n product= Product.objects.get(id=pk)\n serializer=ProductSerializer(product)\n return Response(serializer.data, status=status.HTTP_302_FOUND)\n \n def update(self,request,pk=None):\n product= Product.objects.get(id=pk)\n serializer=ProductSerializer(data=request.data, instance=product)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n #producer\n produceData('product_updated',serializer.data)\n return Response(serializer.data, status=status.HTTP_202_ACCEPTED)\n\n def destroy(self,request,pk=None):\n product= Product.objects.get(id=pk)\n product.delete()\n #producer\n produceData('product_deleted',pk)\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass UserApiView(APIView):\n def get(self,_):\n users= User.objects.all()\n user=random.choice(users)\n return Response({\n 'id':user.id\n })", "sub_path": "productapp/api/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1867, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "rest_framework.viewsets.ViewSet", "line_number": 11, "usage_type": "attribute"}, {"api_name": "rest_framework.viewsets", "line_number": 11, "usage_type": "name"}, {"api_name": "api.models.Product.objects.all", "line_number": 13, "usage_type": "call"}, {"api_name": "api.models.Product.objects", "line_number": 13, "usage_type": "attribute"}, {"api_name": "api.models.Product", "line_number": 13, "usage_type": "name"}, {"api_name": "api.serializers.ProductSerializer", "line_number": 14, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 15, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 15, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 15, "usage_type": "name"}, {"api_name": "api.serializers.ProductSerializer", "line_number": 18, "usage_type": "call"}, {"api_name": "producer.produceData", "line_number": 22, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 23, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "line_number": 23, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 23, "usage_type": "name"}, {"api_name": "api.models.Product.objects.get", "line_number": 26, "usage_type": "call"}, {"api_name": "api.models.Product.objects", "line_number": 26, "usage_type": "attribute"}, {"api_name": "api.models.Product", "line_number": 26, "usage_type": "name"}, {"api_name": "api.serializers.ProductSerializer", "line_number": 27, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 28, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_302_FOUND", "line_number": 28, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 28, "usage_type": "name"}, {"api_name": "api.models.Product.objects.get", "line_number": 31, "usage_type": "call"}, {"api_name": "api.models.Product.objects", "line_number": 31, "usage_type": "attribute"}, {"api_name": "api.models.Product", "line_number": 31, "usage_type": "name"}, {"api_name": "api.serializers.ProductSerializer", "line_number": 32, "usage_type": "call"}, {"api_name": "producer.produceData", "line_number": 36, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 37, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_202_ACCEPTED", "line_number": 37, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 37, "usage_type": "name"}, {"api_name": "api.models.Product.objects.get", "line_number": 40, "usage_type": "call"}, {"api_name": "api.models.Product.objects", "line_number": 40, "usage_type": "attribute"}, {"api_name": "api.models.Product", "line_number": 40, "usage_type": "name"}, {"api_name": "producer.produceData", "line_number": 43, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 44, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_204_NO_CONTENT", "line_number": 44, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 44, "usage_type": "name"}, {"api_name": "rest_framework.views.APIView", "line_number": 47, "usage_type": "name"}, {"api_name": "api.models.User.objects.all", "line_number": 49, "usage_type": "call"}, {"api_name": "api.models.User.objects", "line_number": 49, "usage_type": "attribute"}, {"api_name": "api.models.User", "line_number": 49, "usage_type": "name"}, {"api_name": "random.choice", "line_number": 50, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 51, "usage_type": "call"}]}
+{"seq_id": "616896778", "text": "from flask_swagger_ui import get_swaggerui_blueprint\nfrom flask import Flask\nfrom sqlalchemy import create_engine, MetaData\n\napp = Flask(__name__, instance_relative_config=True)\napp.config.from_pyfile('config.py')\n\n# swagger specific #\nSWAGGER_URL = '/swagger'\nAPI_URL = '/static/swagger.yaml'\nSWAGGERUI_BLUEPRINT = get_swaggerui_blueprint(\n SWAGGER_URL,\n API_URL,\n config={\n 'app_name': \"GENE-SEARCH-REST-API\"\n }\n)\napp.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL)\n# end swagger specific #\nconnection = \"mysql://{user}@{host}:{port}/{database}\".format(user=app.config['USER'], host=app.config['HOST'],\n port=app.config['PORT'], database=app.config['DATABASE'])\nengine = create_engine(connection)\nmetadata = MetaData(bind=engine)\nfrom app import views\n", "sub_path": "app/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 850, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "flask.Flask", "line_number": 5, "usage_type": "call"}, {"api_name": "flask_swagger_ui.get_swaggerui_blueprint", "line_number": 11, "usage_type": "call"}, {"api_name": "sqlalchemy.create_engine", "line_number": 22, "usage_type": "call"}, {"api_name": "sqlalchemy.MetaData", "line_number": 23, "usage_type": "call"}]}
+{"seq_id": "343842043", "text": "from argparse import ArgumentParser\nfrom collections import OrderedDict\nfrom copy import deepcopy\nfrom pprint import pformat\nfrom string import ascii_letters\nfrom typing import Any, Callable, Dict, List, Optional, Sequence, Set, Union\nimport json\nimport sys\nimport time\n\nfrom tap.utils import get_class_variables, get_dest, get_git_root, get_git_url, has_git,has_uncommitted_changes,\\\n is_option_arg, type_to_str\n\n\nSUPPORTED_DEFAULT_BASE_TYPES = {str, int, float, bool}\nSUPPORTED_DEFAULT_OPTIONAL_TYPES = {Optional[str], Optional[int], Optional[float]}\nSUPPORTED_DEFAULT_LIST_TYPES = {List[str], List[int], List[float]}\nSUPPORTED_DEFAULT_SET_TYPES = {Set[str], Set[int], Set[float]}\nSUPPORTED_DEFAULT_COLLECTION_TYPES = SUPPORTED_DEFAULT_LIST_TYPES | SUPPORTED_DEFAULT_SET_TYPES\nSUPPORTED_DEFAULT_TYPES = set.union(SUPPORTED_DEFAULT_BASE_TYPES,\n SUPPORTED_DEFAULT_OPTIONAL_TYPES,\n SUPPORTED_DEFAULT_COLLECTION_TYPES)\n\n\nclass Tap(ArgumentParser):\n \"\"\"Tap is a typed argument parser that wraps Python's built-in ArgumentParser.\"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"Initializes the Tap instance.\n\n :param args: Arguments passed to the super class ArgumentParser.\n :param kwargs: Keyword arguments passed to the super class ArgumentParser.\n \"\"\"\n # Whether the arguments have been parsed (i.e. if parse_args has been called)\n self._parsed = False\n\n # Set extra arguments to empty list\n self.extra_args = []\n\n # Create argument buffer\n self.argument_buffer = OrderedDict()\n\n # Get class variables help strings from the comments\n self.class_variables = self._get_class_variables()\n\n # Get annotations from self and all super classes up through tap\n self._annotations = self._get_annotations()\n\n # Initialize the super class, i.e. ArgumentParser\n super(Tap, self).__init__(*args, **kwargs)\n\n # Add arguments to self\n self.add_arguments() # Adds user-overridden arguments to the arguments buffer\n self._add_arguments() # Adds all arguments in order to self\n\n def _add_argument(self, *name_or_flags, **kwargs) -> None:\n \"\"\"Adds an argument to self (i.e. the super class ArgumentParser).\n\n Sets the following attributes of kwargs when not explicitly provided:\n - type: Set to the type annotation of the argument.\n - default: Set to the default value of the argument (if provided).\n - required: True if a default value of the argument is not provided, False otherwise.\n - action: Set to \"store_true\" if the argument is a required bool or a bool with default value False.\n Set to \"store_false\" if the argument is a bool with default value True.\n - nargs: Set to \"*\" if the type annotation is List[str], List[int], or List[float].\n - help: Set to the argument documentation from the class docstring.\n\n :param name_or_flags: Either a name or a list of option strings, e.g. foo or -f, --foo.\n :param kwargs: Keyword arguments.\n \"\"\"\n # Get variable name\n variable = get_dest(*name_or_flags, **kwargs)\n\n # Get default if not specified\n if hasattr(self, variable):\n kwargs['default'] = kwargs.get('default', getattr(self, variable))\n\n # Set required if option arg\n if is_option_arg(*name_or_flags) and variable != 'help':\n kwargs['required'] = kwargs.get('required', not hasattr(self, variable))\n\n\n if len(name_or_flags) == 1 and name_or_flags[0][:2] == \"--\":\n # expand attributes such that (\"--attribute\",) becomes (\"--attribute\", \"-a\")\n cvar_names = {n: None for n in self.class_variables}\n for long_name in self.class_variables:\n preferred_shorts = []\n for char in long_name:\n # collect eligible characters from long_name as preferred options\n if (\n char in ascii_letters\n and char not in preferred_shorts\n and not any([char == v for v in cvar_names.values() if v])\n ):\n preferred_shorts += char\n other_shorts = [\n asc\n for asc in ascii_letters\n if asc not in long_name and asc not in preferred_shorts\n ]\n for char in preferred_shorts + other_shorts:\n if char == \"h\":\n # avoiding \"h\" because it overlaps with default behavior of ArgumentParser.add_help\n continue\n if not any([char == v for v in set(cvar_names.values()) if v]):\n short_name = char\n break\n cvar_names[long_name] = short_name\n if cvar_names and name_or_flags[0][2:] in cvar_names:\n name_or_flags = (f\"{name_or_flags[0]}\", f\"-{cvar_names[name_or_flags[0][2:]]}\")\n\n # Set help if necessary\n if 'help' not in kwargs:\n kwargs['help'] = '('\n\n # Type\n if variable in self._annotations:\n kwargs['help'] += type_to_str(self._annotations[variable]) + ', '\n\n # Required/default\n if kwargs.get('required', False):\n kwargs['help'] += 'required'\n else:\n kwargs['help'] += f'default={kwargs.get(\"default\", None)}'\n\n kwargs['help'] += ')'\n\n # Description\n if variable in self.class_variables:\n kwargs['help'] += ' ' + self.class_variables[variable]['comment']\n\n # Set other kwargs where not provided\n if variable in self._annotations:\n # Get type annotation\n var_type = self._annotations[variable]\n\n # If type is not explicitly provided, set it if it's one of our supported default types\n if 'type' not in kwargs:\n if var_type not in SUPPORTED_DEFAULT_TYPES:\n raise ValueError(\n f'Variable \"{variable}\" has type \"{var_type}\" which is not supported by default.\\n'\n f'Please explicitly add the argument to the parser by writing:\\n\\n'\n f'def add_arguments(self) -> None:\\n'\n f' self.add_argument(\"--{variable}\", type=func, {\"required=True\" if kwargs[\"required\"] else f\"default={getattr(self, variable)}\"})\\n\\n'\n f'where \"func\" maps from str to {var_type}.')\n\n # If Optional type, extract type\n if var_type in SUPPORTED_DEFAULT_OPTIONAL_TYPES:\n var_type = var_type.__args__[0]\n\n # If List type, extract type of elements in list and set nargs\n elif var_type in SUPPORTED_DEFAULT_COLLECTION_TYPES:\n var_type = var_type.__args__[0]\n kwargs['nargs'] = kwargs.get('nargs', '*')\n\n # If bool then set action, otherwise set type\n if var_type == bool:\n kwargs['action'] = kwargs.get('action', f'store_{\"true\" if kwargs[\"required\"] or not kwargs[\"default\"] else \"false\"}')\n else:\n kwargs['type'] = var_type\n\n super(Tap, self).add_argument(*name_or_flags, **kwargs)\n\n def add_argument(self, *name_or_flags, **kwargs) -> None:\n \"\"\"Adds an argument to the argument buffer, which will later be passed to _add_argument.\"\"\"\n variable = get_dest(*name_or_flags, **kwargs)\n self.argument_buffer[variable] = (name_or_flags, kwargs)\n\n def _add_arguments(self) -> None:\n \"\"\"Add arguments to self in the order they are defined as class variables (so the help string is in order).\"\"\"\n # Add class variables (in order)\n for variable in self.class_variables:\n if variable in self.argument_buffer:\n name_or_flags, kwargs = self.argument_buffer[variable]\n self._add_argument(*name_or_flags, **kwargs)\n else:\n self._add_argument(f'--{variable}')\n\n # Add any arguments that were added manually in add_arguments but aren't class variables (in order)\n for variable, (name_or_flags, kwargs) in self.argument_buffer.items():\n if variable not in self.class_variables:\n self._add_argument(*name_or_flags, **kwargs)\n\n def add_arguments(self) -> None:\n \"\"\"Explicitly add arguments to the argument buffer if not using default settings.\"\"\"\n pass\n\n def process_args(self) -> None:\n \"\"\"Perform additional argument processing and/or validation.\"\"\"\n pass\n\n @staticmethod\n def get_reproducibility_info() -> Dict[str, str]:\n \"\"\"Gets a dictionary of reproducibility information.\n\n Reproducibility information always includes:\n - command_line: The command line command used to execute the code.\n - time: The current time.\n\n If git is installed, reproducibility information also includes:\n - git_root: The root of the git repo where the command is run.\n - git_url: The url of the current hash of the git repo where the command is run.\n Ex. https://github.com/swansonk14/rationale-alignment/tree/
\n - git_has_uncommitted_changes: Whether the current git repo has uncommitted changes.\n\n :return: A dictionary of reproducibility information.\n \"\"\"\n reproducibility = {\n 'command_line': f'python {\" \".join(sys.argv)}',\n 'time': time.strftime('%c')\n }\n\n if has_git():\n reproducibility['git_root'] = get_git_root()\n reproducibility['git_url'] = get_git_url(commit_hash=True)\n reproducibility['git_has_uncommitted_changes'] = has_uncommitted_changes()\n\n return reproducibility\n\n def _log_all(self) -> Dict[str, Any]:\n \"\"\"Gets all arguments along with reproducibility information.\n\n :return: A dictionary containing all arguments along with reproducibility information.\n \"\"\"\n arg_log = self.as_dict()\n arg_log['reproducibility'] = self.get_reproducibility_info()\n\n return arg_log\n\n def parse_args(self,\n args: Optional[Sequence[str]] = None,\n known_only: bool = False) -> 'Tap':\n \"\"\"Parses arguments, sets attributes of self equal to the parsed arguments, and processes arguments.\n\n :param args: List of strings to parse. The default is taken from `sys.argv`.\n :param known_only: If true, ignores extra arguments and only parses known arguments.\n Unparsed arguments are saved to self.extra_args.\n :return: self, which is a Tap instance containing all of the parsed args.\n \"\"\"\n # Parse args using super class ArgumentParser's parse_args or parse_known_args function\n if known_only:\n default_namespace, self.extra_args = super(Tap, self).parse_known_args(args)\n else:\n default_namespace = super(Tap, self).parse_args(args)\n\n # Copy parsed arguments to self\n for variable, value in vars(default_namespace).items():\n # Conversion from list to set\n if variable in self._annotations and self._annotations[variable] in SUPPORTED_DEFAULT_SET_TYPES:\n value = set(value)\n\n # Set variable in self (and deepcopy)\n setattr(self, variable, deepcopy(value))\n\n # Process args\n self.process_args()\n\n # Indicate that args have been parsed\n self._parsed = True\n\n return self\n\n @classmethod\n def _get_from_self_and_super(cls,\n extract_func: Callable[[type], dict],\n dict_type: type = dict) -> Union[Dict[str, Any], OrderedDict]:\n \"\"\"Returns a dictionary mapping variable names to values.\n\n Variables and values are extracted from classes using key starting\n with this class and traversing up the super classes up through Tap.\n\n If super class and sub class have the same key, the sub class value is used.\n\n Super classes are traversed through breadth first search.\n\n :param extract_func: A function that extracts from a class a dictionary mapping variables to values.\n :param dict_type: The type of dictionary to use (e.g. dict, OrderedDict, etc.)\n :return: A dictionary mapping variable names to values from the class dict.\n \"\"\"\n visited = set()\n super_classes = [cls]\n dictionary = dict_type()\n\n while len(super_classes) > 0:\n super_class = super_classes.pop(0)\n\n if super_class not in visited and issubclass(super_class, Tap):\n super_dictionary = extract_func(super_class)\n\n # Update only unseen variables to avoid overriding subclass values\n for variable, value in super_dictionary.items():\n if variable not in dictionary:\n dictionary[variable] = value\n for variable in super_dictionary.keys() - dictionary.keys():\n dictionary[variable] = super_dictionary[variable]\n\n super_classes += list(super_class.__bases__)\n visited.add(super_class)\n\n return dictionary\n\n def _get_class_dict(self) -> Dict[str, Any]:\n \"\"\"Returns a dictionary mapping class variable names to values from the class dict.\"\"\"\n class_dict = self._get_from_self_and_super(\n extract_func=lambda super_class: dict(getattr(super_class, '__dict__', dict()))\n )\n class_dict = {\n var: val\n for var, val in class_dict.items()\n if not (var.startswith('_') or callable(val) or isinstance(val, staticmethod))\n }\n\n return class_dict\n\n def _get_annotations(self) -> Dict[str, Any]:\n \"\"\"Returns a dictionary mapping variable names to their type annotations.\"\"\"\n return self._get_from_self_and_super(\n extract_func=lambda super_class: dict(getattr(super_class, '__annotations__', dict()))\n )\n\n def _get_class_variables(self) -> OrderedDict:\n \"\"\"Returns an OrderedDict mapping class variables names to their additional information.\"\"\"\n try:\n class_variables = self._get_from_self_and_super(\n extract_func=lambda super_class: get_class_variables(super_class),\n dict_type=OrderedDict\n )\n # Exception if inspect.getsource fails to extract the source code\n except Exception:\n class_variables = OrderedDict()\n for variable in self._get_class_dict().keys():\n class_variables[variable] = {'comment': ''}\n\n return class_variables\n\n def _get_argument_names(self) -> Set[str]:\n \"\"\"Returns a list of variable names corresponding to the arguments.\"\"\"\n return set(self._get_class_dict().keys()) | set(self._annotations.keys())\n\n def as_dict(self) -> Dict[str, Any]:\n \"\"\"Returns the member variables corresponding to the class variable arguments.\n\n :return: A dictionary mapping each argument's name to its value.\n \"\"\"\n if not self._parsed:\n raise ValueError('You should call `parse_args` before retrieving arguments.')\n\n return {var: getattr(self, var) for var in self._get_argument_names()}\n\n def save(self, path: str) -> None:\n \"\"\"Saves the arguments and reproducibility information in JSON format.\n\n :param path: Path to the JSON file where the arguments will be saved.\n \"\"\"\n with open(path, 'w') as f:\n json.dump(self._log_all(), f, indent=4, sort_keys=True)\n\n def __str__(self) -> str:\n \"\"\"Returns a string representation of self.\n\n :return: A formatted string representation of the instance's declaration\n \"\"\"\n keys = self._get_class_variables().keys()\n csv = \", \".join([f\"{k}={(vars(self)[k]).__repr__()}\" for k in keys])\n return f\"{self.__class__.__name__}({csv})\"\n", "sub_path": "tap/tap.py", "file_name": "tap.py", "file_ext": "py", "file_size_in_byte": 16228, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "typing.Optional", "line_number": 16, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 17, "usage_type": "name"}, {"api_name": "typing.Set", "line_number": 18, "usage_type": "name"}, {"api_name": "argparse.ArgumentParser", "line_number": 25, "usage_type": "name"}, {"api_name": "collections.OrderedDict", "line_number": 41, "usage_type": "call"}, {"api_name": "tap.utils.get_dest", "line_number": 72, "usage_type": "call"}, {"api_name": "tap.utils.is_option_arg", "line_number": 79, "usage_type": "call"}, {"api_name": "string.ascii_letters", "line_number": 91, "usage_type": "name"}, {"api_name": "string.ascii_letters", "line_number": 98, "usage_type": "name"}, {"api_name": "tap.utils.type_to_str", "line_number": 118, "usage_type": "call"}, {"api_name": "tap.utils.get_dest", "line_number": 166, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 209, "usage_type": "attribute"}, {"api_name": "time.strftime", "line_number": 210, "usage_type": "call"}, {"api_name": "tap.utils.has_git", "line_number": 213, "usage_type": "call"}, {"api_name": "tap.utils.get_git_root", "line_number": 214, "usage_type": "call"}, {"api_name": "tap.utils.get_git_url", "line_number": 215, "usage_type": "call"}, {"api_name": "tap.utils.has_uncommitted_changes", "line_number": 216, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 193, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 220, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 220, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 231, "usage_type": "name"}, {"api_name": "typing.Sequence", "line_number": 231, "usage_type": "name"}, {"api_name": "copy.deepcopy", "line_number": 253, "usage_type": "call"}, {"api_name": "typing.Callable", "line_number": 265, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 266, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 266, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 266, "usage_type": "name"}, {"api_name": "collections.OrderedDict", "line_number": 266, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 302, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 302, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 315, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 315, "usage_type": "name"}, {"api_name": "tap.utils.get_class_variables", "line_number": 325, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 326, "usage_type": "name"}, {"api_name": "collections.OrderedDict", "line_number": 330, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 321, "usage_type": "name"}, {"api_name": "typing.Set", "line_number": 336, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 340, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 340, "usage_type": "name"}, {"api_name": "json.dump", "line_number": 356, "usage_type": "call"}]}
+{"seq_id": "132057166", "text": "from airflow import DAG\nfrom datetime import datetime, timedelta\nfrom airflow.operators.python_operator import PythonOperator\n\nimport sys, os\nsys.path.append('../')\n\nimport data_query\nimport data_manipulation\n\ndefault_args = {\n 'owner': 'bi',\n 'depends_on_past': False,\n 'start_date': datetime(2019, 7, 16),\n 'retry_delay': timedelta(minutes=10)\n}\n\ndag = DAG(\n \"presto_data_test\",\n default_args=default_args,\n schedule_interval=\"@daily\"\n)\n\ndef query_data(**context):\n return data_query.return_df()\n\nquery_task = PythonOperator(\n task_id='query_task',\n python_callable=query_data,\n provide_context=True,\n dag=dag\n)\n\ndef show_data(**context):\n df = context[\"task_instance\"].xcom_pull(task_ids='query_task')\n data_manipulation.show_total_sum(df)\n\nprint_task = PythonOperator(\n task_id='print_task',\n python_callable=show_data,\n provide_context=True,\n dag=dag\n)\n\nquery_task >> print_task", "sub_path": "BACKUPS/python/airflow/airflow_presto_dag/dataframe_test.dag.py", "file_name": "dataframe_test.dag.py", "file_ext": "py", "file_size_in_byte": 937, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "sys.path.append", "line_number": 6, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 6, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 14, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 15, "usage_type": "call"}, {"api_name": "airflow.DAG", "line_number": 18, "usage_type": "call"}, {"api_name": "data_query.return_df", "line_number": 25, "usage_type": "call"}, {"api_name": "airflow.operators.python_operator.PythonOperator", "line_number": 27, "usage_type": "call"}, {"api_name": "data_manipulation.show_total_sum", "line_number": 36, "usage_type": "call"}, {"api_name": "airflow.operators.python_operator.PythonOperator", "line_number": 38, "usage_type": "call"}]}
+{"seq_id": "24654673", "text": "#!/usr/bin/env python\n\"\"\"\nInit a diffscuss-mb code review directory.\n\"\"\"\n\nfrom optparse import OptionParser\nimport os\nfrom textwrap import dedent\n\nfrom common import get_git_root, DIFFSCUSS_MB_FILE_NAME, \\\n USERS_DIR_NAME, REVIEWS_DIR_NAME, mkdir_for_keeps\n\n\ndef main(opts, args):\n git_root = get_git_root(opts.git_exe)\n os.chdir(git_root)\n\n dmb_root_dir = args[0]\n mkdir_for_keeps(dmb_root_dir)\n\n with open(DIFFSCUSS_MB_FILE_NAME, 'wb') as fil:\n fil.write(dmb_root_dir)\n\n users_dir = os.path.join(dmb_root_dir, USERS_DIR_NAME)\n mkdir_for_keeps(users_dir)\n\n reviews_dir = os.path.join(dmb_root_dir, REVIEWS_DIR_NAME)\n mkdir_for_keeps(reviews_dir)\n\nif __name__ == '__main__':\n parser = OptionParser(usage=dedent(\"\"\"\\\n %prog [options] diffscuss-mailbox-dir\n\n Init a diffscuss mailbox system. Must be run from\n within a git checkout.\n\n diffscuss-mailbox-dir is relative to the git root,\n and will be created.\n \"\"\"))\n parser.add_option(\"-g\", \"--git-exe\", dest=\"git_exe\", default=\"git\",\n help=dedent(\"\"\"\\\n Git exe (defaults to 'git'.\n \"\"\"))\n\n (opts, args) = parser.parse_args()\n if len(args) != 1:\n parser.error(\"Must provide exactly one diffscuss mailbox directory.\")\n main(opts, args)\n\n", "sub_path": "diffscuss-mb/dmb-init.py", "file_name": "dmb-init.py", "file_ext": "py", "file_size_in_byte": 1559, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "common.get_git_root", "line_number": 15, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 16, "usage_type": "call"}, {"api_name": "common.mkdir_for_keeps", "line_number": 19, "usage_type": "call"}, {"api_name": "common.DIFFSCUSS_MB_FILE_NAME", "line_number": 21, "usage_type": "argument"}, {"api_name": "os.path.join", "line_number": 24, "usage_type": "call"}, {"api_name": "common.USERS_DIR_NAME", "line_number": 24, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 24, "usage_type": "attribute"}, {"api_name": "common.mkdir_for_keeps", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 27, "usage_type": "call"}, {"api_name": "common.REVIEWS_DIR_NAME", "line_number": 27, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 27, "usage_type": "attribute"}, {"api_name": "common.mkdir_for_keeps", "line_number": 28, "usage_type": "call"}, {"api_name": "optparse.OptionParser", "line_number": 31, "usage_type": "call"}, {"api_name": "textwrap.dedent", "line_number": 31, "usage_type": "call"}, {"api_name": "textwrap.dedent", "line_number": 41, "usage_type": "call"}]}
+{"seq_id": "453879195", "text": "#!/usr/bin/python\n#求0—7所能组成的奇数个数\n\n#计算出组成数字的个数,再用set去重,再用x%2==1过滤出奇数\n\ns= [i for i in '01234567']\nimport itertools\narr = [] #数字总个数\nfor i in range(1,9):\n a = list(itertools.permutations(s,i))\n l = list(map(lambda x:int(''.join(x)),a))\n arr+=l\n print(i,len(l)) #输出组成的数字,不同位数的都有多少\narr1 = set(arr) #去重\narr2 = list(filter(lambda x:x%2==1,arr1)) #过滤奇数\nprint(len(arr),len(arr1),len(arr2))\n", "sub_path": "jishuzuhe.py", "file_name": "jishuzuhe.py", "file_ext": "py", "file_size_in_byte": 518, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "itertools.permutations", "line_number": 10, "usage_type": "call"}]}
+{"seq_id": "366771814", "text": "#############################################################################\r\n# #\r\n# Name: #\r\n# jointDuplicator.py #\r\n# #\r\n# Desc: #\r\n# Creates duplicate sets of joints with an attribute to control #\r\n# the blend. #\r\n# #\r\n# Author: #\r\n# Matt Jenkins #\r\n# #\r\n#############################################################################\r\n\r\n\r\nimport jointDuplicatorUI as customUI\r\nimport maya.OpenMayaUI as omUi\r\nimport maya.cmds as mc\r\nfrom functools import partial\r\n\r\ntry:\r\n from PySide import QtGui, QtCore\r\n import PySide.QtGui as QtWidgets\r\n from shiboken import wrapInstance\r\nexcept ImportError:\r\n from PySide2 import QtGui, QtCore, QtWidgets\r\n from shiboken2 import wrapInstance\r\n\r\n\r\ndef maya_main_window():\r\n main_window_ptr = omUi.MQtUtil.mainWindow()\r\n return wrapInstance(long(main_window_ptr), QtWidgets.QWidget)\r\n\r\ndef main():\r\n global myWindow\r\n global ctrlCrvBoxValue\r\n global suffixABoxValue\r\n global suffixBBoxValue\r\n global attrNameBoxValue\r\n global attrNiceNameBoxValue\r\n global curSuffixBoxValue\r\n global heirachyMode\r\n ctrlCrvBoxValue = None\r\n suffixABoxValue = 'IK'\r\n suffixBBoxValue = 'FK'\r\n attrNameBoxValue = 'IKFKSwitch'\r\n attrNiceNameBoxValue = 'IK / FK Switch'\r\n curSuffixBoxValue = 'result'\r\n heirachyMode = False\r\n\r\n try:\r\n myWindow.close()\r\n except: pass\r\n myWindow = myTool(parent=maya_main_window())\r\n myWindow.show()\r\n\r\n\r\nclass myTool(QtWidgets.QDialog):\r\n def __init__(self,parent = None):\r\n\r\n reload(customUI)\r\n print(\"loaded\")\r\n\r\n super(myTool, self).__init__(parent)\r\n self.setWindowFlags(QtCore.Qt.Tool)\r\n self.ui = customUI.Ui_MainWindow() #Define UI class in module\r\n\r\n self.ui.setupUi(self) # start window\r\n\r\n self.ui.ctrlCrvBox.textChanged.connect(self.updateCtrlCrvBox)\r\n self.ui.setCtrlCrvBtn.released.connect(self.updateCtrlCrvBtn)\r\n self.ui.createBtn.released.connect(self.updateCreateBtn)\r\n self.ui.modeSelRad.clicked.connect(partial(self.updateModeRad, 'modeSel'))\r\n self.ui.modeHeirRad.clicked.connect(partial(self.updateModeRad, 'modeHeir'))\r\n self.ui.suffixABox.textChanged.connect(self.updateSuffixABox)\r\n self.ui.suffixBBox.textChanged.connect(self.updateSuffixBBox)\r\n self.ui.attrNameBox.textChanged.connect(self.updateAttrNameBox)\r\n self.ui.attrNiceNameBox.textChanged.connect(self.updateAttrNiceNameBox)\r\n self.ui.curSuffixBox.textChanged.connect(self.updateCurSuffixBox)\r\n\r\n def updateSuffixABox(self, *args):\r\n global suffixABoxValue\r\n suffixABoxValue = self.ui.suffixABox.text()\r\n\r\n def updateSuffixBBox(self, *args):\r\n global suffixBBoxValue\r\n suffixBBoxValue = self.ui.suffixBBox.text()\r\n\r\n def updateAttrNameBox(self, *args):\r\n global attrNameBoxValue\r\n attrNameBoxValue = self.ui.attrNameBox.text()\r\n\r\n def updateAttrNiceNameBox(self, *args):\r\n global attrNiceNameBoxValue\r\n attrNiceNameBoxValue = self.ui.attrNiceNameBox.text()\r\n\r\n def updateCurSuffixBox(self, *args):\r\n global curSuffixBoxValue\r\n curSuffixBoxValue = self.ui.curSuffixBox.text()\r\n\r\n def updateCtrlCrvBox(self, *args):\r\n global ctrlCrvBoxValue\r\n ctrlCrvBoxValue = self.ui.ctrlCrvBox.text()\r\n if mc.objExists(ctrlCrvBoxValue):\r\n self.ui.ctrlCrvBox.setStyleSheet(\"background-color: rgb(90, 150, 50);\")\r\n else:\r\n self.ui.ctrlCrvBox.setStyleSheet(\"background-color: rgb(110, 90, 90);\")\r\n\r\n def updateCtrlCrvBtn(self, *args):\r\n crvSelection = mc.ls(sl=True)\r\n crvSelection = str(crvSelection)\r\n crvSelection = crvSelection.replace(\"[u'\",'')\r\n crvSelection = crvSelection.replace(\"']\",'')\r\n crvSelection = crvSelection.replace(\"[\",'')\r\n crvSelection = crvSelection.replace(\"]\",'')\r\n self.ui.ctrlCrvBox.setText(crvSelection)\r\n\r\n def updateModeRad(self, value, *args):\r\n global heirachyMode\r\n if value == 'modeSel':\r\n heirachyMode = False\r\n elif value == 'modeHeir':\r\n heirachyMode = True\r\n\r\n def updateCreateBtn(self, *args):\r\n self.createAttr()\r\n\r\n if heirachyMode:\r\n #-- Joint Hierachy Mode\r\n selJoints = mc.ls(sl=True, type='joint')\r\n\r\n if not selJoints:\r\n mc.confirmDialog(title='ERROR', message='Select valid Joint(s)', button=['Ok'])\r\n return\r\n\r\n for curjoint in selJoints:\r\n previousJoint=None\r\n jointTree = mc.listRelatives(curjoint, s=False, typ='joint', ad=True)\r\n jointTree.append(curjoint)\r\n jointTree.reverse()\r\n self.createJoints(jointTree)\r\n\r\n else:\r\n #-- Selected Joints Mode\r\n previousJoint=None\r\n selJoints = mc.ls(sl=True, type='joint')\r\n if not selJoints:\r\n mc.confirmDialog(title='ERROR', message='Select valid Joint(s)', button=['Ok'])\r\n return\r\n self.createJoints(selJoints)\r\n\r\n def createJoints(self, joints):\r\n #-- Set Suffix Values\r\n if not suffixABoxValue or not suffixBBoxValue:\r\n mc.confirmDialog(title='ERROR', message='Enter a valid suffix value', button=['Ok'])\r\n return\r\n suffixA = '_'+suffixABoxValue+'_'\r\n suffixB = '_'+suffixBBoxValue+'_'\r\n if not curSuffixBoxValue:\r\n mc.confirmDialog(title='ERROR', message='Enter a valid current suffix value', button=['Ok'])\r\n return\r\n curSuffix = '_'+curSuffixBoxValue+'_'\r\n\r\n #-- Main Code\r\n\r\n for x in joints:\r\n if curSuffix not in x:\r\n if '_JNT' not in x:\r\n mc.confirmDialog(title='ERROR', message='One or more incorrectly named Joints selected', button=['Ok'])\r\n return\r\n\r\n #-- Rename current Joint\r\n resultJointName = x.replace('_JNT', curSuffix+'JNT')\r\n if mc.objExists(resultJointName):\r\n mc.confirmDialog(title='ERROR', message='New Joint name already exists', button=['Ok'])\r\n return\r\n\r\n mc.rename(x,resultJointName)\r\n x=resultJointName\r\n\r\n #-- Names from current Joint\r\n blendSuffix = '_'+suffixABoxValue+suffixBBoxValue[:1].upper() + suffixBBoxValue[1:]\r\n ikJointName = x.replace(curSuffix, suffixA)\r\n fkJointName = x.replace(curSuffix, suffixB)\r\n blendRName = x.replace(curSuffix+'JNT', blendSuffix+'Rot_BLND')\r\n blendTName = x.replace(curSuffix+'JNT', blendSuffix+'Trans_BLND')\r\n blendSName = x.replace(curSuffix+'JNT', blendSuffix+'Scale_BLND')\r\n\r\n #-- Duplicate Joints\r\n if mc.objExists(ikJointName) or mc.objExists(fkJointName):\r\n mc.confirmDialog(title='ERROR', message='Joint(s) already exist', button=['Ok'])\r\n return\r\n ikJoints = mc.duplicate(x, n=ikJointName, po=True)\r\n fkJoints = mc.duplicate(x, n=fkJointName, po=True)\r\n\r\n #-- Parent Duplicated Joints\r\n resultParent=mc.listRelatives(x, p=True, c=False)\r\n if resultParent:\r\n for p in resultParent:\r\n if curSuffix in p:\r\n ikParent=p.replace(curSuffix, suffixA)\r\n fkParent=p.replace(curSuffix, suffixB)\r\n mc.parent(ikJointName, ikParent)\r\n mc.parent(fkJointName, fkParent)\r\n\r\n #-- Create and attach Blends\r\n mc.createNode('blendColors', n=blendRName)\r\n mc.createNode('blendColors', n=blendTName)\r\n mc.createNode('blendColors', n=blendSName)\r\n #--Inputs\r\n mc.connectAttr(ikJointName + '.rotate', blendRName + '.color2')\r\n mc.connectAttr(fkJointName + '.rotate', blendRName + '.color1')\r\n mc.connectAttr(ikJointName + '.translate', blendTName + '.color2')\r\n mc.connectAttr(fkJointName + '.translate', blendTName + '.color1')\r\n mc.connectAttr(ikJointName + '.scale', blendSName + '.color2')\r\n mc.connectAttr(fkJointName + '.scale', blendSName + '.color1')\r\n mc.connectAttr(ctrlCrv + '.' + attrName, blendRName + '.blender')\r\n mc.connectAttr(ctrlCrv + '.' + attrName, blendTName + '.blender')\r\n mc.connectAttr(ctrlCrv + '.' + attrName, blendSName + '.blender')\r\n #--Outputs\r\n mc.connectAttr(blendRName + '.output', x + '.rotate')\r\n mc.connectAttr(blendTName + '.output', x + '.translate')\r\n mc.connectAttr(blendSName + '.output', x + '.scale')\r\n\r\n def createAttr(self):\r\n #--Set attribute names\r\n if not attrNameBoxValue:\r\n mc.confirmDialog(title='ERROR', message='Enter a valid attribute name', button=['Ok'])\r\n return\r\n if not attrNiceNameBoxValue:\r\n mc.confirmDialog(title='ERROR', message='Enter a valid nice name', button=['Ok'])\r\n return\r\n\r\n if not ctrlCrvBoxValue or not mc.objExists(ctrlCrvBoxValue):\r\n mc.confirmDialog(title='ERROR', message='Select valid Control Curve', button=['Ok'])\r\n return\r\n\r\n global attrName\r\n global attrNiceName\r\n global ctrlCrv\r\n attrName = attrNameBoxValue\r\n attrNiceName = attrNiceNameBoxValue\r\n ctrlCrv=ctrlCrvBoxValue\r\n\r\n if not mc.attributeQuery(attrName, node=ctrlCrv, exists=True):\r\n mc.addAttr(ctrlCrv, ln=attrName, nn=attrNiceName, min=0, max=1, at='float', dv=0, k=True)\r\n\r\n\r\n\r\n\r\nmain()", "sub_path": "scripts/jointDuplicator/jointDuplicator.py", "file_name": "jointDuplicator.py", "file_ext": "py", "file_size_in_byte": 10453, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "maya.OpenMayaUI.MQtUtil.mainWindow", "line_number": 31, "usage_type": "call"}, {"api_name": "maya.OpenMayaUI.MQtUtil", "line_number": 31, "usage_type": "attribute"}, {"api_name": "maya.OpenMayaUI", "line_number": 31, "usage_type": "name"}, {"api_name": "shiboken2.wrapInstance", "line_number": 32, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QWidget", "line_number": 32, "usage_type": "attribute"}, {"api_name": "PySide2.QtWidgets", "line_number": 32, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QDialog", "line_number": 58, "usage_type": "attribute"}, {"api_name": "PySide2.QtWidgets", "line_number": 58, "usage_type": "name"}, {"api_name": "PySide2.QtCore.Qt", "line_number": 65, "usage_type": "attribute"}, {"api_name": "PySide2.QtCore", "line_number": 65, "usage_type": "name"}, {"api_name": "jointDuplicatorUI.Ui_MainWindow", "line_number": 66, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 73, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 74, "usage_type": "call"}, {"api_name": "maya.cmds.objExists", "line_number": 104, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 104, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 110, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 110, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 130, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 130, "usage_type": "name"}, {"api_name": "maya.cmds.confirmDialog", "line_number": 133, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 133, "usage_type": "name"}, {"api_name": "maya.cmds.listRelatives", "line_number": 138, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 138, "usage_type": "name"}, {"api_name": "maya.cmds.ls", "line_number": 146, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 146, "usage_type": "name"}, {"api_name": "maya.cmds.confirmDialog", "line_number": 148, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 148, "usage_type": "name"}, {"api_name": "maya.cmds.confirmDialog", "line_number": 155, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 155, "usage_type": "name"}, {"api_name": "maya.cmds.confirmDialog", "line_number": 160, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 160, "usage_type": "name"}, {"api_name": "maya.cmds.confirmDialog", "line_number": 169, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 169, "usage_type": "name"}, {"api_name": "maya.cmds.objExists", "line_number": 174, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 174, "usage_type": "name"}, {"api_name": "maya.cmds.confirmDialog", "line_number": 175, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 175, "usage_type": "name"}, {"api_name": "maya.cmds.rename", "line_number": 178, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 178, "usage_type": "name"}, {"api_name": "maya.cmds.objExists", "line_number": 190, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 190, "usage_type": "name"}, {"api_name": "maya.cmds.confirmDialog", "line_number": 191, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 191, "usage_type": "name"}, {"api_name": "maya.cmds.duplicate", "line_number": 193, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 193, "usage_type": "name"}, {"api_name": "maya.cmds.duplicate", "line_number": 194, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 194, "usage_type": "name"}, {"api_name": "maya.cmds.listRelatives", "line_number": 197, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 197, "usage_type": "name"}, {"api_name": "maya.cmds.parent", "line_number": 203, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 203, "usage_type": "name"}, {"api_name": "maya.cmds.parent", "line_number": 204, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 204, "usage_type": "name"}, {"api_name": "maya.cmds.createNode", "line_number": 207, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 207, "usage_type": "name"}, {"api_name": "maya.cmds.createNode", "line_number": 208, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 208, "usage_type": "name"}, {"api_name": "maya.cmds.createNode", "line_number": 209, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 209, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 211, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 211, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 212, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 212, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 213, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 213, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 214, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 214, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 215, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 215, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 216, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 216, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 217, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 217, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 218, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 218, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 219, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 219, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 221, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 221, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 222, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 222, "usage_type": "name"}, {"api_name": "maya.cmds.connectAttr", "line_number": 223, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 223, "usage_type": "name"}, {"api_name": "maya.cmds.confirmDialog", "line_number": 228, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 228, "usage_type": "name"}, {"api_name": "maya.cmds.confirmDialog", "line_number": 231, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 231, "usage_type": "name"}, {"api_name": "maya.cmds.objExists", "line_number": 234, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 234, "usage_type": "name"}, {"api_name": "maya.cmds.confirmDialog", "line_number": 235, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 235, "usage_type": "name"}, {"api_name": "maya.cmds.attributeQuery", "line_number": 245, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 245, "usage_type": "name"}, {"api_name": "maya.cmds.addAttr", "line_number": 246, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 246, "usage_type": "name"}]}
+{"seq_id": "390685810", "text": "import numpy as np\nfrom ..utils import get_g\n\n\nclass DirectBias():\n \"\"\"Direct Bias Metric\"\"\"\n def __init__(self, E, c=1, g=None):\n \"\"\"Direct bias calculation\n Args:\n E (WE class object): Word embeddings object\n Kwargs:\n c (float): strictness factor\n g (np.array): gender direction\n\n \"\"\"\n if g is None:\n g = get_g(E)\n assert len(g) == E.dim \n self.g = g\n self.E = E\n self.c = c\n\n def _direct_bias(self, vec):\n \"\"\"Direct bias computation\n\n Args:\n vec (np.array): numpy array to calculate direct bias for\n \n \"\"\"\n return np.power(np.abs(vec.dot(self.g)), self.c) \n\n def compute(self, word_list):\n \"\"\"Compute direct bias\n\n Args:\n word_list (list): list of words to compute bias for. \n Returns:\n The direct bias of each word in the `word_list`.\n \n \"\"\"\n if not isinstance(word_list, list):\n word_list = [word_list]\n db = np.mean(\n [self._direct_bias(self.E.v(word)) for word in word_list]\n )\n return db\n", "sub_path": "fee/metrics/direct_bias.py", "file_name": "direct_bias.py", "file_ext": "py", "file_size_in_byte": 1174, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "utils.get_g", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.power", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 43, "usage_type": "call"}]}
+{"seq_id": "255649237", "text": "from collections import defaultdict\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.feature_extraction import DictVectorizer\nfrom sklearn.cross_validation import KFold\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\nfrom knock73 import feature, feature_vector, train, create_feature\nfrom knock74 import fit_feature, load_dict\nfrom knock76 import predict\nimport scipy\n\ndef cv(feature_dict, feature, polarity, folds):\n kfold = KFold(len(polarity), n_folds = folds)\n count, f1, recall, precision, accuracy = 0, 0, 0, 0, 0\n for train, test in kfold:\n LR = LogisticRegression()\n count += 1\n x = [(feature[i]) for i in train]\n y = [(polarity[i])for i in train]\n LR.fit(scipy.sparse.vstack(x), (y))\n\n test_label = []\n answer_label = [(polarity[j]) for j in test]\n for j in test:\n query = feature[j]\n result = -1 if query.shape[1] != len(feature_dict) else predict(LR, query)\n test_label.append(int(result[0]))\n accuracy += accuracy_score(answer_label, test_label)\n precision += precision_score(answer_label, test_label)\n recall += recall_score(answer_label, test_label)\n f1 += f1_score(answer_label, test_label)\n print('{}_fold finished.'.format(count))\n return accuracy, precision, recall, f1\n\nif __name__ == '__main__':\n feature_dict = load_dict('knock72_file.txt')\n feature, polarity = create_feature(open('sentiment.txt'))\n threshold = 0.5\n folds = 5\n accuracy, precision, recall, f1 = cv(feature_dict, feature, polarity, folds)\n print('accuracy: {}'.format(accuracy / 5))\n print('precision: {}'.format(precision / 5))\n print('recall: {}'.format(recall / 5))\n print('F1: {}'.format(f1 / 5))\n\n\n\n\n\n", "sub_path": "arai/chapter08/knock78.py", "file_name": "knock78.py", "file_ext": "py", "file_size_in_byte": 1809, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "sklearn.cross_validation.KFold", "line_number": 12, "usage_type": "call"}, {"api_name": "knock73.train", "line_number": 14, "usage_type": "name"}, {"api_name": "sklearn.linear_model.LogisticRegression", "line_number": 15, "usage_type": "call"}, {"api_name": "knock73.feature", "line_number": 17, "usage_type": "name"}, {"api_name": "knock73.train", "line_number": 17, "usage_type": "name"}, {"api_name": "knock73.train", "line_number": 18, "usage_type": "name"}, {"api_name": "scipy.sparse.vstack", "line_number": 19, "usage_type": "call"}, {"api_name": "scipy.sparse", "line_number": 19, "usage_type": "attribute"}, {"api_name": "knock73.feature", "line_number": 24, "usage_type": "name"}, {"api_name": "knock76.predict", "line_number": 25, "usage_type": "call"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 27, "usage_type": "call"}, {"api_name": "sklearn.metrics.precision_score", "line_number": 28, "usage_type": "call"}, {"api_name": "sklearn.metrics.recall_score", "line_number": 29, "usage_type": "call"}, {"api_name": "sklearn.metrics.f1_score", "line_number": 30, "usage_type": "call"}, {"api_name": "knock74.load_dict", "line_number": 35, "usage_type": "call"}, {"api_name": "knock73.feature", "line_number": 36, "usage_type": "name"}, {"api_name": "knock73.create_feature", "line_number": 36, "usage_type": "call"}, {"api_name": "knock73.feature", "line_number": 39, "usage_type": "argument"}]}
+{"seq_id": "533152924", "text": "from threading import Condition\nfrom datetime import datetime\nimport configparser\nimport logging\nimport sys\nimport os\n\nimport click\n\nfrom .extract import Provider\nfrom .transform import Transformer\nfrom .load import Loader\n\n\n# logging utility\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S')\nlog = logging.getLogger(__name__)\n\n\n@click.command()\n@click.argument(\"connect\", default='connect.ini')\n@click.argument(\"etl\", default='config.ini')\ndef etl_from_config(connect, etl):\n # config variables\n connect_config = configparser.ConfigParser()\n connect_config.read(connect)\n etl_config = configparser.ConfigParser()\n etl_config.read(etl)\n\n # thread concurrent structures\n unpr_list_cond = Condition()\n unpr_list = []\n\n pr_list_cond = Condition()\n pr_list = []\n\n extract_thread = Provider(unpr_list_cond, unpr_list, etl_config)\n extract_thread.start()\n\n transform_thread = Transformer(unpr_list_cond, pr_list_cond,\n unpr_list, pr_list, etl_config)\n transform_thread.start()\n\n load_thread = Loader(pr_list_cond, pr_list, etl_config, connect_config)\n load_thread.start()\n\n\nif __name__ == '__main__':\n etl_from_config()\n", "sub_path": "src/poe_price/data/etl/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1274, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "logging.basicConfig", "line_number": 16, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 16, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 18, "usage_type": "call"}, {"api_name": "configparser.ConfigParser", "line_number": 26, "usage_type": "call"}, {"api_name": "configparser.ConfigParser", "line_number": 28, "usage_type": "call"}, {"api_name": "threading.Condition", "line_number": 32, "usage_type": "call"}, {"api_name": "threading.Condition", "line_number": 35, "usage_type": "call"}, {"api_name": "extract.Provider", "line_number": 38, "usage_type": "call"}, {"api_name": "transform.Transformer", "line_number": 41, "usage_type": "call"}, {"api_name": "load.Loader", "line_number": 45, "usage_type": "call"}, {"api_name": "click.command", "line_number": 21, "usage_type": "call"}, {"api_name": "click.argument", "line_number": 22, "usage_type": "call"}, {"api_name": "click.argument", "line_number": 23, "usage_type": "call"}]}
+{"seq_id": "603808913", "text": "import argparse\nimport torch\nfrom rtpt import RTPT\nfrom models import BaseNet\nimport clip\nfrom PIL import Image\nfrom matplotlib.colors import LinearSegmentedColormap\nfrom captum.attr import IntegratedGradients\nfrom captum.attr import GradientShap\nfrom captum.attr import Occlusion\nfrom captum.attr import Saliency\nfrom captum.attr import NoiseTunnel\nfrom captum.attr import visualization as viz\nimport numpy as np\nfrom torchvision.transforms import Normalize\nimport matplotlib.pyplot as plt\nimport os\n\nparser = argparse.ArgumentParser(description='Crazy Stuff')\nparser.add_argument('--data_dir', default='./data',\n help='Select data path')\nparser.add_argument('--data_name', default='rt-polarity', type=str, choices=['rt-polarity', 'toxicity',\n 'toxicity_full', 'ethics', 'restaurant'],\n help='Select name of data set')\nparser.add_argument('--num_prototypes', default=10, type=int,\n help='Total number of prototypes')\nparser.add_argument('--num_classes', default=2, type=int,\n help='How many classes are to be classified?')\nparser.add_argument('--class_weights', default=[0.5,0.5],\n help='Class weight for cross entropy loss')\nparser.add_argument('-g','--gpu', type=int, default=[0], nargs='+',\n help='GPU device number(s)')\nparser.add_argument('--one_shot', type=bool, default=False,\n help='Whether to use one-shot learning or not (i.e. only a few training examples)')\nparser.add_argument('--discard', type=bool, default=False,\n help='Whether edge cases in the middle between completely toxic(1) and not toxic(0) shall be omitted')\nparser.add_argument('--proto_size', type=int, default=1,\n help='Define how many words should be used to define a prototype')\nparser.add_argument('--language_model', type=str, default='Bert', choices=['Bert','SentBert','GPT2', 'Clip_ViT-B/32','Clip_RN50x4', 'Clip_RN50'],\n help='Define which language model to use')\nparser.add_argument('--avoid_spec_token', type=bool, default=False,\n help='Whether to manually set PAD, SEP and CLS token to high value after Bert embedding computation')\nparser.add_argument('--compute_emb', type=bool, default=False,\n help='Whether to recompute (True) the embedding or just load it (False)')\nparser.add_argument('--metric', type=str, default='L2',\n help='metric')\nparser.add_argument('--input_type', type=str, required=True, choices=['text', 'img'],\n help='choose between text and image')\nparser.add_argument('--explain', type=bool, default=False,\n help='Who needs help anyway?')\n\n\nlabels = ['non toxic', 'toxic']\n\ninv_normalize = Normalize(\n mean=[-0.48145466/0.26862954, -0.4578275/0.26130258, -0.40821073/0.27577711],\n std=[1/0.26862954, 1/0.26130258, 1/0.27577711]\n)\n\ndefault_cmap = LinearSegmentedColormap.from_list('custom blue',\n [(0, '#ffffff'),\n (0.25, '#000000'),\n (1, '#000000')], N=256)\n\n\nclass ClipProbeModel(torch.nn.Module):\n def __init__(self):\n super(ClipProbeModel, self).__init__()\n self.model_probe = BaseNet(args)\n self.model_probe.load_state_dict(torch.load(args.model_path))\n self.model_probe.to(f'cuda:{args.gpu[0]}')\n self.model_probe.eval()\n self.MMM, self.preprocess = clip.load(args.language_model.split('_')[1], f'cuda:{args.gpu[0]}')\n self.MMM.to(f'cuda:{args.gpu[0]}')\n self.MMM.eval()\n\n def forward(self, x):\n if args.input_type == 'text':\n emb = self._forward_txt(x)\n else:\n emb = self._forward_img(x)\n predicted_label = self.model_probe.forward(emb, [])\n return predicted_label\n\n def _forward_txt(self, x):\n return self.MMM.encode_text(x).float()\n\n def _forward_img(self, x):\n #x = x.unsqueeze(0)\n return self.MMM.encode_image(x).float()\n\n\ndef explain_pred(model, x, y, file_name):\n #gradientshap(model, x, y, file_name)\n #saliency(model, x, y, file_name)\n #occlusion(model, x, y, file_name)\n noise_tunnel(model, x, y, file_name)\n #gradientshap(model, x, y, file_name)\n\n\n\ndef eval_model(args):\n args.model_path = './experiments/train_results/toxicity/05-19-14:07_baseline_Clip_ViT-B/best_model.pth.tar'\n #args.model_path = './experiments/train_results/toxicity/05-19-17:14_baseline_Clip_RN50/best_model.pth.tar'\n #args.model_path = './experiments/train_results/toxicity/05-19-17:30_baseline_Clip_RN50x4/best_model.pth.tar'\n model = ClipProbeModel()\n\n if args.input_type == 'text':\n print('Eval a text')\n txt = ['You are an asshole.']\n file_name = txt[0].replace(' ', '_').replace('.', '')\n x = clip.tokenize(txt)\n elif args.input_type == 'img':\n print('Eval an image')\n file_name = 'b14_p254_12'\n #file_name = 'b14_p253_4'\n #file_name = 'b13_p233_1'\n #file_name = 'b14_p253_11'\n #file_name = 'b2_p28_8'\n #file_name = 'b10_p136_15'\n x = model.preprocess(Image.open(f\"/workspace/datasets/SMID_images_400px/img/{file_name}.jpg\")).unsqueeze(0)\n else:\n raise ValueError('input type unknown')\n print(\"Running on gpu {}\".format(args.gpu))\n\n x = x.to(f'cuda:{args.gpu[0]}')\n\n logits = model(x)\n probs = logits.softmax(dim=-1)\n\n prediction_score, pred_label_idx = torch.topk(probs.float(), 1)\n\n pred_label_idx.squeeze_()\n predicted_label = labels[pred_label_idx]\n print(f'Predicted: {predicted_label} ({prediction_score.squeeze().item() * 100:.2f})')\n\n if args.explain and args.input_type == 'img':\n explain_pred(model, x, pred_label_idx, file_name)\n\n\ndef occlusion(model, x, y, file_name):\n inv_transformed_img = inv_normalize(x)\n ablator = Occlusion(model)\n attribution = ablator.attribute(x, target=y, sliding_window_shapes=(8, 8), strides=(2,2))\n fig, axis = viz.visualize_image_attr_multiple(np.transpose(attribution.cpu().detach().numpy(), (1, 2, 0)),\n np.transpose(inv_transformed_img.cpu().detach().numpy(), (1, 2, 0)),\n [\"original_image\", \"heat_map\"],\n [\"all\", \"absolute_value\"],\n cmap=default_cmap,\n show_colorbar=True)\n\n save_path = './clip_stuff/explain/toxicity/'\n os.makedirs(save_path, exist_ok=True)\n fig.savefig(os.path.join(save_path, f'occlusion_{file_name}.png'))\n\n\ndef saliency(model, x, y, file_name):\n inv_transformed_img = inv_normalize(x)\n saliency = Saliency(model)\n\n attribution = saliency.attribute(x, target=y)\n fig, axis = viz.visualize_image_attr_multiple(np.transpose(attribution.squeeze().cpu().detach().numpy(), (1, 2, 0)),\n np.transpose(inv_transformed_img.squeeze().cpu().detach().numpy(), (1, 2, 0)),\n [\"original_image\", \"heat_map\"],\n [\"all\", \"absolute_value\"],\n cmap=default_cmap,\n show_colorbar=True)\n\n save_path = './clip_stuff/explain/toxicity/'\n os.makedirs(save_path, exist_ok=True)\n fig.savefig(os.path.join(save_path, f'saliency_{file_name}.png'))\n\n\n\ndef gradientshap(model, x, y, file_name):\n inv_transformed_img = inv_normalize(x)\n gradient_shap = GradientShap(model)\n\n # Defining baseline distribution of images\n rand_img_dist = torch.cat([x * 0, x * 1])\n\n attributions_gs = gradient_shap.attribute(x,\n n_samples=50,\n stdevs=0.0001,\n baselines=rand_img_dist,\n target=y)\n fig, axis = viz.visualize_image_attr_multiple(np.transpose(attributions_gs.squeeze().cpu().detach().numpy(), (1, 2, 0)),\n np.transpose(inv_transformed_img.squeeze().cpu().detach().numpy(), (1, 2, 0)),\n [\"original_image\", \"heat_map\"],\n [\"all\", \"absolute_value\"],\n cmap=default_cmap,\n show_colorbar=True)\n\n save_path = './clip_stuff/explain/toxicity/'\n os.makedirs(save_path, exist_ok=True)\n fig.savefig(os.path.join(save_path, f'gradientshap_{file_name}.png'))\n\n\ndef noise_tunnel(model, x, y, file_name):\n inv_transformed_img = inv_normalize(x)\n integrated_gradients = IntegratedGradients(model)\n noise_tunnel_ = NoiseTunnel(integrated_gradients)\n\n attributions_ig_nt = noise_tunnel_.attribute(x, nt_samples=5, nt_type='smoothgrad_sq', target=y)\n fig, axis = viz.visualize_image_attr_multiple(np.transpose(attributions_ig_nt.squeeze().cpu().detach().numpy(), (1, 2, 0)),\n np.transpose(inv_transformed_img.squeeze().cpu().detach().numpy(), (1, 2, 0)),\n [\"original_image\", \"heat_map\"],\n [\"all\", \"positive\"],\n cmap=default_cmap,\n show_colorbar=True,\n use_pyplot=False)\n\n save_path = './clip_stuff/explain/toxicity/'\n os.makedirs(save_path, exist_ok=True)\n fig.savefig(os.path.join(save_path, f'noise_tunnel_{file_name}.png'))\n\n\nif __name__ == '__main__':\n # torch.manual_seed(0)\n # np.random.seed(0)\n torch.set_num_threads(6)\n args = parser.parse_args()\n\n # Create RTPT object and start the RTPT tracking\n rtpt = RTPT(name_initials='Kersting', experiment_name='CrazyStuff', max_iterations=1)\n rtpt.start()\n\n eval_model(args)\n", "sub_path": "main/eval.py", "file_name": "eval.py", "file_ext": "py", "file_size_in_byte": 10201, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 19, "usage_type": "call"}, {"api_name": "torchvision.transforms.Normalize", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.colors.LinearSegmentedColormap.from_list", "line_number": 60, "usage_type": "call"}, {"api_name": "matplotlib.colors.LinearSegmentedColormap", "line_number": 60, "usage_type": "name"}, {"api_name": "torch.nn", "line_number": 66, "usage_type": "attribute"}, {"api_name": "models.BaseNet", "line_number": 69, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 70, "usage_type": "call"}, {"api_name": "clip.load", "line_number": 73, "usage_type": "call"}, {"api_name": "clip.tokenize", "line_number": 112, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 121, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 121, "usage_type": "name"}, {"api_name": "torch.topk", "line_number": 131, "usage_type": "call"}, {"api_name": "captum.attr.Occlusion", "line_number": 143, "usage_type": "call"}, {"api_name": "captum.attr.visualization.visualize_image_attr_multiple", "line_number": 145, "usage_type": "call"}, {"api_name": "captum.attr.visualization", "line_number": 145, "usage_type": "name"}, {"api_name": "numpy.transpose", "line_number": 145, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 146, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 153, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 154, "usage_type": "call"}, {"api_name": "os.path", "line_number": 154, "usage_type": "attribute"}, {"api_name": "captum.attr.Saliency", "line_number": 159, "usage_type": "call"}, {"api_name": "captum.attr.visualization.visualize_image_attr_multiple", "line_number": 162, "usage_type": "call"}, {"api_name": "captum.attr.visualization", "line_number": 162, "usage_type": "name"}, {"api_name": "numpy.transpose", "line_number": 162, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 163, "usage_type": "call"}, {"api_name": "os.makedirs", "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": "captum.attr.GradientShap", "line_number": 177, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 180, "usage_type": "call"}, {"api_name": "captum.attr.visualization.visualize_image_attr_multiple", "line_number": 187, "usage_type": "call"}, {"api_name": "captum.attr.visualization", "line_number": 187, "usage_type": "name"}, {"api_name": "numpy.transpose", "line_number": 187, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 188, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 195, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 196, "usage_type": "call"}, {"api_name": "os.path", "line_number": 196, "usage_type": "attribute"}, {"api_name": "captum.attr.IntegratedGradients", "line_number": 201, "usage_type": "call"}, {"api_name": "captum.attr.NoiseTunnel", "line_number": 202, "usage_type": "call"}, {"api_name": "captum.attr.visualization.visualize_image_attr_multiple", "line_number": 205, "usage_type": "call"}, {"api_name": "captum.attr.visualization", "line_number": 205, "usage_type": "name"}, {"api_name": "numpy.transpose", "line_number": 205, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 206, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 214, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 215, "usage_type": "call"}, {"api_name": "os.path", "line_number": 215, "usage_type": "attribute"}, {"api_name": "torch.set_num_threads", "line_number": 221, "usage_type": "call"}, {"api_name": "rtpt.RTPT", "line_number": 225, "usage_type": "call"}, {"api_name": "rtpt.start", "line_number": 226, "usage_type": "call"}]}
+{"seq_id": "3212806", "text": "import datetime\nimport smtplib\nimport email.MIMEMultipart\n\nfromAddress = \"DTA-TWC-Logmon@cable.comcast.com\"\ntoAddress = [\"DASTeamB@cable.comcast.com\"]\nSERVER = 'mailrelay.comcast.com'\n\nmessage = \"Test\"\nemail = \"Subject: ALERT! - DTA2 : IVR : logMon: callEndReason :%s hour\\n\\n%s\" % (datetime.datetime.now().strftime(\"%Y-%m-%d %H\"), message)\n\n\nserver = smtplib.SMTP(SERVER)\n#server.sendmail(fromAddress, toAddress, email)\nserver.quit()\n", "sub_path": "mailapp.py", "file_name": "mailapp.py", "file_ext": "py", "file_size_in_byte": 435, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "email.MIMEMultipart", "line_number": 10, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 10, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 10, "usage_type": "attribute"}, {"api_name": "smtplib.SMTP", "line_number": 13, "usage_type": "call"}]}
+{"seq_id": "179508866", "text": "# Author: FFng, ffng0x15@gmail.com\n# 2017-08-18\n# Python 3.6\n\n\"\"\"\nData Structure:\nseat_info = {\n '_id': int,\n 'no': str,\n 'name': str,\n 'status': int,\n 'status_name': str\n}\n\nseat_info_dict = {\n 'meta': {\n 'updated_at': float, Unix timestamp,\n 'updated_at_human': str\n },\n seat_name: seat_info,\n ...\n}\n\nchanges_dict = {\n seat_name: {\n 'old': {\n 'status_name': str, old_status_name,\n 'updated_at': float, old_updated_at\n },\n 'new': {\n 'status_name': str, new_status_name,\n 'updated_at': float, new_updated_at\n }\n },\n ...\n}\n\nbooking_logs = {\n booking_no: { # str\n 'space': str, space,\n 'start_time': str, start_time,\n 'end_time': str, end_time,\n 'status_name': str, status_name\n },\n ...\n}\n\n\n\"\"\"\n\nimport requests\nimport time\nimport datetime\nimport json\nimport logging\nimport re\nimport os\nimport smtplib\nfrom email.mime.text import MIMEText\n\nfrom lxml import html as lxml_html\n\nimport ffc\n\ntry:\n from .trace_with_logger import TraceWithLogger\n from .exceptions import DateIsNotAvailable\n from .process_captcha import ProcessCaptcha\n from .exceptions import SeatIsNotAvailable\nexcept ImportError:\n from trace_with_logger import TraceWithLogger\n from exceptions import DateIsNotAvailable\n from process_captcha import ProcessCaptcha\n from exceptions import SeatIsNotAvailable\n\n\nAREA_MAP = {\n 46: '1层',\n 51: '301/302'\n}\n\nSEAT_STATUS_MAP = {\n 1: '空闲',\n 2: '已预约',\n 6: '使用中',\n 7: '临时离开'\n}\n\n\nLOGGER = ffc.init_logger(debug=False, name='trace_with_logger', file_path='./trace_with_logger.log',\n ch_level=logging.WARNING, ch_process_name=False, ch_thread_name=False,\n fh_level=logging.DEBUG, fh_process_name=False, fh_thread_name=False,\n fh_timed_rotating=True)\n\n\ndef trace_with_logger(record_input=True, record_output=True):\n global LOGGER\n return TraceWithLogger(logger=LOGGER, record_input=record_input, record_output=record_output)\n\n\nclass SeatMonitor:\n\n def __init__(self, debug=False, config='./private_config.json'):\n self.debug = debug\n if isinstance(config, str):\n self.config_dict = json.load(open(config, 'r', encoding='utf-8'))\n elif isinstance(config, dict):\n self.config_dict = config\n else:\n raise TypeError('Unexpected type of \"config\": {t}'.format(t=type(config)))\n log_path = self.config_dict.get('log_path') or './default_log_path.log'\n print('debug: {d}, log_path: {p}'.format(d=repr(self.debug), p=repr(log_path)))\n\n self.logger = ffc.init_logger(debug=self.debug, name=__name__, file_path=log_path,\n ch_level=logging.INFO, ch_process_name=False, ch_thread_name=False,\n fh_level=logging.DEBUG, fh_process_name=False, fh_thread_name=False,\n fh_timed_rotating=True)\n\n self.seat_info_dict = dict()\n self._seat_id_name_map = dict()\n self.session = requests.Session()\n self.login_status = False\n\n def _build_seat_id_name_map(self):\n\n for name in self.seat_info_dict:\n if name == 'meta':\n continue\n seat_id = self.seat_info_dict[name]['_id']\n self._seat_id_name_map.update({seat_id: name})\n return True\n\n @staticmethod\n def t_unix_to_human(unix_timestamp):\n \"\"\"\n :param unix_timestamp: int/float, unix timestamp\n :return: str, in format '2017-08-18 Fri 14:58:23'\n \"\"\"\n return datetime.datetime.fromtimestamp(unix_timestamp).strftime('%Y-%m-%d %a %H:%M:%S')\n\n def get_seats_status(self, area: int=46, day: str=None):\n l = self.logger\n if not isinstance(area, int):\n raise TypeError('area: {t} _{v}_'.format(t=type(area), v=repr(area)))\n if area not in AREA_MAP:\n raise ValueError('Unknown area: _{v}_'.format(v=repr(area)))\n if not isinstance(day, str):\n raise TypeError('day: {t} _{v}_'.format(t=type(day), v=repr(day)))\n if not re.match('201\\d-\\d{2}-\\d{2}', day):\n raise TypeError('Invalid day: _{v}_'.format(v=repr(day)))\n\n url = 'http://202.114.9.133/api.php/spaces_old'\n now_dt = datetime.datetime.now()\n today = now_dt.strftime('%Y-%m-%d')\n start_time = '08:30' if day != today else now_dt.strftime('%H:%M')\n payload = {\n 'area': area,\n 'day': day,\n 'startTime': start_time,\n 'endTime': '22:00'\n }\n l.debug('payload: {d}'.format(d=payload))\n\n # TODO: Separate this network access part, add more exception processes\n try:\n r = requests.get(url, params=payload, timeout=10)\n json_dict = json.loads(r.content)\n assert json_dict['status'] == 1\n except:\n raise\n\n def __process_received_content():\n global SEAT_STATUS_MAP\n nonlocal json_dict\n updated_at = time.time()\n updated_at_human = self.t_unix_to_human(updated_at)\n try:\n seat_list = json_dict['data']['list']\n assert len(seat_list) > 0\n except (KeyError, AssertionError):\n raise\n\n _seat_info_dict = {\n 'meta': {\n 'updated_at': updated_at,\n 'updated_at_human': updated_at_human\n }\n }\n for d in seat_list:\n _id = d['id'] # int, 内部id,预约座位时用于指定座位\n assert isinstance(_id, int)\n no = d['no'] # 座位的编号\n name = d['name']\n assert isinstance(no, str) and isinstance(name, str) and no == name\n\n status = d['status']\n status_name = d['status_name']\n if (status not in SEAT_STATUS_MAP) or (status_name != SEAT_STATUS_MAP[status]):\n raise ValueError('status: _{s}_, name: _{n}_'.format(s=repr(status), n=repr(status_name)))\n\n seat_info = {\n '_id': _id,\n 'no': no,\n 'name': name,\n 'status': status,\n 'status_name': status_name\n }\n if name in _seat_info_dict:\n raise ValueError('Repetitive name _{n}_. old: _{old}_, new: _{new}_'.format(\n n=repr(name), old=_seat_info_dict.get(name), new=seat_info))\n _seat_info_dict.update({\n name: seat_info # # because only str can be used as key in JSON\n })\n return _seat_info_dict\n seat_info_dict = __process_received_content()\n self.seat_info_dict.update(seat_info_dict)\n self._build_seat_id_name_map()\n l.info(f'get {len(seat_info_dict):,d} seat\\'s info')\n\n def __save_to_json_file():\n global AREA_MAP\n nonlocal payload, seat_info_dict\n try:\n _path = self.config_dict['seat_info_path']\n except:\n raise\n _json_dict = {\n 'params': {\n 'area': payload['area'],\n 'area_name': AREA_MAP[payload['area']],\n 'day': payload['day'],\n 'start_time': payload['startTime'],\n 'end_time': payload['endTime']\n },\n 'seat_info_dict': seat_info_dict\n }\n\n _json_str = json.dumps(_json_dict, ensure_ascii=False, indent=None, sort_keys=True)\n with open(_path, mode='a', encoding='utf-8') as f:\n if f.tell() != 0:\n f.write('\\n')\n f.write(_json_str)\n return _path\n json_path = __save_to_json_file()\n l.debug('Saved json(seat_info_dict) to {p}'.format(p=repr(os.path.abspath(json_path))))\n\n return seat_info_dict\n\n def diff_seat_info_dict(self, old: dict, new: dict, focus_on: list):\n \"\"\"\n \n :param old: old seat_info_dict\n :param new: \n :param focus_on: List[str] list of seat_name\n :return: dict\n \"\"\"\n l = self.logger\n\n old_updated_at = old['meta']['updated_at']\n new_updated_at = new['meta']['updated_at']\n l.debug('updated time: old: {o}, new: {n}'.format(o=self.t_unix_to_human(old_updated_at),\n n=self.t_unix_to_human(new_updated_at)))\n if old_updated_at == new_updated_at:\n return {}\n\n if not focus_on:\n for name in old.keys():\n if name == 'meta':\n continue\n focus_on.append(name)\n\n _name_status = list()\n for name in focus_on:\n _name_status.append((name, old[name]['status_name']))\n\n if len(focus_on) <= 10:\n l.info(f'Focus on {len(focus_on):,d} seats: {_name_status}')\n else:\n l.info(f'Focus on {len(focus_on):,d} seats (>10)')\n\n changes_dict = dict()\n for name in focus_on:\n old_status_name = old[name]['status_name']\n new_status_name = new[name]['status_name']\n if old_status_name == new_status_name:\n continue\n\n changes_dict[name] = {\n 'old': {\n 'status_name': old_status_name,\n 'updated_at': old_updated_at\n },\n 'new': {\n 'status_name': new_status_name,\n 'updated_at': new_updated_at\n }\n }\n l.info(f'{len(changes_dict)} seats\\' status changed.')\n\n return changes_dict\n\n def describe_changes(self, changes_dict: dict):\n l = self.logger\n\n if not changes_dict:\n l.debug('no changes')\n return []\n\n l.debug(f'changes_dict: {changes_dict}')\n\n def __convert(t_unix):\n return datetime.datetime.fromtimestamp(t_unix).strftime('%H:%M')\n\n s_list = list()\n for name in changes_dict:\n d = changes_dict[name]\n old = d['old']\n new = d['new']\n s = (f\"[{name:s}]\"\n f\"{old['status_name']}({__convert(old['updated_at'])})\"\n f\"->{new['status_name']}({__convert(new['updated_at'])})\")\n s_list.append(s)\n l.info(s)\n\n return s_list\n\n @trace_with_logger()\n def send_mail(self, subject: str, content: str):\n l = self.logger\n cfg = self.config_dict['mail']\n smtp_host = cfg['smtp_host']\n smtp_port = cfg['smtp_port']\n mail_user = cfg['username']\n mail_pass = cfg['password']\n sender = mail_user\n receivers = cfg['receivers']\n content += f'\\nthis mail was generated at {ffc.t_ff()} (timestamp={int(time.time())})'\n msg = MIMEText(content+'', 'plain', 'utf-8')\n msg['Subject'] = subject\n msg['From'] = sender\n msg['To'] = receivers[0]\n l.debug(f'Generated a mail to {receivers}, subject: {subject}')\n\n try:\n smtp_obj = smtplib.SMTP_SSL(host=smtp_host, port=smtp_port)\n smtp_obj.login(mail_user, mail_pass)\n smtp_obj.sendmail(from_addr=sender, to_addrs=receivers, msg=msg.as_string())\n smtp_obj.quit()\n l.info(f\"Sent a mail to {msg['To']}\")\n return True\n except smtplib.SMTPException as e:\n l.error(e)\n return False\n\n def login(self):\n l = self.logger\n cfg = self.config_dict['user']\n s = self.session\n\n index_url = 'http://202.114.9.133/Home/Web/Index'\n l.debug(f'Opening Index page: {index_url}')\n r = s.get(index_url, timeout=10)\n r.raise_for_status()\n\n captcha_url = 'http://202.114.9.133/api.php/check'\n l.debug(f'Loading CAPTCHA image...')\n r = s.get(captcha_url, timeout=10)\n r.raise_for_status()\n _path = './tmp.png'\n open('tmp.png', 'wb').write(r.content)\n l.info(f'Saved CAPTCHA at {repr(os.path.abspath(_path))}, please input answer: ')\n\n _start = time.time()\n process_captcha = ProcessCaptcha()\n _, answer = process_captcha.decode_captcha(file_path=_path)\n ms = int((time.time() - _start)*1000.0)\n l.info(f'Auto processed CAPTCHA, answer: {answer}, used {ms:,}ms')\n\n # answer = input('Answer: ')\n l.info(f'Received answer: _{repr(answer)}_')\n login_url = 'http://202.114.9.133/api.php/login'\n payload = {\n 'username': cfg['username'],\n 'password': cfg['password'],\n 'verify': answer\n }\n l.info(f\"Logging... username: {repr(payload['username'])}, {login_url}\")\n r = s.post(login_url, data=payload, timeout=10)\n r.raise_for_status()\n j = json.loads(r.content, encoding='utf-8')\n assert j['msg'] == '登陆成功'\n self.login_status = True\n l.info(f'Login succeed')\n return True\n\n def get_booking_history(self):\n l = self.logger\n\n s = self.session\n if s is None:\n raise ValueError('Session is invalid. Login first.')\n\n booking_history_url = 'http://202.114.9.133/User/Index/book'\n l.debug(f'Opening booking history page... {booking_history_url}')\n r = s.get(booking_history_url, timeout=10)\n r.raise_for_status()\n assert len(r.text) > 20000\n _path = './tmp.html'\n open(_path, 'w', encoding='utf-8').write(r.text)\n l.debug(f'Saved booking history page into {repr(os.path.abspath(_path))}')\n\n tree = lxml_html.fromstring(r.text)\n\n def __pick(_tr, _index):\n return _tr.xpath(f'./td[{_index}]/text()')[0].strip()\n booking_logs = dict()\n for tr in tree.xpath('//table[@id=\"menu_table\"]//tr[contains(@id, \"list\")]'):\n booking_no = __pick(tr, 1) # 预约号\n space = __pick(tr, 2) # 预约空间\n start_time = __pick(tr, 3) # 开始时间\n end_time = __pick(tr, 4) # 结束时间\n status_name = __pick(tr, 5) # 当前状态\n # print(booking_no, space, start_time, end_time, status_name)\n booking_logs.update({\n booking_no: {\n 'space': space,\n 'start_time': start_time,\n 'end_time': end_time,\n 'status_name': status_name\n }\n })\n\n _path = './booking_history.json'\n _json_str = json.dumps(booking_logs, ensure_ascii=False, indent=None, sort_keys=True)\n with open(_path, mode='a', encoding='utf-8') as f:\n if f.tell() != 0:\n f.write('\\n')\n f.write(_json_str)\n l.debug(f'Saved {len(booking_logs):,d} records into {repr(os.path.abspath(_path))}')\n\n return booking_logs\n\n @trace_with_logger()\n def _book(self, wanted_day: str='2017-08-21', area_id: int=46, seat_id: int=1638):\n l = self.logger\n s = self.session\n seat_name = self._seat_id_name_map[seat_id]\n if s is None:\n raise ValueError('Session is invalid. Login first.')\n l.info(f'wanted_day: {repr(wanted_day)}, '\n f'area_id: {repr(area_id)} -> {AREA_MAP[area_id]}, '\n f'seat_id: {repr(seat_id)} -> {seat_name}')\n\n # 获取可以预约的日期\n area_status_url = f'http://202.114.9.133/api.php/space_days/{area_id}'\n r = s.get(area_status_url, timeout=10)\n r.raise_for_status()\n j = json.loads(r.content, encoding='utf-8')\n assert j['msg'] == '获取可预约日期'\n day_list = list()\n for d in j['data']['list']:\n day_list.append(d['day'])\n l.debug(f'Available day: {day_list}')\n\n if wanted_day not in day_list:\n l.info(f'wanted_day {wanted_day} is not available')\n raise DateIsNotAvailable(f'{wanted_day} is not available.')\n\n # 获取可预约的时间段\n space_time_url = 'http://202.114.9.133/api.php/space_time_buckets'\n payload = {\n 'day': wanted_day,\n 'area': area_id\n }\n r = s.get(space_time_url, params=payload, timeout=10)\n j = json.loads(r.content, encoding='utf-8')\n assert j['msg'] == '获取可预约时间段'\n book_time_id = j['data']['list'][0]['bookTimeId']\n l.debug(f'segment/bookTimeId: {repr(book_time_id)}')\n\n # 预约\n book_url = f'http://202.114.9.133/api.php/spaces/{seat_id}/book'\n payload = {\n 'access_token': s.cookies.get('access_token'),\n 'userid': self.config_dict['user']['username'],\n 'segment': book_time_id,\n 'type': 1\n }\n r = s.post(book_url, data=payload, timeout=10)\n j = json.loads(r.content, encoding='utf-8')\n try:\n assert j['status'] == 1\n assert '预约成功' in j['msg']\n except Exception:\n l.error(f'{repr(j)}')\n raise\n\n d = j['data']['list']\n booking_no = d['no']\n seat_name = d['spaceInfo']['name']\n start_time = d['beginTime']['date']\n end_time = d['endTime']['date']\n status_name = d['statusName']\n l.info(f'Book succeed: {booking_no} {seat_name} {start_time}-{end_time} {status_name}')\n return True\n\n def book(self, wanted_day: str='2017-08-21', seat_name: str='1005'):\n l = self.logger\n\n self.get_seats_status(area=46, day=wanted_day)\n if seat_name not in self.seat_info_dict:\n raise ValueError(f'Unknown seat_name: _{repr(seat_name)}_')\n seat_id = self.seat_info_dict[seat_name]['_id']\n\n current_status_name = self.seat_info_dict[seat_name]['status_name']\n l.info(f'wanted_day: {wanted_day}, seat_name: {seat_name}, status: {current_status_name}')\n if current_status_name != '空闲':\n l.info('Seat is unavailable')\n raise SeatIsNotAvailable\n\n if self._book(wanted_day=wanted_day, area_id=46, seat_id=seat_id):\n # TODO\n return True\n else:\n return False\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "sub_path": "seat_monitor.py", "file_name": "seat_monitor.py", "file_ext": "py", "file_size_in_byte": 18472, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "ffc.init_logger", "line_number": 90, "usage_type": "call"}, {"api_name": "logging.WARNING", "line_number": 91, "usage_type": "attribute"}, {"api_name": "logging.DEBUG", "line_number": 92, "usage_type": "attribute"}, {"api_name": "trace_with_logger.TraceWithLogger", "line_number": 98, "usage_type": "call"}, {"api_name": "json.load", "line_number": 106, "usage_type": "call"}, {"api_name": "ffc.init_logger", "line_number": 114, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 115, "usage_type": "attribute"}, {"api_name": "logging.DEBUG", "line_number": 116, "usage_type": "attribute"}, {"api_name": "requests.Session", "line_number": 121, "usage_type": "call"}, {"api_name": "datetime.datetime.fromtimestamp", "line_number": 139, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 139, "usage_type": "attribute"}, {"api_name": "re.match", "line_number": 149, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 153, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 153, "usage_type": "attribute"}, {"api_name": "requests.get", "line_number": 166, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 167, "usage_type": "call"}, {"api_name": "time.time", "line_number": 175, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 238, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 245, "usage_type": "call"}, {"api_name": "os.path", "line_number": 245, "usage_type": "attribute"}, {"api_name": "datetime.datetime.fromtimestamp", "line_number": 312, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 312, "usage_type": "attribute"}, {"api_name": "ffc.t_ff", "line_number": 337, "usage_type": "call"}, {"api_name": "time.time", "line_number": 337, "usage_type": "call"}, {"api_name": "email.mime.text.MIMEText", "line_number": 338, "usage_type": "call"}, {"api_name": "smtplib.SMTP_SSL", "line_number": 345, "usage_type": "call"}, {"api_name": "smtplib.SMTPException", "line_number": 351, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 371, "usage_type": "call"}, {"api_name": "os.path", "line_number": 371, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 373, "usage_type": "call"}, {"api_name": "process_captcha.ProcessCaptcha", "line_number": 374, "usage_type": "call"}, {"api_name": "process_captcha.decode_captcha", "line_number": 375, "usage_type": "call"}, {"api_name": "time.time", "line_number": 376, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 390, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 410, "usage_type": "call"}, {"api_name": "os.path", "line_number": 410, "usage_type": "attribute"}, {"api_name": "lxml.html.fromstring", "line_number": 412, "usage_type": "call"}, {"api_name": "lxml.html", "line_number": 412, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 434, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 439, "usage_type": "call"}, {"api_name": "os.path", "line_number": 439, "usage_type": "attribute"}, {"api_name": "json.loads", "line_number": 458, "usage_type": "call"}, {"api_name": "exceptions.DateIsNotAvailable", "line_number": 467, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 476, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 490, "usage_type": "call"}, {"api_name": "exceptions.SeatIsNotAvailable", "line_number": 519, "usage_type": "name"}]}
+{"seq_id": "313273540", "text": "import pygame\r\nimport sys\r\nimport time\r\nimport pickle\r\nfrom network import Network\r\nfrom wordSource import wordSource\r\nfrom input import InputBox\r\n\r\npygame.font.init()\r\n\r\n# Windows size\r\n_displayWidth = 510\r\n_displayHeight = 400\r\n\r\n# Game windows\r\ngameDisplay = pygame.display.set_mode((_displayWidth, _displayHeight))\r\npygame.display.set_caption(\"Game\")\r\nclock = pygame.time.Clock()\r\n\r\n# Colors\r\n_black = (0,0,0)\r\n_white = (255,255,255)\r\n_red = (200,0,0)\r\n_brightRed = (255,0,0)\r\n_green = (0,200,0)\r\n_brightGreen = (0,255,0)\r\n_blue = (0,0,200)\r\n_brightBlue = (0,0,255)\r\n_yellow = (200,200,0)\r\n\r\n# Text size\r\n_smallText = pygame.font.SysFont(\"cambria\", 20)\r\n_mediumText = pygame.font.SysFont(\"cambria\", 30)\r\n_largeText = pygame.font.SysFont(\"cambria\", 40)\r\n\r\n# Button size\r\n_btnWidth = 120\r\n_btnHeight = 50\r\n\r\n# Text input fields\r\n_inputBoxes = []\r\n_inputBoxes.append(InputBox(149, 10, 200, 30)) # Input Word\r\n\r\n_canvas = pygame.Surface((_displayWidth, _displayHeight))\r\n_canvas.fill(_white)\r\n_input1_bckg = pygame.Rect(151,12,196,26) # Clear Input Word\r\n\r\n### Format displayed text\r\ndef text_objects(text, font, color):\r\n textSurface = font.render(text, True, color)\r\n return textSurface, textSurface.get_rect()\r\n\r\n### Create button\r\ndef button(msg, x, y, ac, ic, action=None):\r\n mouse = pygame.mouse.get_pos()\r\n click = pygame.mouse.get_pressed()\r\n\r\n pygame.draw.rect(gameDisplay, ac,(x,y,_btnWidth,_btnHeight))\r\n\r\n if x+_btnWidth > mouse[0] > x and y+_btnHeight > mouse[1] > y:\r\n if click[0] == 1 and action != None:\r\n action()\r\n time.sleep(0.5)\r\n else:\r\n pygame.draw.rect(gameDisplay, ic,(x,y,_btnWidth,_btnHeight))\r\n \r\n # Button text\r\n textSurf, textRect = text_objects(msg, _smallText, _black)\r\n textRect.center = ( (x+(_btnWidth/2)), (y+(_btnHeight/2)) )\r\n gameDisplay.blit(textSurf, textRect)\r\n\r\n## Create local game\r\ndef createLocal():\r\n guessingWordWindow()\r\n print(\"Create new local game\")\r\n\r\n# Not started \r\ndef createServerGame():\r\n # ## Nickname input\r\n # ## Choose type (Public/Private)\r\n # ## Player count\r\n\r\n onlineGame()\r\n print(\"Create new game\")\r\n\r\n### Close game window\r\ndef quitGame():\r\n print(\"Close game\")\r\n pygame.quit()\r\n quit()\r\n\r\n\r\n\r\ndef redrawWindow(win, game, p):\r\n win.fill((128,128,128))\r\n\r\n if not(game.connected()):\r\n font = pygame.font.SysFont(\"comicsans\", 80)\r\n text = font.render(\"Waiting for Player...\", 1, (255,0,0), True)\r\n win.blit(text, (width/2 - text.get_width()/2, height/2 - text.get_height()/2))\r\n else:\r\n font = pygame.font.SysFont(\"comicsans\", 60)\r\n text = font.render(\"Your Move\", 1, (0, 255,255))\r\n win.blit(text, (80, 200))\r\n\r\n text = font.render(\"Opponents\", 1, (0, 255, 255))\r\n win.blit(text, (380, 200))\r\n\r\n move1 = game.get_player_move(0)\r\n move2 = game.get_player_move(1)\r\n if game.bothWent():\r\n text1 = font.render(move1, 1, (0,0,0))\r\n text2 = font.render(move2, 1, (0, 0, 0))\r\n else:\r\n if game.p1Went and p == 0:\r\n text1 = font.render(move1, 1, (0,0,0))\r\n elif game.p1Went:\r\n text1 = font.render(\"Locked In\", 1, (0, 0, 0))\r\n else:\r\n text1 = font.render(\"Waiting...\", 1, (0, 0, 0))\r\n\r\n if game.p2Went and p == 1:\r\n text2 = font.render(move2, 1, (0,0,0))\r\n elif game.p2Went:\r\n text2 = font.render(\"Locked In\", 1, (0, 0, 0))\r\n else:\r\n text2 = font.render(\"Waiting...\", 1, (0, 0, 0))\r\n\r\n if p == 1:\r\n win.blit(text2, (100, 350))\r\n win.blit(text1, (400, 350))\r\n else:\r\n win.blit(text1, (100, 350))\r\n win.blit(text2, (400, 350))\r\n\r\n for btn in btns:\r\n btn.draw(win)\r\n\r\n pygame.display.update()\r\n\r\ndef onlineGame():\r\n run = True\r\n clock = pygame.time.Clock()\r\n n = Network()\r\n player = int(n.getP()) ## Nestrādā: TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'\r\n print(\"You are player\", player)\r\n\r\n ## Struct \r\n createStruct = True\r\n y = 50\r\n x = 150\r\n\r\n ## Guessing word\r\n #word = wordSource.getWord()\r\n word = \"KOKS\"\r\n inputWord = \"\"\r\n attemptCount = 0\r\n maxPoints = 0\r\n guessAttempt = False\r\n gameOver = False\r\n correctInput = False\r\n startCountdown = True\r\n\r\n gameDisplay.fill(_white)\r\n gameDisplay.blit(_canvas, (151,12), _input1_bckg)\r\n\r\n while run:\r\n clock.tick(60)\r\n try:\r\n game = n.send(\"get\")\r\n except:\r\n run = False\r\n print(\"Couldn't get game\")\r\n break\r\n\r\n if game.allEndGuessing():\r\n redrawWindow(gameDisplay, game, player)\r\n pygame.time.delay(500)\r\n try:\r\n game = n.send(\"reset\")\r\n except:\r\n run = False\r\n print(\"Couldn't get game\")\r\n break\r\n\r\n font = pygame.font.SysFont(\"comicsans\", 90)\r\n text = font.render(\"You Won!\", 1, (255,0,0))\r\n\r\n gameDisplay.blit(text, (width/2 - text.get_width()/2, height/2 - text.get_height()/2))\r\n pygame.display.update()\r\n pygame.time.delay(2000)\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n run = False\r\n pygame.quit()\r\n\r\n if gameOver:\r\n if player == 0:\r\n if not game.p1endGuessing:\r\n n.send(maxPoints)\r\n elif player == 1:\r\n if not game.p2endGuessing:\r\n n.send(maxPoints)\r\n else:\r\n if not game.p3endGuessing:\r\n n.send(maxPoints)\r\n\r\n redrawWindow(gameDisplay, game, player)\r\n\r\n\r\n## Local game\r\ndef guessingWordWindow():\r\n ## Struct \r\n createStruct = True\r\n y = 50\r\n x = 150\r\n\r\n ## Guessing word\r\n #word = wordSource.getWord()\r\n word = \"KOKS\"\r\n inputWord = \"\"\r\n attemptCount = 0\r\n maxPoint = 0\r\n guessAttempt = False\r\n gameOver = False\r\n correctInput = False\r\n startCountdown = True\r\n\r\n gameDisplay.fill(_white)\r\n gameDisplay.blit(_canvas, (151,12), _input1_bckg)\r\n\r\n while True:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n # InputBox\r\n _inputBoxes[0].handle_event(event)\r\n gameDisplay.blit(_canvas, (152,12), _input1_bckg)\r\n if event.type == pygame.KEYDOWN:\r\n if _inputBoxes[0].active:\r\n if event.key == pygame.K_RETURN:\r\n inputWord = _inputBoxes[0].text\r\n _inputBoxes[0].text = ''\r\n if not gameOver:\r\n guessAttempt = True \r\n\r\n ## Generate guessing structure\r\n if createStruct:\r\n createStruct = False\r\n for n in range(5):\r\n l = 0\r\n while l < len(word):\r\n pygame.draw.rect(gameDisplay, _black,((x + 35*l)-2,(y+ 40*n)-2,34,34))\r\n pygame.draw.rect(gameDisplay, _white,((x + 35*l),(y+ 40*n),30,30))\r\n l += 1\r\n \r\n ## Attempt\r\n # Attempt input\r\n if not gameOver:\r\n _inputBoxes[0].draw(gameDisplay)\r\n \r\n # Attempt \r\n if guessAttempt:\r\n guessAttempt = False\r\n point = 0\r\n inputWord = inputWord.upper()\r\n \r\n # Input word length check\r\n if(len(inputWord) > len(word)):\r\n inputWord = inputWord[:len(word)]\r\n # Correct input\r\n if(word == inputWord):\r\n gameOver = True\r\n correctInput = True\r\n maxPoint = len(word)*2\r\n maxPoint += 5- attemptCount\r\n textSurf, textRect = text_objects(\"Your input is correct.\", _smallText, _black)\r\n textRect.center = ((_displayWidth+x)/2 , 270 )\r\n gameDisplay.blit(textSurf, textRect)\r\n\r\n l = 0\r\n for c in word:\r\n if( l < len(word)):\r\n pygame.draw.rect(gameDisplay, _green,((x + 35*l),(y + 40*attemptCount),30,30))\r\n\r\n textSurf, textRect = text_objects(c, _smallText, _black)\r\n textRect.center = ( ((x + 35*l)+(30/2)), ((y + 40*attemptCount)+(30/2)) )\r\n gameDisplay.blit(textSurf, textRect)\r\n\r\n l += 1\r\n\r\n # Incorrect input\r\n else:\r\n i = 0\r\n while i < len(inputWord):\r\n\r\n if(inputWord[i] == word[i]):\r\n pygame.draw.rect(gameDisplay, _green,((x + 35*i),(y + 40*attemptCount),30,30))\r\n point += 2\r\n elif(word.find(inputWord[i]) != -1):\r\n pygame.draw.rect(gameDisplay, _yellow,((x + 35*i),(y + 40*attemptCount),30,30))\r\n point += 1\r\n else:\r\n pygame.draw.rect(gameDisplay, _red,((x + 35*i),(y + 40*attemptCount),30,30))\r\n\r\n textSurf, textRect = text_objects(inputWord[i], _smallText, _black)\r\n textRect.center = ( ((x + 35*i)+(30/2)), ((y + 40*attemptCount)+(30/2)) )\r\n gameDisplay.blit(textSurf, textRect)\r\n\r\n i += 1\r\n \r\n empty = 0\r\n while(len(word) != len(inputWord) + empty):\r\n pygame.draw.rect(gameDisplay, _red,((x + 35*(empty + len(inputWord))),(y + 40*attemptCount),30,30))\r\n empty += 1\r\n \r\n # Point\r\n if maxPoint < point:\r\n maxPoint = point\r\n # Attempt\r\n attemptCount += 1\r\n\r\n # Dont guess after all attempt\r\n if attemptCount >= 5:\r\n gameOver = True \r\n if not correctInput:\r\n\r\n textSurf, textRect = text_objects(\"Your input isn't correct.\", _smallText, _black)\r\n textRect.center = ((_displayWidth+x)/2 , 270 )\r\n gameDisplay.blit(textSurf, textRect)\r\n\r\n i = 0\r\n while i < len(word):\r\n pygame.draw.rect(gameDisplay, _green,((x + 35*i), 360,30,30))\r\n\r\n textSurf, textRect = text_objects(word[i], _smallText, _black)\r\n textRect.center = ( ((x + 35*i)+(30/2)), (360 +(30/2)) )\r\n gameDisplay.blit(textSurf, textRect)\r\n\r\n i += 1\r\n\r\n textSurf, textRect = text_objects(\"Correct answer is:\", _smallText, _black)\r\n textRect.center = ( (_displayWidth+x)/2 , 330 )\r\n gameDisplay.blit(textSurf, textRect)\r\n\r\n if gameOver:\r\n textSurf, textRect = text_objects(\"You earned \" + str(maxPoint) + \" points\", _smallText, _black)\r\n textRect.center = ((_displayWidth+x)/2 , 300 )\r\n gameDisplay.blit(textSurf, textRect)\r\n\r\n button(\"Play Again\", 10, 10, _brightGreen, _green, guessingWordWindow)\r\n #button(\"Main\", 10, 240, _brightBlue, _blue, menuWindow)\r\n\r\n\r\n pygame.display.update()\r\n clock.tick(60)\r\n\r\n## Menu window\r\ndef menuWindow():\r\n\r\n ## Window title\r\n gameDisplay.fill(_white)\r\n TextSurf, TextRect = text_objects(\"Guess the Word\", _largeText, _black)\r\n TextRect.center = ((_displayWidth/2), (100))\r\n gameDisplay.blit(TextSurf, TextRect)\r\n\r\n while True:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n quitGame()\r\n\r\n ## Create button (dp_w, dp_h, active_color, inactive_color, function)\r\n button(\"Local\", 30, 250, _brightGreen, _green, createLocal)\r\n button(\"Online\", 195, 250, _brightBlue, _blue, createServerGame)\r\n button(\"Quit\", 360, 250, _brightRed, _red, quitGame)\r\n\r\n pygame.display.update()\r\n clock.tick(60)\r\n\r\n\r\n# Programm start\r\nmenuWindow()\r\n", "sub_path": "client.py", "file_name": "client.py", "file_ext": "py", "file_size_in_byte": 12282, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "pygame.font.init", "line_number": 9, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 9, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 16, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 16, "usage_type": "attribute"}, {"api_name": "pygame.display.set_caption", "line_number": 17, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 17, "usage_type": "attribute"}, {"api_name": "pygame.time.Clock", "line_number": 18, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 18, "usage_type": "attribute"}, {"api_name": "pygame.font.SysFont", "line_number": 32, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 32, "usage_type": "attribute"}, {"api_name": "pygame.font.SysFont", "line_number": 33, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 33, "usage_type": "attribute"}, {"api_name": "pygame.font.SysFont", "line_number": 34, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 34, "usage_type": "attribute"}, {"api_name": "input.InputBox", "line_number": 42, "usage_type": "call"}, {"api_name": "pygame.Surface", "line_number": 44, "usage_type": "call"}, {"api_name": "pygame.Rect", "line_number": 46, "usage_type": "call"}, {"api_name": "pygame.mouse.get_pos", "line_number": 55, "usage_type": "call"}, {"api_name": "pygame.mouse", "line_number": 55, "usage_type": "attribute"}, {"api_name": "pygame.mouse.get_pressed", "line_number": 56, "usage_type": "call"}, {"api_name": "pygame.mouse", "line_number": 56, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 58, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 58, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 63, "usage_type": "call"}, {"api_name": "pygame.draw.rect", "line_number": 65, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 65, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 89, "usage_type": "call"}, {"api_name": "pygame.font.SysFont", "line_number": 98, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 98, "usage_type": "attribute"}, {"api_name": "pygame.font.SysFont", "line_number": 102, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 102, "usage_type": "attribute"}, {"api_name": "pygame.display.update", "line_number": 139, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 139, "usage_type": "attribute"}, {"api_name": "pygame.time.Clock", "line_number": 143, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 143, "usage_type": "attribute"}, {"api_name": "network.Network", "line_number": 144, "usage_type": "call"}, {"api_name": "pygame.time.delay", "line_number": 178, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 178, "usage_type": "attribute"}, {"api_name": "pygame.font.SysFont", "line_number": 186, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 186, "usage_type": "attribute"}, {"api_name": "pygame.display.update", "line_number": 190, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 190, "usage_type": "attribute"}, {"api_name": "pygame.time.delay", "line_number": 191, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 191, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 193, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 193, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 194, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 196, "usage_type": "call"}, {"api_name": "pygame.event.get", "line_number": 234, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 234, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 235, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 236, "usage_type": "call"}, {"api_name": "pygame.KEYDOWN", "line_number": 241, "usage_type": "attribute"}, {"api_name": "pygame.K_RETURN", "line_number": 243, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 255, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 255, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 256, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 256, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 286, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 286, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 300, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 300, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 303, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 303, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 306, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 306, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 316, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 316, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 336, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 336, "usage_type": "attribute"}, {"api_name": "pygame.display.update", "line_number": 357, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 357, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 370, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 370, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 371, "usage_type": "attribute"}, {"api_name": "pygame.display.update", "line_number": 379, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 379, "usage_type": "attribute"}]}
+{"seq_id": "270164195", "text": "#!/usr/bin/python3\n# coding=utf-8\n\n# -------------------------------------------------------------------------------\n# This file is part of Phobos, a Blender Add-On to edit robot models.\n# Copyright (C) 2020 University of Bremen & DFKI GmbH Robotics Innovation Center\n#\n# You should have received a copy of the 3-Clause BSD License in the LICENSE file.\n# If not, see .\n# -------------------------------------------------------------------------------\n\nimport json\nfrom datetime import datetime\nfrom phobos.blender.defs import version\nfrom phobos.blender.defs import repository\nfrom phobos.blender.utils import io as ioUtils\nfrom phobos.blender.utils.general import roundFloatsInDict\nfrom phobos.blender.phoboslog import log\n\n\ndef exportSMURFScene(entities, path):\n \"\"\"Exports an arranged scene into SMURFS. It will export only entities\n with a valid entity/name, and entity/type property.\n\n Args:\n selected_only(bool): If True only selected entities get exported.\n subfolder(bool): If True the models are exported into separate subfolders\n entities: \n path: \n\n Returns:\n\n \"\"\"\n log(\"Exporting scene to \" + path + '.smurfs', \"INFO\")\n with open(path + '.smurfs', 'w') as outputfile:\n sceneinfo = (\n \"# SMURF scene created at \"\n + path\n + \" \"\n + datetime.now().strftime(\"%Y%m%d_%H:%M\")\n + \"\\n\"\n )\n log(sceneinfo, \"INFO\")\n sceneinfo += \"# created with Phobos \" + version + \" - \" + repository + \"\\n\\n\"\n ioUtils.securepath(path)\n outputfile.write(sceneinfo)\n entitiesdict = roundFloatsInDict(\n {'entities': entities}, ioUtils.getExpSettings().decimalPlaces\n )\n outputfile.write(json.dumps(entitiesdict, indent=2))\n\n\n# registering import/export functions of types with Phobos\nscene_type_dict = {'smurfs': {'export': exportSMURFScene, 'extensions': ('smurfs',)}}\n", "sub_path": "phobos/blender/io/scenes/smurfs.py", "file_name": "smurfs.py", "file_ext": "py", "file_size_in_byte": 1970, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "phobos.blender.phoboslog.log", "line_number": 34, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 40, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 40, "usage_type": "name"}, {"api_name": "phobos.blender.phoboslog.log", "line_number": 43, "usage_type": "call"}, {"api_name": "phobos.blender.defs.version", "line_number": 44, "usage_type": "name"}, {"api_name": "phobos.blender.defs.repository", "line_number": 44, "usage_type": "name"}, {"api_name": "phobos.blender.utils.io.securepath", "line_number": 45, "usage_type": "call"}, {"api_name": "phobos.blender.utils.io", "line_number": 45, "usage_type": "name"}, {"api_name": "phobos.blender.utils.general.roundFloatsInDict", "line_number": 47, "usage_type": "call"}, {"api_name": "phobos.blender.utils.io.getExpSettings", "line_number": 48, "usage_type": "call"}, {"api_name": "phobos.blender.utils.io", "line_number": 48, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 50, "usage_type": "call"}]}
+{"seq_id": "276097982", "text": "import matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn import linear_model\nimport math\n\n\ndata = \"\"\"2\t15.11\n4\t11.36\n6\t9.77\n8\t9.09\n10\t8.48\n15\t7.69\n20\t7.33\n25\t7.06\n30\t6.7\n40\t6.43\n50\t6.16\n60\t5.99\n70\t5.77\n80\t5.64\n90\t5.39\n110\t5.09\n130\t4.87\n150\t4.6\n160\t4.5\n170\t4.36\n180\t4.2\n\"\"\"\n\n\ndef load_data():\n v = data.splitlines()\n x = [v[i].split('\\t')[0] for i in range(len(v))]\n y = [v[i].split('\\t')[1] for i in range(len(v))]\n return x, y\n\n\n# part a\ndef a():\n regr = linear_model.LinearRegression()\n x, y = load_data()\n\n # make x, y as log x, log y\n print(x)\n x = [math.log(float(x[i])) for i in range(len(x))]\n print(x)\n y = [math.log(float(y[i])) for i in range(len(y))]\n\n # make x, y as np array\n x = np.array(x).reshape(-1, 1)\n y = np.array(y).reshape(-1, 1)\n regr.fit(x, y)\n\n plt.scatter(x.tolist(), y.tolist(), color='black')\n plt.plot(x.tolist(), regr.predict(x).tolist(), color='blue', linewidth=2)\n plt.title('Regression line in log-log coordinates')\n plt.xlabel('Log of Hours')\n plt.ylabel('Log of Sulfate')\n plt.show()\n\n\n# part b\ndef b():\n regr = linear_model.LinearRegression()\n x, y = load_data()\n\n # make x, y as log x, log y\n print(x)\n x = [math.log(float(x[i])) for i in range(len(x))]\n print(x)\n y = [math.log(float(y[i])) for i in range(len(y))]\n\n # make x, y as np array\n x = np.array(x).reshape(-1, 1)\n y = np.array(y).reshape(-1, 1)\n regr.fit(x, y)\n\n yy = regr.predict(x)\n\n # reverse log to plot original coordinate\n x = x.tolist()\n x = [math.exp(x[i][0]) for i in range(len(x))]\n\n y = y.tolist()\n y = [math.exp(y[i][0]) for i in range(len(y))]\n\n yy = yy.tolist()\n yy = [math.exp(yy[i][0]) for i in range(len(yy))]\n\n plt.scatter(x, y, color='black')\n plt.plot(x, yy, color='blue', linewidth=2)\n plt.title('Regression curve in original coordinates')\n plt.xlabel('Hours')\n plt.ylabel('Sulfate')\n plt.show()\n\n# part c\ndef c_1():\n regr = linear_model.LinearRegression()\n x, y = load_data()\n\n # make x, y as log x, log y\n print(x)\n x = [math.log(float(x[i])) for i in range(len(x))]\n print(x)\n y = [math.log(float(y[i])) for i in range(len(y))]\n\n # make x, y as np array\n x = np.array(x).reshape(-1, 1)\n y = np.array(y).reshape(-1, 1)\n regr.fit(x, y)\n yy = regr.predict(x)\n plt.title('Residual plot in log-log coordinates')\n plt.scatter(y.tolist(), (y - yy).tolist())\n plt.show()\n\ndef c_2():\n regr = linear_model.LinearRegression()\n x, y = load_data()\n\n # make x, y as log x, log y\n print(x)\n x = [math.log(float(x[i])) for i in range(len(x))]\n print(x)\n y = [math.log(float(y[i])) for i in range(len(y))]\n\n # make x, y as np array\n x = np.array(x).reshape(-1, 1)\n y = np.array(y).reshape(-1, 1)\n regr.fit(x, y)\n yy = regr.predict(x)\n\n y_original = [math.exp(y[i][0]) for i in range(len(y))]\n\n y_residuals = [math.exp(y[i][0] - yy[i][0]) for i in range(len(y))]\n\n plt.title('Residual plot in original coordinates')\n plt.scatter(y_original, y_residuals)\n plt.show()\n\n\nif __name__ == \"__main__\":\n a()\n b()\n c_1()\n c_2()\n\n\n\n", "sub_path": "CS498_AML_HM5/HW5_7-9.py", "file_name": "HW5_7-9.py", "file_ext": "py", "file_size_in_byte": 3181, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "sklearn.linear_model.LinearRegression", "line_number": 40, "usage_type": "call"}, {"api_name": "sklearn.linear_model", "line_number": 40, "usage_type": "name"}, {"api_name": "math.log", "line_number": 45, "usage_type": "call"}, {"api_name": "math.log", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 51, "usage_type": "call"}, {"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.plot", "line_number": 55, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 55, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 56, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 56, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "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.show", "line_number": 59, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 59, "usage_type": "name"}, {"api_name": "sklearn.linear_model.LinearRegression", "line_number": 64, "usage_type": "call"}, {"api_name": "sklearn.linear_model", "line_number": 64, "usage_type": "name"}, {"api_name": "math.log", "line_number": 69, "usage_type": "call"}, {"api_name": "math.log", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 74, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 75, "usage_type": "call"}, {"api_name": "math.exp", "line_number": 82, "usage_type": "call"}, {"api_name": "math.exp", "line_number": 85, "usage_type": "call"}, {"api_name": "math.exp", "line_number": 88, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 90, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 90, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 91, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 91, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 92, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 92, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 93, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 93, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 94, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 94, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 95, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 95, "usage_type": "name"}, {"api_name": "sklearn.linear_model.LinearRegression", "line_number": 99, "usage_type": "call"}, {"api_name": "sklearn.linear_model", "line_number": 99, "usage_type": "name"}, {"api_name": "math.log", "line_number": 104, "usage_type": "call"}, {"api_name": "math.log", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 113, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 113, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 114, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 114, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 115, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 115, "usage_type": "name"}, {"api_name": "sklearn.linear_model.LinearRegression", "line_number": 118, "usage_type": "call"}, {"api_name": "sklearn.linear_model", "line_number": 118, "usage_type": "name"}, {"api_name": "math.log", "line_number": 123, "usage_type": "call"}, {"api_name": "math.log", "line_number": 125, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 129, "usage_type": "call"}, {"api_name": "math.exp", "line_number": 133, "usage_type": "call"}, {"api_name": "math.exp", "line_number": 135, "usage_type": "call"}, {"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.scatter", "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"}]}
+{"seq_id": "417816346", "text": "import numpy as np\n\n#모델 생성\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import VotingClassifier\n\nfrom sklearn.metrics import accuracy_score\n\n\nfrom sklearn.datasets import load_breast_cancer\nfrom sklearn.model_selection import train_test_split\n\ncancer_data = load_breast_cancer()\n\nX_data = cancer_data.data\ny_label = cancer_data.target\n\nX_training, X_testing, y_training, y_testing = train_test_split(X_data, y_label, test_size = 0.2, random_state = 0)\n\n#개별 ML 모델을 위한 Classifier 생성\nrf_clf = RandomForestClassifier(n_estimators = 100, random_state = 0)\nlr_clf = LogisticRegression(solver = 'liblinear', random_state = 0)\nsvm_clf = SVC(gamma = 'auto', probability = True, random_state = 0)\n\n# 개별 모델들을 학습\nrf_clf.fit(X_training , y_training) \nlr_clf.fit(X_training, y_training)\nsvm_clf.fit(X_training, y_training)\n\n#학습된 개별 모델들이 각자 반환하는 예측 데이터 셋을 생성하고 개별 모델의 정확도 측정\nrf_pred = rf_clf.predict(X_testing)\nlr_pred = lr_clf.predict(X_testing)\nsvm_pred = svm_clf.predict(X_testing)\n\nprint('Random Forest 정확도 : {0:.4f}'.format(accuracy_score(y_testing, rf_pred)))\nprint('Logistic Regression 정확도 : {0:.4f}'.format(accuracy_score(y_testing, lr_pred)))\nprint('SVM 정확도 : {0:.4f}'.format(accuracy_score(y_testing, svm_pred)))\n\n#투표 분류\nvoting_clf = VotingClassifier(\n\testimators = [('rf', rf_clf), ('lr', lr_clf), ('svm', svm_clf)],\n\tvoting='soft')\n\nvoting_clf.fit(X_training, y_training)\n\nvoting_pred = voting_clf.predict(X_testing)\n\nprint('CV 기반 앙상블 모델 정확도 : {0:.4f}'.format(accuracy_score(y_testing, voting_pred)))", "sub_path": "ClassFIT_AI/AI_Model/CV.py", "file_name": "CV.py", "file_ext": "py", "file_size_in_byte": 1767, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "sklearn.datasets.load_breast_cancer", "line_number": 15, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 20, "usage_type": "call"}, {"api_name": "sklearn.ensemble.RandomForestClassifier", "line_number": 23, "usage_type": "call"}, {"api_name": "sklearn.linear_model.LogisticRegression", "line_number": 24, "usage_type": "call"}, {"api_name": "sklearn.svm.SVC", "line_number": 25, "usage_type": "call"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 37, "usage_type": "call"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 38, "usage_type": "call"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 39, "usage_type": "call"}, {"api_name": "sklearn.ensemble.VotingClassifier", "line_number": 42, "usage_type": "call"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 50, "usage_type": "call"}]}
+{"seq_id": "388693040", "text": "# Copyright 2019 The FastEstimator Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nimport time\nfrom typing import Iterable, List, Set, Union\n\nimport numpy as np\n\nfrom fastestimator.backend.get_lr import get_lr\nfrom fastestimator.backend.to_number import to_number\nfrom fastestimator.summary.system import System\nfrom fastestimator.util.data import Data\nfrom fastestimator.util.traceability_util import traceable\nfrom fastestimator.util.util import parse_modes, to_list, to_set\n\n\n@traceable()\nclass Trace:\n \"\"\"Trace controls the training loop. Users can use the `Trace` base class to customize their own functionality.\n\n Traces are invoked by the fe.Estimator periodically as it runs. In addition to the current data dictionary, they are\n also given a pointer to the current `System` instance which allows access to more information as well as giving the\n ability to modify or even cancel training. The order of function invocations is as follows:\n\n ``` plot\n Training: Testing:\n\n on_begin on_begin\n | |\n on_epoch_begin (train) <------< on_epoch_begin (test) <------<\n | | | |\n on_batch_begin (train) <----< | on_batch_begin (test) <----< |\n | | | | | |\n on_batch_end (train) >-----^ | on_batch_end (test) >------^ |\n | ^ | |\n on_epoch_end (train) | on_epoch_end (test) >---------^\n | | |\n on_epoch_begin (eval) | on_end\n | ^\n on_batch_begin (eval) <----< |\n | | |\n on_batch_end (eval) >-----^ |\n | |\n on_epoch_end (eval) >----------^\n |\n on_end\n ```\n\n Args:\n inputs: A set of keys that this trace intends to read from the state dictionary as inputs.\n outputs: A set of keys that this trace intends to write into the system buffer.\n mode: What mode(s) to execute this Trace in. For example, \"train\", \"eval\", \"test\", or \"infer\". To execute\n regardless of mode, pass None. To execute in all modes except for a particular one, you can pass an argument\n like \"!infer\" or \"!train\".\n \"\"\"\n system: System\n inputs: List[str]\n outputs: List[str]\n mode: Set[str]\n\n def __init__(self,\n inputs: Union[None, str, Iterable[str]] = None,\n outputs: Union[None, str, Iterable[str]] = None,\n mode: Union[None, str, Iterable[str]] = None) -> None:\n self.inputs = to_list(inputs)\n self.outputs = to_list(outputs)\n self.mode = parse_modes(to_set(mode))\n\n def on_begin(self, data: Data) -> None:\n \"\"\"Runs once at the beginning of training or testing.\n\n Args:\n data: A dictionary through which traces can communicate with each other or write values for logging.\n \"\"\"\n pass\n\n def on_epoch_begin(self, data: Data) -> None:\n \"\"\"Runs at the beginning of each epoch.\n\n Args:\n data: A dictionary through which traces can communicate with each other or write values for logging.\n \"\"\"\n pass\n\n def on_batch_begin(self, data: Data) -> None:\n \"\"\"Runs at the beginning of each batch.\n\n Args:\n data: A dictionary through which traces can communicate with each other or write values for logging.\n \"\"\"\n pass\n\n def on_batch_end(self, data: Data) -> None:\n \"\"\"Runs at the end of each batch.\n\n Args:\n data: The current batch and prediction data, as well as any information written by prior `Traces`.\n \"\"\"\n pass\n\n def on_epoch_end(self, data: Data) -> None:\n \"\"\"Runs at the end of each epoch.\n\n Args:\n data: A dictionary through which traces can communicate with each other or write values for logging.\n \"\"\"\n pass\n\n def on_end(self, data: Data) -> None:\n \"\"\"Runs once at the end training.\n\n Args:\n data: A dictionary through which traces can communicate with each other or write values for logging.\n \"\"\"\n pass\n\n\n@traceable()\nclass TrainEssential(Trace):\n \"\"\"A trace to collect important information during training.\n\n Please don't add this trace into an estimator manually. FastEstimator will add it automatically.\n\n Args:\n monitor_names: Which keys from the data dictionary to monitor during training.\n \"\"\"\n def __init__(self, monitor_names: Set[str]) -> None:\n super().__init__(inputs=monitor_names, mode=\"train\", outputs=[\"steps/sec\", \"epoch_time\", \"total_time\"])\n self.elapse_times = []\n self.train_start = None\n self.epoch_start = None\n self.step_start = None\n\n def on_begin(self, data: Data) -> None:\n self.train_start = time.perf_counter()\n data.write_with_log(\"num_device\", self.system.num_devices)\n data.write_with_log(\"logging_interval\", self.system.log_steps)\n\n def on_epoch_begin(self, data: Data) -> None:\n if self.system.log_steps:\n self.epoch_start = time.perf_counter()\n self.step_start = time.perf_counter()\n\n def on_batch_end(self, data: Data) -> None:\n if self.system.log_steps and (self.system.global_step % self.system.log_steps == 0\n or self.system.global_step == 1):\n for key in self.inputs:\n if key in data:\n data.write_with_log(key, data[key])\n if self.system.global_step > 1:\n self.elapse_times.append(time.perf_counter() - self.step_start)\n data.write_with_log(\"steps/sec\", round(self.system.log_steps / np.sum(self.elapse_times), 2))\n self.elapse_times = []\n self.step_start = time.perf_counter()\n\n def on_epoch_end(self, data: Data) -> None:\n if self.system.log_steps:\n self.elapse_times.append(time.perf_counter() - self.step_start)\n data.write_with_log(\"epoch_time\", \"{} sec\".format(round(time.perf_counter() - self.epoch_start, 2)))\n\n def on_end(self, data: Data) -> None:\n data.write_with_log(\"total_time\", \"{} sec\".format(round(time.perf_counter() - self.train_start, 2)))\n for model in self.system.network.models:\n if hasattr(model, \"current_optimizer\"):\n data.write_with_log(model.model_name + \"_lr\", get_lr(model))\n\n\n@traceable()\nclass EvalEssential(Trace):\n \"\"\"A trace to collect important information during evaluation.\n\n Please don't add this trace into an estimator manually. FastEstimator will add it automatically.\n\n Args:\n monitor_names: Any keys which should be collected over the course of an eval epoch.\n \"\"\"\n def __init__(self, monitor_names: Set[str]) -> None:\n super().__init__(mode=\"eval\", inputs=monitor_names)\n self.eval_results = None\n\n def on_epoch_begin(self, data: Data) -> None:\n self.eval_results = None\n\n def on_batch_end(self, data: Data) -> None:\n if self.eval_results is None:\n self.eval_results = {key: [data[key]] for key in self.inputs if key in data}\n else:\n for key in self.inputs:\n if key in data:\n self.eval_results[key].append(data[key])\n\n def on_epoch_end(self, data: Data) -> None:\n for key, value_list in self.eval_results.items():\n data.write_with_log(key, np.mean(np.array(value_list), axis=0))\n\n\n@traceable()\nclass Logger(Trace):\n \"\"\"A Trace that prints log messages.\n\n Please don't add this trace into an estimator manually. FastEstimator will add it automatically.\n \"\"\"\n def __init__(self) -> None:\n super().__init__(inputs=\"*\")\n\n def on_begin(self, data: Data) -> None:\n if not self.system.mode == \"test\":\n start_step = 1 if not self.system.global_step else self.system.global_step\n self._print_message(\"FastEstimator-Start: step: {}; \".format(start_step), data)\n\n def on_batch_end(self, data: Data) -> None:\n if self.system.mode == \"train\" and self.system.log_steps and (\n self.system.global_step % self.system.log_steps == 0 or self.system.global_step == 1):\n self._print_message(\"FastEstimator-Train: step: {}; \".format(self.system.global_step), data)\n\n def on_epoch_end(self, data: Data) -> None:\n if self.system.mode == \"train\" and self.system.log_steps:\n self._print_message(\"FastEstimator-Train: step: {}; \".format(self.system.global_step), data, True)\n elif self.system.mode == \"eval\":\n self._print_message(\"FastEstimator-Eval: step: {}; \".format(self.system.global_step), data, True)\n elif self.system.mode == \"test\":\n self._print_message(\"FastEstimator-Test: step: {}; \".format(self.system.global_step), data, True)\n\n def on_end(self, data: Data) -> None:\n if not self.system.mode == \"test\":\n self._print_message(\"FastEstimator-Finish: step: {}; \".format(self.system.global_step), data)\n\n def _print_message(self, header: str, data: Data, log_epoch: bool = False) -> None:\n \"\"\"Print a log message to the screen, and record the `data` into the `system` summary.\n\n Args:\n header: The prefix for the log message.\n data: A collection of data to be recorded.\n log_epoch: Whether epoch information should be included in the log message.\n \"\"\"\n log_message = header\n if log_epoch:\n log_message += \"epoch: {}; \".format(self.system.epoch_idx)\n self.system.write_summary('epoch', self.system.epoch_idx)\n for key, val in data.read_logs().items():\n val = to_number(val)\n self.system.write_summary(key, val)\n if val.size > 1:\n log_message += \"\\n{}:\\n{};\".format(key, np.array2string(val, separator=','))\n else:\n log_message += \"{}: {}; \".format(key, str(val))\n print(log_message)\n", "sub_path": "fastestimator/trace/trace.py", "file_name": "trace.py", "file_ext": "py", "file_size_in_byte": 11124, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "fastestimator.summary.system.System", "line_number": 67, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 68, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 69, "usage_type": "name"}, {"api_name": "typing.Set", "line_number": 70, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 73, "usage_type": "name"}, {"api_name": "typing.Iterable", "line_number": 73, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 74, "usage_type": "name"}, {"api_name": "typing.Iterable", "line_number": 74, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 75, "usage_type": "name"}, {"api_name": "typing.Iterable", "line_number": 75, "usage_type": "name"}, {"api_name": "fastestimator.util.util.to_list", "line_number": 76, "usage_type": "call"}, {"api_name": "fastestimator.util.util.to_list", "line_number": 77, "usage_type": "call"}, {"api_name": "fastestimator.util.util.parse_modes", "line_number": 78, "usage_type": "call"}, {"api_name": "fastestimator.util.util.to_set", "line_number": 78, "usage_type": "call"}, {"api_name": "fastestimator.util.data.Data", "line_number": 80, "usage_type": "name"}, {"api_name": "fastestimator.util.data.Data", "line_number": 88, "usage_type": "name"}, {"api_name": "fastestimator.util.data.Data", "line_number": 96, "usage_type": "name"}, {"api_name": "fastestimator.util.data.Data", "line_number": 104, "usage_type": "name"}, {"api_name": "fastestimator.util.data.Data", "line_number": 112, "usage_type": "name"}, {"api_name": "fastestimator.util.data.Data", "line_number": 120, "usage_type": "name"}, {"api_name": "fastestimator.util.traceability_util.traceable", "line_number": 28, "usage_type": "call"}, {"api_name": "typing.Set", "line_number": 138, "usage_type": "name"}, {"api_name": "fastestimator.util.data.Data", "line_number": 145, "usage_type": "name"}, {"api_name": "time.perf_counter", "line_number": 146, "usage_type": "call"}, {"api_name": "fastestimator.util.data.Data", "line_number": 150, "usage_type": "name"}, {"api_name": "time.perf_counter", "line_number": 152, "usage_type": "call"}, {"api_name": "time.perf_counter", "line_number": 153, "usage_type": "call"}, {"api_name": "fastestimator.util.data.Data", "line_number": 155, "usage_type": "name"}, {"api_name": "time.perf_counter", "line_number": 162, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 163, "usage_type": "call"}, {"api_name": "time.perf_counter", "line_number": 165, "usage_type": "call"}, {"api_name": "fastestimator.util.data.Data", "line_number": 167, "usage_type": "name"}, {"api_name": "time.perf_counter", "line_number": 169, "usage_type": "call"}, {"api_name": "time.perf_counter", "line_number": 170, "usage_type": "call"}, {"api_name": "fastestimator.util.data.Data", "line_number": 172, "usage_type": "name"}, {"api_name": "time.perf_counter", "line_number": 173, "usage_type": "call"}, {"api_name": "fastestimator.backend.get_lr.get_lr", "line_number": 176, "usage_type": "call"}, {"api_name": "fastestimator.util.traceability_util.traceable", "line_number": 129, "usage_type": "call"}, {"api_name": "typing.Set", "line_number": 188, "usage_type": "name"}, {"api_name": "fastestimator.util.data.Data", "line_number": 192, "usage_type": "name"}, {"api_name": "fastestimator.util.data.Data", "line_number": 195, "usage_type": "name"}, {"api_name": "fastestimator.util.data.Data", "line_number": 203, "usage_type": "name"}, {"api_name": "numpy.mean", "line_number": 205, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 205, "usage_type": "call"}, {"api_name": "fastestimator.util.traceability_util.traceable", "line_number": 179, "usage_type": "call"}, {"api_name": "fastestimator.util.data.Data", "line_number": 217, "usage_type": "name"}, {"api_name": "fastestimator.util.data.Data", "line_number": 222, "usage_type": "name"}, {"api_name": "fastestimator.util.data.Data", "line_number": 227, "usage_type": "name"}, {"api_name": "fastestimator.util.data.Data", "line_number": 235, "usage_type": "name"}, {"api_name": "fastestimator.util.data.Data", "line_number": 239, "usage_type": "name"}, {"api_name": "fastestimator.backend.to_number.to_number", "line_number": 252, "usage_type": "call"}, {"api_name": "numpy.array2string", "line_number": 255, "usage_type": "call"}, {"api_name": "fastestimator.util.traceability_util.traceable", "line_number": 208, "usage_type": "call"}]}
+{"seq_id": "183583134", "text": "from movies_dataframes import movies_df, ratings_df, users_df\nimport pandas as pd\nimport numpy as np\nfrom collections import Counter\n\ndef find_liked_disliked(x):\n liked_films_id = x.query('Rating.max() == Rating').MovieID.to_numpy()\n disliked_films_id = x.query('Rating.min() == Rating').MovieID.to_numpy()\n return pd.Series([liked_films_id, disliked_films_id],\n index=['liked_films', 'disliked_films'])\n\n\ndef match_film_name(movie_id):\n return movies_df.loc[movie_id].Name\n\n\ndef take_popular_genres(reviews):\n genres_list = movies_df.loc[reviews.MovieID].Genre.str.split('|').sum()\n favourite = Counter(genres_list).most_common(1)[0]\n return '{genre} ({times})'.format(genre=favourite[0], times=favourite[1])\n\n\nif __name__ == \"__main__\":\n vectorized_match = np.vectorize(match_film_name)\n\n mostly_watched_genres = ratings_df.groupby('UserID').\\\n apply(take_popular_genres).rename('mostly watched genre (times watched)')\n\n liked_disliked_id = ratings_df.groupby('UserID').\\\n apply(find_liked_disliked)\n\n liked_disliked_films = liked_disliked_id.applymap(vectorized_match)\n\n users_favourites = users_df.merge(mostly_watched_genres, left_index=True,\n right_index=True)\n users_favourites = users_favourites.merge(liked_disliked_films, left_index=True,\n right_index=True)\n\n users_favourites.to_csv('users_favourites.csv')\n", "sub_path": "data_analysis/movies_analysis/users_favourites/create_users_favourites.py", "file_name": "create_users_favourites.py", "file_ext": "py", "file_size_in_byte": 1476, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "pandas.Series", "line_number": 9, "usage_type": "call"}, {"api_name": "movies_dataframes.movies_df.loc", "line_number": 14, "usage_type": "attribute"}, {"api_name": "movies_dataframes.movies_df", "line_number": 14, "usage_type": "name"}, {"api_name": "movies_dataframes.movies_df.loc", "line_number": 18, "usage_type": "attribute"}, {"api_name": "movies_dataframes.movies_df", "line_number": 18, "usage_type": "name"}, {"api_name": "collections.Counter", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.vectorize", "line_number": 24, "usage_type": "call"}, {"api_name": "movies_dataframes.ratings_df.groupby", "line_number": 26, "usage_type": "call"}, {"api_name": "movies_dataframes.ratings_df", "line_number": 26, "usage_type": "name"}, {"api_name": "movies_dataframes.ratings_df.groupby", "line_number": 29, "usage_type": "call"}, {"api_name": "movies_dataframes.ratings_df", "line_number": 29, "usage_type": "name"}, {"api_name": "movies_dataframes.users_df.merge", "line_number": 34, "usage_type": "call"}, {"api_name": "movies_dataframes.users_df", "line_number": 34, "usage_type": "name"}]}
+{"seq_id": "418519344", "text": "from flask import Flask, render_template, request\nfrom flask.views import MethodView\nfrom wtforms import Form, StringField, SubmitField\nfrom wtforms.fields.core import SelectField\nfrom calorie import Calorie\nfrom temperature import Temperature\n\napp = Flask(__name__)\n\n\"\"\"\nADD COMMENT!\n\"\"\"\n\n\nclass HomePage(MethodView):\n \n def get(self):\n return render_template('index.html')\n\n\nclass CaloriesFormPage(MethodView):\n \n \"\"\"\n ADD COMMENT!\n \"\"\"\n\n def get(self):\n calories_form = CaloriesForm()\n return render_template('calories_form_page.html',\n caloriesform=calories_form) \n \n\n def post(self):\n calories_form = CaloriesForm(request.form)\n\n temperature = Temperature(country=calories_form.country.data,\n city= calories_form.city.data)\n\n current_temp = temperature.get_temperature()\n if current_temp != 'Error':\n calorie = Calorie(weight=float(calories_form.weight.data), \n height=float(calories_form.height.data),\n age=float(calories_form.age.data), \n sex=calories_form.sex.data,\n temperature=current_temp)\n\n calories_kcal, calorie_kJ = calorie.calculate()\n\n return render_template('calories_form_page.html',\n caloriesform=calories_form,\n city=temperature.city.upper(),\n country=temperature.country.upper(),\n current_temperature=current_temp, \n calories=calories_kcal,\n calories2=calorie_kJ,\n result=True)\n else:\n return render_template('calories_form_page.html',\n caloriesform=calories_form,\n city=temperature.city.upper(),\n country=temperature.country.upper(),\n current_temperature=False, \n result=True)\n\n\nclass CaloriesForm(Form):\n\n \"\"\"\n ADD COMMENT!\n \"\"\"\n \n # Widgets\n city = StringField(\"City: \", default=\"Ljubljana\")\n country = StringField(\"Country: \", default=\"Slovenia\")\n weight = StringField(\"Weight: \", default=70)\n height = StringField(\"Height: \", default=175)\n age = StringField(\"Age: \", default=30)\n #sex = StringField(\"Gender: \", default=\"Woman\")\n sex = SelectField(\"Gender: \", choices=[\"man\", \"woman\"]) \n button = SubmitField(\"Calculate\")\n\n\n#app.add_url_rule('/', view_func=HomePage.as_view('home_page'))\n#app.add_url_rule('/calories_form', view_func=CaloriesFormPage.as_view('calories_form_page'))\napp.add_url_rule('/', view_func=CaloriesFormPage.as_view('calories_form_page'))\n\napp.run(debug=True)", "sub_path": "flask_app.py", "file_name": "flask_app.py", "file_ext": "py", "file_size_in_byte": 2985, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "flask.Flask", "line_number": 8, "usage_type": "call"}, {"api_name": "flask.views.MethodView", "line_number": 15, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 18, "usage_type": "call"}, {"api_name": "flask.views.MethodView", "line_number": 21, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 29, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 34, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 34, "usage_type": "name"}, {"api_name": "temperature.Temperature", "line_number": 36, "usage_type": "call"}, {"api_name": "temperature.get_temperature", "line_number": 39, "usage_type": "call"}, {"api_name": "calorie.Calorie", "line_number": 41, "usage_type": "call"}, {"api_name": "calorie.calculate", "line_number": 47, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 49, "usage_type": "call"}, {"api_name": "temperature.city.upper", "line_number": 51, "usage_type": "call"}, {"api_name": "temperature.city", "line_number": 51, "usage_type": "attribute"}, {"api_name": "temperature.country.upper", "line_number": 52, "usage_type": "call"}, {"api_name": "temperature.country", "line_number": 52, "usage_type": "attribute"}, {"api_name": "flask.render_template", "line_number": 58, "usage_type": "call"}, {"api_name": "temperature.city.upper", "line_number": 60, "usage_type": "call"}, {"api_name": "temperature.city", "line_number": 60, "usage_type": "attribute"}, {"api_name": "temperature.country.upper", "line_number": 61, "usage_type": "call"}, {"api_name": "temperature.country", "line_number": 61, "usage_type": "attribute"}, {"api_name": "wtforms.Form", "line_number": 66, "usage_type": "name"}, {"api_name": "wtforms.StringField", "line_number": 73, "usage_type": "call"}, {"api_name": "wtforms.StringField", "line_number": 74, "usage_type": "call"}, {"api_name": "wtforms.StringField", "line_number": 75, "usage_type": "call"}, {"api_name": "wtforms.StringField", "line_number": 76, "usage_type": "call"}, {"api_name": "wtforms.StringField", "line_number": 77, "usage_type": "call"}, {"api_name": "wtforms.fields.core.SelectField", "line_number": 79, "usage_type": "call"}, {"api_name": "wtforms.SubmitField", "line_number": 80, "usage_type": "call"}]}
+{"seq_id": "219174317", "text": "# Copyright (c) 2015 Uber Technologies, Inc.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n_tornado_supported = False\n_stack_context_supported = False\n\nimport opentracing\ntry:\n import tornado # noqa\n _tornado_supported = True\n from opentracing.scope_managers.tornado import TornadoScopeManager\n from opentracing.scope_managers.tornado import tracer_stack_context\n _stack_context_supported = True\nexcept ImportError:\n pass\n\n\ndef is_tornado_supported():\n return _tornado_supported\n\n\ndef is_stack_context_supported():\n return _stack_context_supported\n\n\nclass _TracerEnteredStackContext(object):\n \"\"\"\n An entered tracer_stack_context() object.\n\n Intended to have a ready-to-use context where\n Span objects can be activated before the context\n itself is returned to the user.\n \"\"\"\n\n def __init__(self, context):\n self._context = context\n self._deactivation_cb = context.__enter__()\n\n def __enter__(self):\n return self._deactivation_cb\n\n def __exit__(self, type, value, traceback):\n return self._context.__exit__(type, value, traceback)\n\n\ndef span_in_stack_context(span):\n \"\"\"\n Create Tornado's (4.x, 5.x) StackContext that stores the given span in the\n thread-local request context. This function is intended for use\n in Tornado applications based on IOLoop, although will work fine\n in single-threaded apps like Flask, albeit with more overhead.\n\n StackContext has been deprecated in Tornado 6 and higher.\n Because of asyncio nature of Tornado 6.x, consider using\n `span_in_context` with opentracing scope manager `ContextVarScopeManager`\n\n ## Usage example in Tornado application\n\n Suppose you have a method `handle_request(request)` in the http server.\n Instead of calling it directly, use a wrapper:\n\n .. code-block:: python\n\n from opentracing_instrumentation import request_context\n\n @tornado.gen.coroutine\n def handle_request_wrapper(request, actual_handler, *args, **kwargs)\n\n request_wrapper = TornadoRequestWrapper(request=request)\n span = http_server.before_request(request=request_wrapper)\n\n with request_context.span_in_stack_context(span):\n return actual_handler(*args, **kwargs)\n\n :param span:\n :return:\n Return StackContext that wraps the request context.\n \"\"\"\n if not _tornado_supported:\n raise RuntimeError('span_in_stack_context requires Tornado')\n\n if not is_stack_context_supported():\n raise RuntimeError('tornado.stack_context is not supported in '\n 'Tornado >= 6.x')\n if not isinstance(\n opentracing.tracer.scope_manager, TornadoScopeManager\n ):\n raise RuntimeError('scope_manager is not TornadoScopeManager')\n\n # Enter the newly created stack context so we have\n # storage available for Span activation.\n context = tracer_stack_context()\n entered_context = _TracerEnteredStackContext(context)\n\n if span is None:\n return entered_context\n\n opentracing.tracer.scope_manager.activate(span, False)\n assert opentracing.tracer.active_span is not None\n assert opentracing.tracer.active_span is span\n\n return entered_context\n", "sub_path": "opentracing_instrumentation/tornado_context.py", "file_name": "tornado_context.py", "file_ext": "py", "file_size_in_byte": 4251, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "opentracing.scope_managers.tornado.TornadoScopeManager", "line_number": 103, "usage_type": "argument"}, {"api_name": "opentracing.tracer", "line_number": 103, "usage_type": "attribute"}, {"api_name": "opentracing.scope_managers.tornado.tracer_stack_context", "line_number": 109, "usage_type": "call"}, {"api_name": "opentracing.tracer.scope_manager.activate", "line_number": 115, "usage_type": "call"}, {"api_name": "opentracing.tracer", "line_number": 115, "usage_type": "attribute"}, {"api_name": "opentracing.tracer", "line_number": 116, "usage_type": "attribute"}, {"api_name": "opentracing.tracer", "line_number": 117, "usage_type": "attribute"}]}
+{"seq_id": "484743422", "text": "import json\r\nimport os\r\n\r\nfrom cloudshell.api.cloudshell_api import CloudShellAPISession, InputNameValue\r\n\r\n#print 'install_device_farm_app called: ' + str(os.environ)\r\n\r\nresource = json.loads(os.environ['RESOURCECONTEXT'])\r\nreservation = json.loads(os.environ['RESERVATIONCONTEXT'])\r\nconnectivity = json.loads(os.environ['QUALICONNECTIVITYCONTEXT'])\r\n\r\nresid = reservation['id']\r\n\r\n\r\n# service = resource['appData']['name']\r\n\r\n\r\napi = CloudShellAPISession(host=connectivity['serverAddress'],\r\n token_id=connectivity['adminAuthToken'],\r\n domain=reservation['domain'])\r\n\r\napi.WriteMessageToReservationOutput(resid, 'install_device_farm_app script called: ' + str(os.environ))\r\n# Temporary implementation bypassing the installation service:\r\n# try:\r\n# cp_resource = [x['value']\r\n# for x in resource['appData']['installationService']['attributes']\r\n# if x['name'] == 'AWS EC2'][0]\r\n# deploy_inputs = [InputNameValue(x['name'].lower().replace(' ', '_'), x['value'])\r\n# for x in resource['appData']['installationService']['attributes']\r\n# if x['name'] != 'AWS EC2']\r\n# except:\r\n# cp_resource = resource['attributes']['AWS EC2']\r\n# deploy_inputs = [InputNameValue(name.lower().replace(' ', '_'), value)\r\n# for name, value in resource['attributes'].iteritems()\r\n# if name != 'AWS EC2']\r\n\r\n# try:\r\n# result = api.ExecuteCommand(resid, cp_resource, \"Resource\", \"upload_app\", deploy_inputs)\r\n# except:\r\n\r\ndeployed_app_name = resource['deployedAppData']['name']\r\n\r\nresult = api.ExecuteResourceConnectedCommand(resid, deployed_app_name, \"upload_app_connected\", \"remote_app_management\", [\r\n resource['attributes']['APK URL'],\r\n resource['attributes']['APK Asset Updates'],\r\n])\r\n\r\n# Version that calls the installation service from this script\r\n# For this to work, update datamodel.xml on model \"AWS Mobile Device Installation\":\r\n# Change to SupportsConcurrentCommands=\"true\"\r\n\r\n# installation_result = api.InstallApp(reservationId=resid,\r\n# resourceName=service,\r\n# commandName='Install',\r\n# commandInputs=[],\r\n# printOutput=True)\r\n", "sub_path": "Environment/AWS Shell/Resource Scripts/install_device_farm_app.py", "file_name": "install_device_farm_app.py", "file_ext": "py", "file_size_in_byte": 2367, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "json.loads", "line_number": 8, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 8, "usage_type": "attribute"}, {"api_name": "json.loads", "line_number": 9, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 9, "usage_type": "attribute"}, {"api_name": "json.loads", "line_number": 10, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 10, "usage_type": "attribute"}, {"api_name": "cloudshell.api.cloudshell_api.CloudShellAPISession", "line_number": 18, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 22, "usage_type": "attribute"}]}
+{"seq_id": "515638922", "text": "\"\"\"\nUtility functions to export models to the Models dataset and get information about models currently being served\nin the project.\n\"\"\"\n\nfrom hops import hdfs, constants, util, exceptions, kafka\nfrom hops.experiment_impl.util import experiment_utils\nimport os\nimport json\nimport re\n\n\ndef exists(serving_name):\n \"\"\"\n Checks if there exists a serving with the given name\n\n Example use-case:\n\n >>> from hops import serving\n >>> serving.exist(serving_name)\n\n Args:\n :serving_name: the name of the serving\n\n Returns:\n True if the serving exists, otherwise false\n \"\"\"\n try:\n return get_id(serving_name) is not None\n except ServingNotFound as e:\n print(\"No serving with name {} was found in the project {}\".format(serving_name, hdfs.project_name()))\n return False\n\n\ndef delete(serving_name):\n \"\"\"\n Deletes serving instance with a given name\n\n Example use-case:\n\n >>> from hops import serving\n >>> serving.delete(\"irisFlowerClassifier\")\n\n Args:\n :serving_name: name of the serving to delete\n\n Returns:\n None\n \"\"\"\n serving_id = get_id(serving_name)\n print(\"Deleting serving with name: {}...\".format(serving_name))\n _delete_serving_rest(serving_id)\n print(\"Serving with name: {} successfully deleted\".format(serving_name))\n\n\ndef _delete_serving_rest(serving_id):\n \"\"\"\n Makes a REST request to Hopsworks REST API for deleting a serving instance\n\n Args:\n :serving_id: id of the serving to delete\n\n Returns:\n None\n\n Raises:\n :RestAPIError: if there was an error with the REST call to Hopsworks\n \"\"\"\n method = constants.HTTP_CONFIG.HTTP_DELETE\n resource_url = (constants.DELIMITERS.SLASH_DELIMITER +\n constants.REST_CONFIG.HOPSWORKS_REST_RESOURCE + constants.DELIMITERS.SLASH_DELIMITER +\n constants.REST_CONFIG.HOPSWORKS_PROJECT_RESOURCE + constants.DELIMITERS.SLASH_DELIMITER +\n hdfs.project_id() + constants.DELIMITERS.SLASH_DELIMITER +\n constants.REST_CONFIG.HOPSWORKS_SERVING_RESOURCE + constants.DELIMITERS.SLASH_DELIMITER\n + str(serving_id))\n response = util.send_request(method, resource_url)\n\n if response.status_code != 200:\n response_object = response.json()\n error_code, error_msg, user_msg = util._parse_rest_error(response_object)\n raise exceptions.RestAPIError(\"Could not delete serving with id {} (url: {}), \"\n \"server response: \\n \"\n \"HTTP code: {}, HTTP reason: {}, error code: {}, error msg: {}, \"\n \"user msg: {}\".format(serving_id, resource_url, response.status_code,\n response.reason, error_code, error_msg, user_msg))\n\n\ndef start(serving_name):\n \"\"\"\n Starts a model serving instance with a given name\n\n Example use-case:\n\n >>> from hops import serving\n >>> serving.start(\"irisFlowerClassifier\")\n\n Args:\n :serving_name: name of the serving to start\n\n Returns:\n None\n \"\"\"\n serving_id = get_id(serving_name)\n print(\"Starting serving with name: {}...\".format(serving_name))\n _start_or_stop_serving_rest(serving_id, constants.MODEL_SERVING.SERVING_ACTION_START)\n print(\"Serving with name: {} successfully started\".format(serving_name))\n\n\ndef stop(serving_name):\n \"\"\"\n Stops a model serving instance with a given name\n\n Example use-case:\n\n >>> from hops import serving\n >>> serving.stop(\"irisFlowerClassifier\")\n\n Args:\n :serving_name: name of the serving to stop\n\n Returns:\n None\n \"\"\"\n serving_id = get_id(serving_name)\n print(\"Stopping serving with name: {}...\".format(serving_name))\n _start_or_stop_serving_rest(serving_id, constants.MODEL_SERVING.SERVING_ACTION_STOP)\n print(\"Serving with name: {} successfully stopped\".format(serving_name))\n\n\ndef _start_or_stop_serving_rest(serving_id, action):\n \"\"\"\n Makes a REST request to Hopsworks REST API for starting/stopping a serving instance\n\n Args:\n :serving_id: id of the serving to start/stop\n :action: the action to perform (start or stop)\n\n Returns:\n None\n\n Raises:\n :RestAPIError: if there was an error with the REST call to Hopsworks\n \"\"\"\n method = constants.HTTP_CONFIG.HTTP_POST\n resource_url = (constants.DELIMITERS.SLASH_DELIMITER +\n constants.REST_CONFIG.HOPSWORKS_REST_RESOURCE + constants.DELIMITERS.SLASH_DELIMITER +\n constants.REST_CONFIG.HOPSWORKS_PROJECT_RESOURCE + constants.DELIMITERS.SLASH_DELIMITER +\n hdfs.project_id() + constants.DELIMITERS.SLASH_DELIMITER +\n constants.REST_CONFIG.HOPSWORKS_SERVING_RESOURCE + constants.DELIMITERS.SLASH_DELIMITER\n + str(serving_id) + constants.MODEL_SERVING.SERVING_START_OR_STOP_PATH_PARAM + action)\n response = util.send_request(method, resource_url)\n\n if response.status_code != 200:\n response_object = response.json()\n error_code, error_msg, user_msg = util._parse_rest_error(response_object)\n raise exceptions.RestAPIError(\"Could not perform action {} on serving with id {} (url: {}), \"\n \"server response: \\n \"\n \"HTTP code: {}, HTTP reason: {}, error code: {}, error msg: {}, \"\n \"user msg: {}\".format(action, serving_id, resource_url, response.status_code,\n response.reason, error_code, error_msg, user_msg))\n\n\ndef create_or_update(artifact_path, serving_name, serving_type=\"TENSORFLOW\", model_version=1,\n batching_enabled = False, topic_name=\"CREATE\", num_partitions = 1, num_replicas = 1,\n instances = 1):\n \"\"\"\n Creates a serving in Hopsworks if it does not exist, otherwise update the existing one.\n\n Example use-case:\n\n >>> from hops import serving\n >>> serving.create_or_update(\"/Models/mnist\", \"mnist\", \"TENSORFLOW\", 1)\n\n Args:\n :artifact_path: path to the artifact to serve (tf model dir or sklearn script)\n :serving_name: name of the serving to create\n :serving_type: type of the serving, e.g \"TENSORFLOW\" or \"SKLEARN\"\n :model_version: version of the model to serve\n :batching_enabled: boolean flag whether to enable batching for the inference requests\n :instances: the number of serving instances (the more instances the more inference requests can\n be served in parallel)\n\n Returns:\n None\n \"\"\"\n serving_id = get_id(serving_name)\n artifact_path = hdfs._expand_path(artifact_path)\n _validate_user_serving_input(artifact_path, serving_name, serving_type, model_version, batching_enabled,\n num_partitions, num_replicas, instances)\n artifact_path = hdfs.get_plain_path(artifact_path)\n print(\"Creating a serving for model {} ...\".format(serving_name))\n _create_or_update_serving_rest(artifact_path, serving_name, serving_type, model_version, batching_enabled,\n topic_name, num_partitions, num_replicas, serving_id, instances)\n print(\"Serving for model {} successfully created\".format(serving_name))\n\n\ndef _validate_user_serving_input(model_path, model_name, serving_type, model_version, batching_enabled,\n num_partitions, num_replicas, instances):\n \"\"\"\n Validate user input on the client side before sending REST call to Hopsworks (additional validation will be done\n in the backend)\n\n Args:\n :model_path: path to the model or artifact being served\n :model_name: the name of the serving to create\n :serving_type: the type of serving\n :model_version: version of the serving\n :batching_enabled: boolean flag whether to enable batching for inference requests to the serving\n :num_partitions: kafka partitions\n :num_replicas: kafka replicas\n :instances: the number of serving instances (the more instances the more inference requests can\n be served in parallel)\n\n Returns:\n None\n\n Raises:\n :ValueError: if the serving input failed the validation\n \"\"\"\n name_pattern = re.compile(\"^[a-zA-Z0-9]+$\")\n if len(model_name) > 256 or model_name == \"\" or not name_pattern.match(model_name):\n raise ValueError(\"Name of serving cannot be empty, cannot exceed 256 characters and must match the regular \"\n \"expression: ^[a-zA-Z0-9]+$, the provided name: {} is not valid\".format(model_name))\n if not hdfs.exists(model_path):\n raise ValueError(\"The model/artifact path must exist in HDFS, the provided path: {} \"\n \"does not exist\".format(model_path))\n if serving_type not in constants.MODEL_SERVING.SERVING_TYPES:\n raise ValueError(\"The provided serving_type: {} is not supported, supported \"\n \"serving types are: {}\".format(serving_type, \",\".join(constants.MODEL_SERVING.SERVING_TYPES)))\n if not isinstance(model_version, int):\n raise ValueError(\"The model version must be an integer, the provided version is not: {}\".format(model_version))\n if serving_type == constants.MODEL_SERVING.SERVING_TYPE_TENSORFLOW:\n if not isinstance(num_replicas, int):\n raise ValueError(\"Number of kafka topic replicas must be an integer, the provided num replicas \"\n \"is not: {}\".format(model_version))\n if not isinstance(num_partitions, int):\n raise ValueError(\"Number of kafka topic partitions must be an integer, the provided num partitions \"\n \"is not: {}\".format(num_partitions))\n if not isinstance(batching_enabled, bool):\n raise ValueError(\"Batching enabled must be a boolean, the provided value \"\n \"is not: {}\".format(batching_enabled))\n if not isinstance(instances, int):\n raise ValueError(\"The number of serving instances must be an integer, \"\n \"the provided version is not: {}\".format(instances))\n\n\ndef _create_or_update_serving_rest(model_path, model_name, serving_type, model_version,\n batching_enabled = None, topic_name=None, num_partitions = None,\n num_replicas = None, serving_id = None, instances=1):\n \"\"\"\n Makes a REST request to Hopsworks for creating or updating a model serving instance\n\n Args:\n :model_path: path to the model or artifact being served\n :model_name: the name of the serving to create\n :serving_type: the type of serving\n :model_version: version of the serving\n :batching_enabled: boolean flag whether to enable batching for inference requests to the serving\n :topic_name: name of the kafka topic (\"CREATE\" to create a new one, or \"NONE\" to not use kafka topic)\n :num_partitions: kafka partitions\n :num_replicas: kafka replicas\n :serving_id: the id of the serving in case of UPDATE, if serving_id is None, it is a CREATE operation.\n :instances: the number of serving instances (the more instances the more inference requests can\n be served in parallel)\n\n Returns:\n None\n\n Raises:\n :RestAPIError: if there was an error with the REST call to Hopsworks\n \"\"\"\n json_contents = {\n constants.REST_CONFIG.JSON_SERVING_MODEL_VERSION: model_version,\n constants.REST_CONFIG.JSON_SERVING_ARTIFACT_PATH: model_path,\n constants.REST_CONFIG.JSON_SERVING_TYPE: serving_type,\n constants.REST_CONFIG.JSON_SERVING_NAME: model_name,\n constants.REST_CONFIG.JSON_SERVING_KAFKA_TOPIC_DTO: {\n constants.REST_CONFIG.JSON_KAFKA_TOPIC_NAME: topic_name,\n constants.REST_CONFIG.JSON_KAFKA_NUM_PARTITIONS: num_partitions,\n constants.REST_CONFIG.JSON_KAFKA_NUM_REPLICAS: num_replicas\n },\n constants.REST_CONFIG.JSON_SERVING_REQUESTED_INSTANCES: instances,\n }\n if serving_id is not None:\n json_contents[constants.REST_CONFIG.JSON_SERVING_ID] = serving_id\n if serving_type == constants.MODEL_SERVING.SERVING_TYPE_TENSORFLOW:\n json_contents[constants.REST_CONFIG.JSON_SERVING_BATCHING_ENABLED] = batching_enabled\n json_embeddable = json.dumps(json_contents)\n headers = {constants.HTTP_CONFIG.HTTP_CONTENT_TYPE: constants.HTTP_CONFIG.HTTP_APPLICATION_JSON}\n method = constants.HTTP_CONFIG.HTTP_PUT\n resource_url = (constants.DELIMITERS.SLASH_DELIMITER +\n constants.REST_CONFIG.HOPSWORKS_REST_RESOURCE + constants.DELIMITERS.SLASH_DELIMITER +\n constants.REST_CONFIG.HOPSWORKS_PROJECT_RESOURCE + constants.DELIMITERS.SLASH_DELIMITER +\n hdfs.project_id() + constants.DELIMITERS.SLASH_DELIMITER +\n constants.REST_CONFIG.HOPSWORKS_SERVING_RESOURCE + constants.DELIMITERS.SLASH_DELIMITER)\n response = util.send_request(method, resource_url, data=json_embeddable, headers=headers)\n\n if response.status_code != 201 and response.status_code != 200:\n response_object = response.json()\n error_code, error_msg, user_msg = util._parse_rest_error(response_object)\n raise exceptions.RestAPIError(\"Could not create or update serving (url: {}), server response: \\n \" \\\n \"HTTP code: {}, HTTP reason: {}, error code: {}, error msg: {}, \"\n \"user msg: {}\".format(resource_url, response.status_code, response.reason,\n error_code, error_msg, user_msg))\n\ndef get_id(serving_name):\n \"\"\"\n Gets the id of a serving with a given name\n\n Example use-case:\n\n >>> from hops import serving\n >>> serving.get_id(serving_name)\n\n Args:\n :serving_name: name of the serving to get the id for\n\n Returns:\n the id of the serving, None if Serving does not exist\n \"\"\"\n try:\n servings = get_all()\n serving = _find_serving_with_name(serving_name, servings)\n return serving.id\n except ServingNotFound:\n return None\n\n\ndef get_artifact_path(serving_name):\n \"\"\"\n Gets the artifact path of a serving with a given name\n\n Example use-case:\n\n >>> from hops import serving\n >>> serving.get_artifact_path(serving_name)\n\n Args:\n :serving_name: name of the serving to get the artifact path for\n\n Returns:\n the artifact path of the serving (model path in case of tensorflow, or python script in case of SkLearn)\n \"\"\"\n servings = get_all()\n serving = _find_serving_with_name(serving_name, servings)\n return serving.artifact_path\n\n\ndef get_type(serving_name):\n \"\"\"\n Gets the type of a serving with a given name\n\n Example use-case:\n\n >>> from hops import serving\n >>> serving.get_type(serving_name)\n\n Args:\n :serving_name: name of the serving to get the typ for\n\n Returns:\n the type of the serving (e.g Tensorflow or SkLearn)\n \"\"\"\n servings = get_all()\n serving = _find_serving_with_name(serving_name, servings)\n return serving.serving_type\n\n\ndef get_version(serving_name):\n \"\"\"\n Gets the version of a serving with a given name\n\n Example use-case:\n\n >>> from hops import serving\n >>> serving.get_version(serving_name)\n\n Args:\n :serving_name: name of the serving to get the version for\n\n Returns:\n the version of the serving\n \"\"\"\n servings = get_all()\n serving = _find_serving_with_name(serving_name, servings)\n return serving.model_version\n\n\ndef get_kafka_topic(serving_name):\n \"\"\"\n Gets the kafka topic name of a serving with a given name\n\n Example use-case:\n\n >>> from hops import serving\n >>> serving.get_kafka_topic(serving_name)\n\n Args:\n :serving_name: name of the serving to get the kafka topic name for\n\n Returns:\n the kafka topic name of the serving\n \"\"\"\n servings = get_all()\n serving = _find_serving_with_name(serving_name, servings)\n return serving.kafka_topic_dto.name\n\n\ndef get_status(serving_name):\n \"\"\"\n Gets the status of a serving with a given name\n\n Example use-case:\n\n >>> from hops import serving\n >>> serving.get_status(serving_name)\n\n Args:\n :serving_name: name of the serving to get the status for\n\n Returns:\n the status of the serving\n \"\"\"\n servings = get_all()\n serving = _find_serving_with_name(serving_name, servings)\n return serving.status\n\n\ndef get_all():\n \"\"\"\n Gets the list of servings for the current project\n\n Example:\n\n >>> from hops import serving\n >>> servings = serving.get_all()\n >>> servings[0].name\n\n Returns:\n list of servings\n \"\"\"\n return _parse_json_servings(_get_servings_rest())\n\n\ndef _find_serving_with_name(serving_name, servings):\n \"\"\"\n Finds a serving with a given name from a list of servings (O(N))\n\n Args:\n :serving_name: name of the serving to look for\n :servings: the list of servings to look through\n\n Returns:\n serving with the given name\n\n Raises:\n :ServingNotFound: if the requested serving could not be found\n \"\"\"\n serving_names = []\n for serving in servings:\n if serving.name == serving_name:\n return serving\n serving_names.append(serving.name)\n serving_names_str = \",\".join(serving_names)\n raise ServingNotFound(\"No serving with name: {} could be found among the list of \"\n \"available servings: {}\".format(serving_name, serving_names_str))\n\n\ndef _parse_json_servings(json_servings):\n \"\"\"\n Parses a list of JSON servings into Serving Objects\n\n Args:\n :json_servings: the list of JSON servings\n\n Returns:\n a list of Serving Objects\n \"\"\"\n return list(map(lambda json_serving: Serving(json_serving), json_servings))\n\n\ndef _get_servings_rest():\n \"\"\"\n Makes a REST request to Hopsworks to get a list of all servings in the current project\n\n Returns:\n JSON response parsed as a python dict\n\n Raises:\n :RestAPIError: if there was an error with the REST call to Hopsworks\n \"\"\"\n method = constants.HTTP_CONFIG.HTTP_GET\n resource_url = (constants.DELIMITERS.SLASH_DELIMITER +\n constants.REST_CONFIG.HOPSWORKS_REST_RESOURCE + constants.DELIMITERS.SLASH_DELIMITER +\n constants.REST_CONFIG.HOPSWORKS_PROJECT_RESOURCE + constants.DELIMITERS.SLASH_DELIMITER +\n hdfs.project_id() + constants.DELIMITERS.SLASH_DELIMITER +\n constants.REST_CONFIG.HOPSWORKS_SERVING_RESOURCE + constants.DELIMITERS.SLASH_DELIMITER)\n response = util.send_request(method, resource_url)\n response_object = response.json()\n if response.status_code != 200:\n error_code, error_msg, user_msg = util._parse_rest_error(response_object)\n raise exceptions.RestAPIError(\"Could not fetch list of servings from Hopsworks REST API (url: {}), \"\n \"server response: \\n \"\n \"HTTP code: {}, HTTP reason: {}, error code: {}, \"\n \"error msg: {}, user msg: {}\".format(\n resource_url, response.status_code, response.reason, error_code, error_msg, user_msg))\n return response_object\n\n\ndef make_inference_request(serving_name, data, verb=\":predict\"):\n \"\"\"\n Submit an inference request\n\n Example use-case:\n\n >>> from hops import serving\n >>> serving.make_inference_request(\"irisFlowerClassifier\", [[1,2,3,4]], \":predict\")\n\n Args:\n :serving_name: name of the model being served\n :data: data/json to send to the serving\n :verb: type of request (:predict, :classify, or :regress)\n\n Returns:\n the JSON response\n \"\"\"\n return _make_inference_request_rest(serving_name, data, verb)\n\ndef _make_inference_request_rest(serving_name, data, verb):\n \"\"\"\n Makes a REST request to Hopsworks for submitting an inference request to the serving instance\n\n Args:\n :serving_name: name of the model being served\n :data: data/json to send to the serving\n :verb: type of request (:predict, :classify, or :regress)\n\n Returns:\n the JSON response\n\n Raises:\n :RestAPIError: if there was an error with the REST call to Hopsworks\n \"\"\"\n json_embeddable = json.dumps(data)\n headers = {constants.HTTP_CONFIG.HTTP_CONTENT_TYPE: constants.HTTP_CONFIG.HTTP_APPLICATION_JSON}\n method = constants.HTTP_CONFIG.HTTP_POST\n resource_url = (constants.DELIMITERS.SLASH_DELIMITER +\n constants.REST_CONFIG.HOPSWORKS_REST_RESOURCE + constants.DELIMITERS.SLASH_DELIMITER +\n constants.REST_CONFIG.HOPSWORKS_PROJECT_RESOURCE + constants.DELIMITERS.SLASH_DELIMITER +\n hdfs.project_id() + constants.DELIMITERS.SLASH_DELIMITER +\n constants.REST_CONFIG.HOPSWORKS_INFERENCE_RESOURCE + constants.DELIMITERS.SLASH_DELIMITER +\n constants.REST_CONFIG.HOPSWORKS_MODELS_RESOURCE + constants.DELIMITERS.SLASH_DELIMITER\n + serving_name + verb)\n response = util.send_request(method, resource_url, data=json_embeddable, headers=headers)\n response_object = response.json()\n error_code, error_msg, user_msg = util._parse_rest_error(response_object)\n\n if response.status_code != 201 and response.status_code != 200:\n raise exceptions.RestAPIError(\"Could not create or update serving (url: {}), server response: \\n \" \\\n \"HTTP code: {}, HTTP reason: {}, error code: {}, error msg: {}, \"\n \"user msg: {}\".format(resource_url, response.status_code, response.reason,\n error_code, error_msg, user_msg))\n return response_object\n\nclass Serving(object):\n \"\"\"\n Represents a model being served in Hopsworks\n \"\"\"\n\n def __init__(self, serving_json):\n \"\"\"\n Initialize the serving from JSON payload returned by Hopsworks REST API\n\n Args:\n :feature_json: JSON data about the feature returned from Hopsworks REST API\n \"\"\"\n self.status = serving_json[constants.REST_CONFIG.JSON_SERVING_STATUS]\n self.artifact_path = serving_json[constants.REST_CONFIG.JSON_SERVING_ARTIFACT_PATH]\n self.name = serving_json[constants.REST_CONFIG.JSON_SERVING_NAME]\n self.creator = serving_json[constants.REST_CONFIG.JSON_SERVING_CREATOR]\n self.creator = serving_json[constants.REST_CONFIG.JSON_SERVING_CREATOR]\n self.serving_type = serving_json[constants.REST_CONFIG.JSON_SERVING_TYPE]\n self.model_version = serving_json[constants.REST_CONFIG.JSON_SERVING_MODEL_VERSION]\n self.created = serving_json[constants.REST_CONFIG.JSON_SERVING_CREATED]\n self.requested_instances = serving_json[constants.REST_CONFIG.JSON_SERVING_REQUESTED_INSTANCES]\n if constants.REST_CONFIG.JSON_SERVING_KAFKA_TOPIC_DTO in serving_json:\n self.kafka_topic_dto = kafka.KafkaTopicDTO(serving_json[constants.REST_CONFIG.JSON_SERVING_KAFKA_TOPIC_DTO])\n self.id = serving_json[constants.REST_CONFIG.JSON_SERVING_ID]\n\n\nclass ServingNotFound(Exception):\n \"\"\"This exception will be raised if the requested serving could not be found\"\"\"\n", "sub_path": "hops/serving.py", "file_name": "serving.py", "file_ext": "py", "file_size_in_byte": 23687, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "hops.hdfs.project_name", "line_number": 31, "usage_type": "call"}, {"api_name": "hops.hdfs", "line_number": 31, "usage_type": "name"}, {"api_name": "hops.constants.HTTP_CONFIG", "line_number": 69, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 69, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 70, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 70, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 71, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 71, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 71, "usage_type": "attribute"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 72, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 72, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 72, "usage_type": "attribute"}, {"api_name": "hops.hdfs.project_id", "line_number": 73, "usage_type": "call"}, {"api_name": "hops.hdfs", "line_number": 73, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 73, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 73, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 74, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 74, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 74, "usage_type": "attribute"}, {"api_name": "hops.util.send_request", "line_number": 76, "usage_type": "call"}, {"api_name": "hops.util", "line_number": 76, "usage_type": "name"}, {"api_name": "hops.util._parse_rest_error", "line_number": 80, "usage_type": "call"}, {"api_name": "hops.util", "line_number": 80, "usage_type": "name"}, {"api_name": "hops.exceptions.RestAPIError", "line_number": 81, "usage_type": "call"}, {"api_name": "hops.exceptions", "line_number": 81, "usage_type": "name"}, {"api_name": "hops.constants.MODEL_SERVING", "line_number": 105, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 105, "usage_type": "name"}, {"api_name": "hops.constants.MODEL_SERVING", "line_number": 126, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 126, "usage_type": "name"}, {"api_name": "hops.constants.HTTP_CONFIG", "line_number": 144, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 144, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 145, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 145, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 146, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 146, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 146, "usage_type": "attribute"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 147, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 147, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 147, "usage_type": "attribute"}, {"api_name": "hops.hdfs.project_id", "line_number": 148, "usage_type": "call"}, {"api_name": "hops.hdfs", "line_number": 148, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 148, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 148, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 149, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 149, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 149, "usage_type": "attribute"}, {"api_name": "hops.constants.MODEL_SERVING", "line_number": 150, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 150, "usage_type": "name"}, {"api_name": "hops.util.send_request", "line_number": 151, "usage_type": "call"}, {"api_name": "hops.util", "line_number": 151, "usage_type": "name"}, {"api_name": "hops.util._parse_rest_error", "line_number": 155, "usage_type": "call"}, {"api_name": "hops.util", "line_number": 155, "usage_type": "name"}, {"api_name": "hops.exceptions.RestAPIError", "line_number": 156, "usage_type": "call"}, {"api_name": "hops.exceptions", "line_number": 156, "usage_type": "name"}, {"api_name": "hops.hdfs._expand_path", "line_number": 187, "usage_type": "call"}, {"api_name": "hops.hdfs", "line_number": 187, "usage_type": "name"}, {"api_name": "hops.hdfs.get_plain_path", "line_number": 190, "usage_type": "call"}, {"api_name": "hops.hdfs", "line_number": 190, "usage_type": "name"}, {"api_name": "re.compile", "line_number": 220, "usage_type": "call"}, {"api_name": "hops.hdfs.exists", "line_number": 224, "usage_type": "call"}, {"api_name": "hops.hdfs", "line_number": 224, "usage_type": "name"}, {"api_name": "hops.constants.MODEL_SERVING", "line_number": 227, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 227, "usage_type": "name"}, {"api_name": "hops.constants.MODEL_SERVING", "line_number": 229, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 229, "usage_type": "name"}, {"api_name": "hops.constants.MODEL_SERVING", "line_number": 232, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 232, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 273, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 273, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 274, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 274, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 275, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 275, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 276, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 276, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 277, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 277, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 282, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 282, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 278, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 278, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 279, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 279, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 280, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 280, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 285, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 285, "usage_type": "name"}, {"api_name": "hops.constants.MODEL_SERVING", "line_number": 286, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 286, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 287, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 287, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 288, "usage_type": "call"}, {"api_name": "hops.constants.HTTP_CONFIG", "line_number": 289, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 289, "usage_type": "name"}, {"api_name": "hops.constants.HTTP_CONFIG", "line_number": 290, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 290, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 291, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 291, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 292, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 292, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 292, "usage_type": "attribute"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 293, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 293, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 293, "usage_type": "attribute"}, {"api_name": "hops.hdfs.project_id", "line_number": 294, "usage_type": "call"}, {"api_name": "hops.hdfs", "line_number": 294, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 294, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 294, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 295, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 295, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 295, "usage_type": "attribute"}, {"api_name": "hops.util.send_request", "line_number": 296, "usage_type": "call"}, {"api_name": "hops.util", "line_number": 296, "usage_type": "name"}, {"api_name": "hops.util._parse_rest_error", "line_number": 300, "usage_type": "call"}, {"api_name": "hops.util", "line_number": 300, "usage_type": "name"}, {"api_name": "hops.exceptions.RestAPIError", "line_number": 301, "usage_type": "call"}, {"api_name": "hops.exceptions", "line_number": 301, "usage_type": "name"}, {"api_name": "hops.constants.HTTP_CONFIG", "line_number": 492, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 492, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 493, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 493, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 494, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 494, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 494, "usage_type": "attribute"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 495, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 495, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 495, "usage_type": "attribute"}, {"api_name": "hops.hdfs.project_id", "line_number": 496, "usage_type": "call"}, {"api_name": "hops.hdfs", "line_number": 496, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 496, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 496, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 497, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 497, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 497, "usage_type": "attribute"}, {"api_name": "hops.util.send_request", "line_number": 498, "usage_type": "call"}, {"api_name": "hops.util", "line_number": 498, "usage_type": "name"}, {"api_name": "hops.util._parse_rest_error", "line_number": 501, "usage_type": "call"}, {"api_name": "hops.util", "line_number": 501, "usage_type": "name"}, {"api_name": "hops.exceptions.RestAPIError", "line_number": 502, "usage_type": "call"}, {"api_name": "hops.exceptions", "line_number": 502, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 544, "usage_type": "call"}, {"api_name": "hops.constants.HTTP_CONFIG", "line_number": 545, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 545, "usage_type": "name"}, {"api_name": "hops.constants.HTTP_CONFIG", "line_number": 546, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 546, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 547, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 547, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 548, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 548, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 548, "usage_type": "attribute"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 549, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 549, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 549, "usage_type": "attribute"}, {"api_name": "hops.hdfs.project_id", "line_number": 550, "usage_type": "call"}, {"api_name": "hops.hdfs", "line_number": 550, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 550, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 550, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 551, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 551, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 551, "usage_type": "attribute"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 552, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 552, "usage_type": "name"}, {"api_name": "hops.constants.DELIMITERS", "line_number": 552, "usage_type": "attribute"}, {"api_name": "hops.util.send_request", "line_number": 554, "usage_type": "call"}, {"api_name": "hops.util", "line_number": 554, "usage_type": "name"}, {"api_name": "hops.util._parse_rest_error", "line_number": 556, "usage_type": "call"}, {"api_name": "hops.util", "line_number": 556, "usage_type": "name"}, {"api_name": "hops.exceptions.RestAPIError", "line_number": 559, "usage_type": "call"}, {"api_name": "hops.exceptions", "line_number": 559, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 577, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 577, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 578, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 578, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 579, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 579, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 580, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 580, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 581, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 581, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 582, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 582, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 583, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 583, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 584, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 584, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 585, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 585, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 586, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 586, "usage_type": "name"}, {"api_name": "hops.kafka.KafkaTopicDTO", "line_number": 587, "usage_type": "call"}, {"api_name": "hops.kafka", "line_number": 587, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 587, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 587, "usage_type": "name"}, {"api_name": "hops.constants.REST_CONFIG", "line_number": 588, "usage_type": "attribute"}, {"api_name": "hops.constants", "line_number": 588, "usage_type": "name"}]}
+{"seq_id": "396694993", "text": "from PyQt5.QtWidgets import QWidget, QApplication\nfrom PyQt5.QtCore import QPoint, Qt\nfrom PyQt5.QtGui import QPixmap\nfrom Readerinfo_ui import Ui_Form\nimport sys\n\nclass ReaderinfoUi(QWidget, Ui_Form):\n def __init__(self, info, parent=None):\n super().__init__()\n self.info = info\n self.parent = parent\n self.setupUi(self)\n self._drag = False\n self.m_DragPosition = QPoint()\n self.init_ui()\n\n def init_ui(self):\n self.setFixedSize(331, 252)\n self.setWindowOpacity(0.9)\n self.setAttribute(Qt.WA_TranslucentBackground)\n self.setWindowFlag(Qt.FramelessWindowHint)\n\n self.id_label.setText(self.info[0])\n self.name_label.setText(self.info[1])\n self.sex_label.setText(self.info[2])\n self.dept_label.setText(self.info[4])\n self.grade_label.setText(self.info[3])\n\n self.setupSignal()\n\n \n self.setStyleSheet(\n '''QWidget#widget_2{\n background:gray;\n border-top:1px solid white;\n border-bottom:1px solid white;\n border-left:1px solid white;\n border-top-left-radius:10px;\n border-bottom-left-radius:10px;\n }\n QWidget#widget_3{\n color:#232C51;\n background:white;\n border-top:1px solid darkGray;\n border-bottom:1px solid darkGray;\n border-right:1px solid darkGray;\n border-top-right-radius:10px;\n border-bottom-right-radius:10px;\n }\n QPushButton{\n background-color: #4CAF50; \n border: none;\n color: white;\n border-radius:5px;\n padding: 5px 15px;\n text-align: center;\n text-decoration: none;\n display: inline-block;\n font-size: 16px;\n }\n QPushButton:hover{\n background:green;}\n ''')\n self.close_bt.setStyleSheet('''QPushButton{background:#F76677;border-radius:5px;}QPushButton:hover{background:red;}''')\n self.none_bt.setStyleSheet('''QPushButton{background:#F7D674;border-radius:5px;}QPushButton:hover{background:yellow;}''')\n self.min_bt.setStyleSheet('''QPushButton{background:#6DDF6D;border-radius:5px;}QPushButton:hover{background:green;}''')\n\n pix = QPixmap('../image/bg4.jpg')\n self.pic_label.setPixmap(pix)\n self.pic_label.setScaledContents(True)\n\n def setupSignal(self):\n self.close_bt.clicked.connect(self.close)\n self.min_bt.clicked.connect(self.showMinimized)\n\n\n def mousePressEvent(self, event):\n if event.button()== Qt.LeftButton:\n self.m_drag=True\n self.m_DragPosition=event.globalPos()-self.pos()\n event.accept()\n\n def mouseMoveEvent(self, QMouseEvent):\n if QMouseEvent.buttons() and Qt.LeftButton:\n self.move(QMouseEvent.globalPos()-self.m_DragPosition)\n QMouseEvent.accept()\n\n def mouseReleaseEvent(self, QMouseEvent):\n self.m_drag=False\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n gui = ReaderinfoUi(None)\n gui.show()\n sys.exit(app.exec_())", "sub_path": "code/readerinfo_window.py", "file_name": "readerinfo_window.py", "file_ext": "py", "file_size_in_byte": 3247, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 7, "usage_type": "name"}, {"api_name": "Readerinfo_ui.Ui_Form", "line_number": 7, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.QPoint", "line_number": 14, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt.WA_TranslucentBackground", "line_number": 20, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 20, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt.FramelessWindowHint", "line_number": 21, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 21, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QPixmap", "line_number": 68, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt.LeftButton", "line_number": 78, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 78, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt.LeftButton", "line_number": 84, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 84, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 92, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 92, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 95, "usage_type": "call"}]}
+{"seq_id": "471573305", "text": "# -*- coding: utf-8 -*-\n\n\n# 去掉函数中参数值是None的参数\nimport functools\n\n\ndef filter_none_param(func):\n @functools.wraps(func)\n def _wrapper(*args, **kwargs):\n params = dict()\n for key in kwargs:\n if kwargs[key] is not None:\n params[key] = kwargs[key]\n return func(*args, **params)\n return _wrapper\n", "sub_path": "common_app/decorator.py", "file_name": "decorator.py", "file_ext": "py", "file_size_in_byte": 369, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "functools.wraps", "line_number": 9, "usage_type": "call"}]}
+{"seq_id": "288251408", "text": "import collections\n\nfrom django.db import migrations, transaction\n\n\ndef update_report_fields(apps, schema_editor):\n ComplianceReport = apps.get_model('api', 'compliancereport')\n for report in ComplianceReport.objects.filter(supplements__isnull=False, latest_report__isnull=True):\n with transaction.atomic():\n ancestor = report\n root = None\n latest = None\n while ancestor.supplements is not None:\n ancestor = ancestor.supplements\n\n visited = []\n id_traversal = {}\n to_visit = collections.deque([ancestor.id])\n i = 0\n\n while len(to_visit) > 0:\n current_id = to_visit.popleft()\n\n # break loops\n if current_id in visited:\n continue\n visited.append(current_id)\n\n current = ComplianceReport.objects.get(id=current_id)\n\n if current.supplements is None:\n root = current\n latest = current\n # don't count non-supplement reports (really should just be the root)\n if current.supplements is not None and \\\n not current.status.fuel_supplier_status_id == \"Deleted\":\n latest = current\n i += 1\n id_traversal[current_id] = i\n for descendant in current.supplemental_reports.order_by('create_timestamp').all():\n to_visit.append(descendant.id)\n\n for compliance_id, traversal in id_traversal.items():\n ComplianceReport.objects.filter(id=int(compliance_id)) \\\n .update(latest_report=latest, root_report=root, traversal=traversal)\n for report in ComplianceReport.objects.filter(supplements__isnull=True, latest_report__isnull=True):\n ComplianceReport.objects.filter(id=report.id) \\\n .update(latest_report=report, root_report=report)\n\n\nclass Migration(migrations.Migration):\n dependencies = [\n ('api', '0003_auto_20230526_1452'),\n ]\n\n operations = [\n migrations.RunPython(update_report_fields, reverse_code=migrations.RunPython.noop),\n ]\n", "sub_path": "backend/api/migrations/0004_migrate_compliance_report.py", "file_name": "0004_migrate_compliance_report.py", "file_ext": "py", "file_size_in_byte": 2219, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "django.db.transaction.atomic", "line_number": 9, "usage_type": "call"}, {"api_name": "django.db.transaction", "line_number": 9, "usage_type": "name"}, {"api_name": "collections.deque", "line_number": 18, "usage_type": "call"}, {"api_name": "django.db.migrations.Migration", "line_number": 51, "usage_type": "attribute"}, {"api_name": "django.db.migrations", "line_number": 51, "usage_type": "name"}, {"api_name": "django.db.migrations.RunPython", "line_number": 57, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 57, "usage_type": "name"}]}
+{"seq_id": "3068377", "text": "# coding=utf-8\nimport re\nimport json\nfrom pychroner import PluginMeta, PluginType\n\n@PluginMeta(PluginType.TwitterReply, twitterAccount=\"SlashNephy\")\ndef do(pluginApi, stream):\n if stream[\"user\"][\"screen_name\"] == \"SlashNephy\":\n api = pluginApi.getTwitterAccount().getHandler()\n\n m = re.match(\"^@{} makepoll (.+?)$\".format(stream[\"user\"][\"screen_name\"]), stream[\"text\"], re.IGNORECASE)\n if m:\n try:\n t = json.loads(m.group(1))\n api.create_poll(t[\"text\"], t[\"choices\"], minutes=t.get(\"minutes\", 1440))\n\n except:\n api.statuses_update(status=f\"@{stream['user']['screen_name']} JSONが不正です\")\n", "sub_path": "plugins/SlashNephy/MakePoll.py", "file_name": "MakePoll.py", "file_ext": "py", "file_size_in_byte": 686, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "re.match", "line_number": 11, "usage_type": "call"}, {"api_name": "re.IGNORECASE", "line_number": 11, "usage_type": "attribute"}, {"api_name": "json.loads", "line_number": 14, "usage_type": "call"}, {"api_name": "pychroner.PluginMeta", "line_number": 6, "usage_type": "call"}, {"api_name": "pychroner.PluginType.TwitterReply", "line_number": 6, "usage_type": "attribute"}, {"api_name": "pychroner.PluginType", "line_number": 6, "usage_type": "name"}]}
+{"seq_id": "366018240", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon May 14 19:38:34 2018\r\n\r\nload a trained model an use it on preprocessed data\r\n\r\n@author: Wolfgang Kapferer\r\n\"\"\"\r\nfrom keras.models import model_from_json\r\nimport numpy as np\r\n\r\ndef load_model_and_apply(preprocessed):\r\n\r\n resultForDatabase=[]\r\n \r\n model=np.float32(preprocessed)\r\n \r\n input_model=model[:,1:len(model[0])-1]\r\n \r\n pk = model[:,0]\r\n resultForDatabase.append(pk)\r\n \r\n # load json and create model\r\n json_file = open('model.json', 'r')\r\n loaded_model_json = json_file.read()\r\n json_file.close()\r\n loaded_model = model_from_json(loaded_model_json)\r\n # load weights into new model\r\n loaded_model.load_weights(\"model.h5\")\r\n print(\"Loaded model from disk\")\r\n \r\n prediction = loaded_model.predict(input_model)\r\n resultForDatabase.append(prediction)\r\n \r\n return resultForDatabase\r\n", "sub_path": "keras_load_model_and_apply.py", "file_name": "keras_load_model_and_apply.py", "file_ext": "py", "file_size_in_byte": 896, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "numpy.float32", "line_number": 16, "usage_type": "call"}, {"api_name": "keras.models.model_from_json", "line_number": 27, "usage_type": "call"}]}
+{"seq_id": "418306641", "text": "#!/usr/bin/python\n__author__ = 'james harrison'\n\nimport json\nimport requests\nimport xml.etree.ElementTree as ET\n\n\n\nclass Helper(object):\n def __init__(self):\n self.uni_to_home = \"2110\"\n self.home_to_uni = \"1262\"\n self.ROUTE = \"P\"\n\n self.base_url = \"http://rtt.metroinfo.org.nz/rtt/public/utility/file.aspx?\"\n self.payload = {\"contenttype\": \"SQLXML\",\n \"Name\": \"JPRoutePositionET.xml\"}\n\n def get_data(self, platform):\n ''' Fetches the xml data for a given platform'''\n self.payload[\"PlatformTag\"] = platform\n return requests.get(self.base_url, params=self.payload).text[3:]\n\n def get_bus_times(self, xml):\n ''' Get the bus times that matches self.ROUTE from the xml data '''\n times = []\n bus_line = []\n root = ET.fromstring(xml)\n\n for route in root[1]:\n if route.attrib[\"RouteNo\"] == self.ROUTE:\n bus_line = route\n\n for bus in bus_line:\n for trip in bus:\n times.append(int(trip.attrib[\"ETA\"]))\n return times\n\n def print_times(self, times):\n if len(times) > 0:\n for time in sorted(times):\n print(str(time) + \" minutes\")\n else:\n print(\"Sorry no buses going that way :(\")\n\n def main(self):\n home_to_uni_data = self.get_data(self.home_to_uni)\n home_to_uni_times = self.get_bus_times(home_to_uni_data)\n uni_to_home_data = self.get_data(self.uni_to_home)\n uni_to_home_times = self.get_bus_times(uni_to_home_data)\n print(\"------------------------------------------------------\")\n print(\"Home to Uni:\")\n self.print_times(home_to_uni_times)\n print(\"Uni to Home:\")\n self.print_times(uni_to_home_times)\n print(\"------------------------------------------------------\")\n\nif __name__ == \"__main__\":\n helper = Helper()\n helper.main()", "sub_path": "bus.py", "file_name": "bus.py", "file_ext": "py", "file_size_in_byte": 1938, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "requests.get", "line_number": 23, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree.fromstring", "line_number": 29, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 29, "usage_type": "argument"}]}
+{"seq_id": "635457615", "text": "# -*- coding: utf-8 -*-\nimport json\nimport logging\n\nfrom django.conf import settings\nfrom django.template.loader import render_to_string\nfrom django.utils.crypto import get_random_string\nfrom django.utils.translation import ugettext_lazy as _\nfrom rest_framework import response, viewsets\nfrom rest_framework.renderers import BrowsableAPIRenderer\n\nfrom backend.accounts import bcs_perm\nfrom backend.bcs_web.audit_log import client\nfrom backend.components import paas_cc\nfrom backend.uniapps.network.clb import constants as clb_constants\nfrom backend.uniapps.network.clb import serializers\nfrom backend.uniapps.network.clb import utils as clb_utils\nfrom backend.uniapps.network.clb.models import CloudLoadBlancer\nfrom backend.utils.error_codes import error_codes\nfrom backend.utils.renderers import BKAPIRenderer\n\n\nclass DescribeCLBNamesViewSet(viewsets.ViewSet):\n renderer_classes = (BKAPIRenderer, BrowsableAPIRenderer)\n\n def list(self, request, project_id):\n data = clb_utils.describe_clb_detail(\n request.user.token.access_token,\n request.user.username,\n request.project.cc_app_id,\n request.query_params.get('region'),\n )\n return response.Response(data.keys())\n\n\nclass CLBListCreateViewSet(viewsets.ViewSet):\n renderer_classes = (BKAPIRenderer, BrowsableAPIRenderer)\n\n def add_status_and_cluster_name(self, request, project_id, data):\n # 只有已经启动的clb,才能查询到状态\n cluster_id_list = [info['cluster_id'] for info in data]\n clb_dict = {}\n for cluster_id in cluster_id_list:\n clb_dict.update(\n clb_utils.get_deployments(\n request.user.token.access_token, project_id, request.project.kind, cluster_id\n )\n )\n # add status and cluster_name to data\n cluster_id_names = clb_utils.get_cluster_id_names_map(request.user.token.access_token, project_id)\n for info in data:\n filter_key = (info['cluster_id'], info['resource_name'])\n info['cluster_name'] = cluster_id_names.get(info['cluster_id']) or ''\n if filter_key in clb_dict:\n info.update(clb_dict[filter_key])\n return data\n\n def list(self, request, project_id):\n cluster_id = request.query_params.get(\"cluster_id\")\n data = CloudLoadBlancer.objects.get_clb_list(project_id, cluster_id=cluster_id)\n data = self.add_status_and_cluster_name(request, project_id, data)\n\n # 添加权限\n data = bcs_perm.Cluster.hook_perms(request, project_id, data)\n\n return response.Response(data)\n\n def get_vpc_id(self, request, region, clb_name):\n data = clb_utils.describe_clb_detail(\n request.user.token.access_token, request.user.username, request.project.cc_app_id, region\n )\n if clb_name not in data:\n raise error_codes.CheckFailed(f'clb:[{clb_name}] not found')\n return data[clb_name]['vpc_id']\n\n def create(self, request, project_id):\n slz = serializers.CreateCLBSLZ(data=request.data)\n slz.is_valid(raise_exception=True)\n data = slz.validated_data\n # 校验集群权限\n clb_utils.can_use_cluster(request, project_id, data['cluster_id'])\n\n # 通过clb_name渲染deployment\n # 替换clb中的'_'为'-', 后缀使用6位随机字符,并且长度限制为253以内,以满足后台的限制\n # resource_name包含: clb_name[:246] + '-' + random(6)\n replaced_name = data['clb_name'].replace('_', '-')\n data['resource_name'] = f'{replaced_name[:246]}-{get_random_string(6).lower()}'\n data['creator'] = data['updator'] = request.user.username\n data['project_id'] = request.project.project_id\n data['vpc_id'] = self.get_vpc_id(request, data['region'], data['clb_name'])\n\n # 创建并返回记录\n with client.ContextActivityLogClient(\n project_id=project_id,\n user=request.user.username,\n resource_type='lb',\n resource=data['clb_name'],\n description=_(\"集群:{}, 创建云lb controler\").format(data['cluster_id']),\n ).log_add():\n record = CloudLoadBlancer.objects.create(data)\n data = CloudLoadBlancer.objects.parse_record(record)\n\n return response.Response(data)\n\n\nclass MesosCLBOperateViewSet(viewsets.ViewSet):\n renderer_classes = (BKAPIRenderer, BrowsableAPIRenderer)\n\n def update_clb_status(self, clb_id, status):\n CloudLoadBlancer.objects.filter(id=clb_id).update(status=status)\n\n def post(self, request, project_id, clb_id):\n # 获取配置\n record = CloudLoadBlancer.objects.retrieve_record(clb_id)\n # 校验使用集群权限\n clb_utils.can_use_cluster(request, project_id, record['cluster_id'])\n # 获取 repo 地址\n repo_domain = paas_cc.get_jfrog_domain(request.user.token.access_token, project_id, record['cluster_id'])\n if not repo_domain:\n repo_domain = settings.DEFAUT_MESOS_LB_JFROG_DOMAIN\n record['repo_domain'] = repo_domain\n mesos_json = json.loads(render_to_string('mesos.json', record))\n\n with client.ContextActivityLogClient(\n project_id=project_id,\n user=request.user.username,\n resource_type='lb',\n resource=record['resource_name'],\n description=_(\"集群:{}, 创建clb关联deployment:{}\").format(record['cluster_id'], record['resource_name']),\n ).log_add():\n clb_utils.create_mesos_deployment(\n request.user.token.access_token, project_id, record['cluster_id'], record['namespace'], mesos_json\n )\n # 更改状态\n self.update_clb_status(clb_id, clb_constants.CLB_CREATED_STATUS)\n\n return response.Response()\n\n def delete(self, request, project_id, clb_id):\n record = CloudLoadBlancer.objects.retrieve_record(clb_id)\n # 校验使用集群权限\n clb_utils.can_use_cluster(request, project_id, record['cluster_id'])\n\n with client.ContextActivityLogClient(\n project_id=project_id,\n user=request.user.username,\n resource_type='lb',\n resource=record['resource_name'],\n description=_(\"集群:{}, 删除clb关联deployment:{}\").format(record['cluster_id'], record['resource_name']),\n ).log_delete():\n clb_utils.delete_mesos_deployment(\n request.user.token.access_token,\n project_id,\n record['cluster_id'],\n record['namespace'],\n record['resource_name'],\n )\n # 更新状态\n self.update_clb_status(clb_id, clb_constants.CLB_DELETED_STATUS)\n\n return response.Response()\n\n\nclass CLBRetrieveOperateViewSet(viewsets.ViewSet):\n renderer_classes = (BKAPIRenderer, BrowsableAPIRenderer)\n\n def add_status(self, request, data):\n if data['status'] != clb_constants.CLB_CREATED_STATUS:\n return data\n deployment_status = clb_utils.get_deployments(\n request.user.token.access_token,\n data['project_id'],\n request.project.kind,\n data['cluster_id'],\n name=data['resource_name'],\n )\n data.update(deployment_status)\n return data\n\n def retrieve(self, request, project_id, clb_id):\n data = CloudLoadBlancer.objects.retrieve_record(clb_id)\n data = self.add_status(request, data)\n # 添加集群名称\n data['cluster_name'] = clb_utils.get_cluster_name(\n request.user.token.access_token, project_id, data['cluster_id']\n )\n\n return response.Response(data)\n\n def delete(self, request, project_id, clb_id):\n # 获取操作对象\n record = CloudLoadBlancer.objects.retrieve(clb_id)\n if record.status not in clb_constants.ALLOW_UPDATE_DELETE_STATUS_LIST:\n raise error_codes.CheckFailed(_('当前clb状态不允许进行删除操作'))\n # 校验使用集群权限\n clb_utils.can_use_cluster(request, project_id, record.cluster_id)\n\n with client.ContextActivityLogClient(\n project_id=project_id,\n user=request.user.username,\n resource_type='lb',\n resource=record.clb_name,\n description=_(\"集群:{}, 删除clb:{}\").format(record.cluster_id, record.clb_name),\n ).log_delete():\n record.delete()\n\n return response.Response()\n\n def update(self, request, project_id, clb_id):\n slz = serializers.UpdateCLBSLZ(data=request.data)\n slz.is_valid(raise_exception=True)\n data = slz.validated_data\n # 校验使用集群权限\n clb_utils.can_use_cluster(request, project_id, data['cluster_id'])\n\n with client.ContextActivityLogClient(\n project_id=project_id,\n user=request.user.username,\n resource_type='lb',\n resource=data['clb_name'],\n description=_(\"集群:{}, 更新clb:{}\").format(data['cluster_id'], data['clb_name']),\n ).log_delete():\n CloudLoadBlancer.objects.update(clb_id, data)\n data = CloudLoadBlancer.objects.retrieve_record(clb_id)\n\n return response.Response(data)\n\n\nclass CLBStatusViewSet(viewsets.ViewSet):\n renderer_classes = (BKAPIRenderer, BrowsableAPIRenderer)\n\n def compose_data(self, listeners):\n data = []\n for info in listeners:\n item = {'name': info['Name'], 'port': info['listenPort'], 'rules': info['healthStatus']['rules']}\n data.append(item)\n return data\n\n def retrieve_status(self, request, project_id, clb_id):\n record = CloudLoadBlancer.objects.retrieve_record(clb_id)\n status_detail = clb_utils.request_clb_status(request, project_id, record)\n remote_listeners = status_detail.get('remoteListeners') or []\n data = self.compose_data(remote_listeners)\n return response.Response(data)\n\n\nclass GetCLBRegionsViewSet(viewsets.ViewSet):\n renderer_classes = (BKAPIRenderer, BrowsableAPIRenderer)\n\n def list(self, request, project_id):\n data = clb_utils.get_clb_region_list(\n request.user.token.access_token,\n )\n return response.Response(data)\n", "sub_path": "bcs-app/backend/uniapps/network/clb/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 10336, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "rest_framework.viewsets.ViewSet", "line_number": 23, "usage_type": "attribute"}, {"api_name": "rest_framework.viewsets", "line_number": 23, "usage_type": "name"}, {"api_name": "backend.utils.renderers.BKAPIRenderer", "line_number": 24, "usage_type": "name"}, {"api_name": "rest_framework.renderers.BrowsableAPIRenderer", "line_number": 24, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.utils.describe_clb_detail", "line_number": 27, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.utils", "line_number": 27, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 33, "usage_type": "call"}, {"api_name": "rest_framework.response", "line_number": 33, "usage_type": "name"}, {"api_name": "rest_framework.viewsets.ViewSet", "line_number": 36, "usage_type": "attribute"}, {"api_name": "rest_framework.viewsets", "line_number": 36, "usage_type": "name"}, {"api_name": "backend.utils.renderers.BKAPIRenderer", "line_number": 37, "usage_type": "name"}, {"api_name": "rest_framework.renderers.BrowsableAPIRenderer", "line_number": 37, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.utils.get_deployments", "line_number": 45, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.utils", "line_number": 45, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.utils.get_cluster_id_names_map", "line_number": 50, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.utils", "line_number": 50, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer.objects.get_clb_list", "line_number": 60, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer.objects", "line_number": 60, "usage_type": "attribute"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer", "line_number": 60, "usage_type": "name"}, {"api_name": "backend.accounts.bcs_perm.Cluster.hook_perms", "line_number": 64, "usage_type": "call"}, {"api_name": "backend.accounts.bcs_perm.Cluster", "line_number": 64, "usage_type": "attribute"}, {"api_name": "backend.accounts.bcs_perm", "line_number": 64, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 66, "usage_type": "call"}, {"api_name": "rest_framework.response", "line_number": 66, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.utils.describe_clb_detail", "line_number": 69, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.utils", "line_number": 69, "usage_type": "name"}, {"api_name": "backend.utils.error_codes.error_codes.CheckFailed", "line_number": 73, "usage_type": "call"}, {"api_name": "backend.utils.error_codes.error_codes", "line_number": 73, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.serializers.CreateCLBSLZ", "line_number": 77, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.serializers", "line_number": 77, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.utils.can_use_cluster", "line_number": 81, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.utils", "line_number": 81, "usage_type": "name"}, {"api_name": "django.utils.crypto.get_random_string", "line_number": 87, "usage_type": "call"}, {"api_name": "backend.bcs_web.audit_log.client.ContextActivityLogClient", "line_number": 93, "usage_type": "call"}, {"api_name": "backend.bcs_web.audit_log.client", "line_number": 93, "usage_type": "name"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 98, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer.objects.create", "line_number": 100, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer.objects", "line_number": 100, "usage_type": "attribute"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer", "line_number": 100, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer.objects.parse_record", "line_number": 101, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer.objects", "line_number": 101, "usage_type": "attribute"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer", "line_number": 101, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 103, "usage_type": "call"}, {"api_name": "rest_framework.response", "line_number": 103, "usage_type": "name"}, {"api_name": "rest_framework.viewsets.ViewSet", "line_number": 106, "usage_type": "attribute"}, {"api_name": "rest_framework.viewsets", "line_number": 106, "usage_type": "name"}, {"api_name": "backend.utils.renderers.BKAPIRenderer", "line_number": 107, "usage_type": "name"}, {"api_name": "rest_framework.renderers.BrowsableAPIRenderer", "line_number": 107, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer.objects.filter", "line_number": 110, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer.objects", "line_number": 110, "usage_type": "attribute"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer", "line_number": 110, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer.objects.retrieve_record", "line_number": 114, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer.objects", "line_number": 114, "usage_type": "attribute"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer", "line_number": 114, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.utils.can_use_cluster", "line_number": 116, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.utils", "line_number": 116, "usage_type": "name"}, {"api_name": "backend.components.paas_cc.get_jfrog_domain", "line_number": 118, "usage_type": "call"}, {"api_name": "backend.components.paas_cc", "line_number": 118, "usage_type": "name"}, {"api_name": "django.conf.settings.DEFAUT_MESOS_LB_JFROG_DOMAIN", "line_number": 120, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 120, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 122, "usage_type": "call"}, {"api_name": "django.template.loader.render_to_string", "line_number": 122, "usage_type": "call"}, {"api_name": "backend.bcs_web.audit_log.client.ContextActivityLogClient", "line_number": 124, "usage_type": "call"}, {"api_name": "backend.bcs_web.audit_log.client", "line_number": 124, "usage_type": "name"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 129, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.utils.create_mesos_deployment", "line_number": 131, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.utils", "line_number": 131, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.constants.CLB_CREATED_STATUS", "line_number": 135, "usage_type": "attribute"}, {"api_name": "backend.uniapps.network.clb.constants", "line_number": 135, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 137, "usage_type": "call"}, {"api_name": "rest_framework.response", "line_number": 137, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer.objects.retrieve_record", "line_number": 140, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer.objects", "line_number": 140, "usage_type": "attribute"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer", "line_number": 140, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.utils.can_use_cluster", "line_number": 142, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.utils", "line_number": 142, "usage_type": "name"}, {"api_name": "backend.bcs_web.audit_log.client.ContextActivityLogClient", "line_number": 144, "usage_type": "call"}, {"api_name": "backend.bcs_web.audit_log.client", "line_number": 144, "usage_type": "name"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 149, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.utils.delete_mesos_deployment", "line_number": 151, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.utils", "line_number": 151, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.constants.CLB_DELETED_STATUS", "line_number": 159, "usage_type": "attribute"}, {"api_name": "backend.uniapps.network.clb.constants", "line_number": 159, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 161, "usage_type": "call"}, {"api_name": "rest_framework.response", "line_number": 161, "usage_type": "name"}, {"api_name": "rest_framework.viewsets.ViewSet", "line_number": 164, "usage_type": "attribute"}, {"api_name": "rest_framework.viewsets", "line_number": 164, "usage_type": "name"}, {"api_name": "backend.utils.renderers.BKAPIRenderer", "line_number": 165, "usage_type": "name"}, {"api_name": "rest_framework.renderers.BrowsableAPIRenderer", "line_number": 165, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.constants.CLB_CREATED_STATUS", "line_number": 168, "usage_type": "attribute"}, {"api_name": "backend.uniapps.network.clb.constants", "line_number": 168, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.utils.get_deployments", "line_number": 170, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.utils", "line_number": 170, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer.objects.retrieve_record", "line_number": 181, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer.objects", "line_number": 181, "usage_type": "attribute"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer", "line_number": 181, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.utils.get_cluster_name", "line_number": 184, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.utils", "line_number": 184, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 188, "usage_type": "call"}, {"api_name": "rest_framework.response", "line_number": 188, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer.objects.retrieve", "line_number": 192, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer.objects", "line_number": 192, "usage_type": "attribute"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer", "line_number": 192, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.constants.ALLOW_UPDATE_DELETE_STATUS_LIST", "line_number": 193, "usage_type": "attribute"}, {"api_name": "backend.uniapps.network.clb.constants", "line_number": 193, "usage_type": "name"}, {"api_name": "backend.utils.error_codes.error_codes.CheckFailed", "line_number": 194, "usage_type": "call"}, {"api_name": "backend.utils.error_codes.error_codes", "line_number": 194, "usage_type": "name"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 194, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.utils.can_use_cluster", "line_number": 196, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.utils", "line_number": 196, "usage_type": "name"}, {"api_name": "backend.bcs_web.audit_log.client.ContextActivityLogClient", "line_number": 198, "usage_type": "call"}, {"api_name": "backend.bcs_web.audit_log.client", "line_number": 198, "usage_type": "name"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 203, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 207, "usage_type": "call"}, {"api_name": "rest_framework.response", "line_number": 207, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.serializers.UpdateCLBSLZ", "line_number": 210, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.serializers", "line_number": 210, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.utils.can_use_cluster", "line_number": 214, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.utils", "line_number": 214, "usage_type": "name"}, {"api_name": "backend.bcs_web.audit_log.client.ContextActivityLogClient", "line_number": 216, "usage_type": "call"}, {"api_name": "backend.bcs_web.audit_log.client", "line_number": 216, "usage_type": "name"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 221, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer.objects.update", "line_number": 223, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer.objects", "line_number": 223, "usage_type": "attribute"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer", "line_number": 223, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer.objects.retrieve_record", "line_number": 224, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer.objects", "line_number": 224, "usage_type": "attribute"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer", "line_number": 224, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 226, "usage_type": "call"}, {"api_name": "rest_framework.response", "line_number": 226, "usage_type": "name"}, {"api_name": "rest_framework.viewsets.ViewSet", "line_number": 229, "usage_type": "attribute"}, {"api_name": "rest_framework.viewsets", "line_number": 229, "usage_type": "name"}, {"api_name": "backend.utils.renderers.BKAPIRenderer", "line_number": 230, "usage_type": "name"}, {"api_name": "rest_framework.renderers.BrowsableAPIRenderer", "line_number": 230, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer.objects.retrieve_record", "line_number": 240, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer.objects", "line_number": 240, "usage_type": "attribute"}, {"api_name": "backend.uniapps.network.clb.models.CloudLoadBlancer", "line_number": 240, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.utils.request_clb_status", "line_number": 241, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.utils", "line_number": 241, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 244, "usage_type": "call"}, {"api_name": "rest_framework.response", "line_number": 244, "usage_type": "name"}, {"api_name": "rest_framework.viewsets.ViewSet", "line_number": 247, "usage_type": "attribute"}, {"api_name": "rest_framework.viewsets", "line_number": 247, "usage_type": "name"}, {"api_name": "backend.utils.renderers.BKAPIRenderer", "line_number": 248, "usage_type": "name"}, {"api_name": "rest_framework.renderers.BrowsableAPIRenderer", "line_number": 248, "usage_type": "name"}, {"api_name": "backend.uniapps.network.clb.utils.get_clb_region_list", "line_number": 251, "usage_type": "call"}, {"api_name": "backend.uniapps.network.clb.utils", "line_number": 251, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 254, "usage_type": "call"}, {"api_name": "rest_framework.response", "line_number": 254, "usage_type": "name"}]}
+{"seq_id": "128024111", "text": "from odoo import api, fields, models, _\nimport xlwt, xlsxwriter\nimport base64\n\n\nclass EmployeeInfoExcelReport(models.TransientModel):\n _name = 'employee.salary.payslip.report'\n _description = 'Employee Information Excel Report'\n\n employee_id = fields.Many2one('hr.afg.payroll.batches', string='Batches', required=True)\n\n @api.multi\n def generated_excel_report(self, record):\n \n employee_obj = self.env['hr.afg.payroll.batches'].search([('name','=',self.employee_id.name)])\n \n workbook = xlwt.Workbook()\n\n # Style for Excel Report\n style0 = xlwt.easyxf('font:bold True; align: horiz left; pattern: pattern solid, fore_colour white', num_format_str='#,##0.00')\n style1 = xlwt.easyxf('font:bold True, color Yellow , height 400; borders:top double; align: horiz center; pattern: pattern solid, fore_colour blue;', num_format_str='#,##0.00')\n style2 = xlwt.easyxf('font:bold True, color White , height 440; borders:top double; align: horiz center; pattern: pattern solid, fore_colour gold;', num_format_str='#,##0.00')\n styletitle = xlwt.easyxf(\n 'font:bold True, color White, height 240; borders: top double; align: horiz center; pattern: pattern solid, fore_colour gold;',\n num_format_str='#,##0.00')\n sheet = workbook.add_sheet(\"Employee Payslip Report\")\n\n # sheet.write_merge(0, 0, 0, 10, 'GENERAL INFORMATION', style2)\n\n # sheet.write_merge(1, 1, 0, 5, 'Contact Information', style1)\n # sheet.write_merge(1, 1, 6, 10, 'Position', style1)\n\n sheet.write(0, 0, 'Employee Name', styletitle)\n sheet.write(0, 1, 'Mobile', styletitle)\n sheet.write(0, 2, 'Campus', styletitle)\n sheet.write(0, 3, 'Department', styletitle)\n sheet.write(0, 4, 'Designation', styletitle)\n sheet.write(0, 5, 'Base Salary', styletitle)\n sheet.write(0, 6, 'Loss Of Pay', styletitle)\n sheet.write(0, 7, 'Bonus', styletitle)\n sheet.write(0, 8, 'Net Pay', styletitle)\n sheet.write(0, 9, 'Tax', styletitle)\n sheet.write(0, 10, 'Advance Salary', styletitle)\n sheet.write(0, 11, 'Security Deposite', styletitle)\n sheet.write(0, 12, 'Other Deductions', styletitle)\n sheet.write(0, 13, 'Salary Payble', styletitle)\n\n sheet.col(0).width = 700 * (len('Employee Name') + 1)\n sheet.col(1).width = 700 * (len('Mobile') + 1)\n sheet.col(2).width = 700 * (len('Campus') + 1)\n sheet.col(3).width = 700 * (len('Department') + 1)\n sheet.col(4).width = 700 * (len('Designation') + 1)\n sheet.col(5).width = 700 * (len('Base Salary') + 1)\n sheet.col(6).width = 700 * (len('Loss Of Pay') + 1)\n sheet.col(7).width = 700 * (len('Bonus') + 1)\n sheet.col(8).width = 700 * (len('Net Pay') + 1)\n sheet.col(9).width = 700 * (len('Tax') + 1)\n sheet.col(10).width = 700 * (len('Advance Salary') + 1)\n sheet.col(11).width = 700 * (len('Security Deposite') + 1)\n sheet.col(12).width = 700 * (len('Other Deductions') + 1)\n sheet.col(13).width = 700 * (len('Salary Payble') + 1)\n \n sheet.row(0).height_mismatch = True\n sheet.row(0).height = 256 * 2\n # sheet.row(1).height = 256 * 2\n # sheet.row(2).height = 256 * 2\n\n row = 1\n width = 1\n\n for rec in employee_obj.slip_ids:\n sheet.row(width).height = 256 * 2\n \n sheet.write(row, 0, rec.employee_id.name)\n sheet.write(row, 1, rec.mobile)\n sheet.write(row, 2, rec.campus)\n sheet.write(row, 3, rec.department)\n sheet.write(row, 4, rec.designation)\n sheet.write(row, 5, rec.base_salary)\n sheet.write(row, 6, rec.lop)\n sheet.write(row, 7, rec.bonus)\n sheet.write(row, 8, rec.net_pay)\n sheet.write(row, 9, rec.tax)\n sheet.write(row, 10, rec.advance_salary)\n sheet.write(row, 11, rec.security_deposite)\n sheet.write(row, 12, rec.other_deductions)\n sheet.write(row, 13, rec.salary_payable)\n \n row +=1\n width += 1\n workbook.save('/tmp/employee_info_list.xls')\n result_file = open('/tmp/employee_info_list.xls', 'rb').read()\n # report_name = self.employee_id.name,'+',\n attachment_id = self.env['wizard.payslip.details.report'].create({\n 'name': self.employee_id.name +'.'+'xls',\n 'report': base64.encodestring(result_file)\n })\n\n return {\n 'name': _('Notification'),\n 'context': self.env.context,\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'wizard.payslip.details.report',\n 'res_id': attachment_id.id,\n 'data': None,\n 'type': 'ir.actions.act_window',\n 'target': 'new'\n }\n\n\nclass WizardEmployeeInformationExcelReport(models.TransientModel):\n _name = 'wizard.payslip.details.report'\n\n name = fields.Char('File Name', size=64)\n report = fields.Binary('Prepared File', filters='.xls', readonly=True)\n", "sub_path": "meli_mis/addons/afg_payroll/models/excel.py", "file_name": "excel.py", "file_ext": "py", "file_size_in_byte": 5149, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "odoo.models.TransientModel", "line_number": 6, "usage_type": "attribute"}, {"api_name": "odoo.models", "line_number": 6, "usage_type": "name"}, {"api_name": "odoo.fields.Many2one", "line_number": 10, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 10, "usage_type": "name"}, {"api_name": "xlwt.Workbook", "line_number": 17, "usage_type": "call"}, {"api_name": "xlwt.easyxf", "line_number": 20, "usage_type": "call"}, {"api_name": "xlwt.easyxf", "line_number": 21, "usage_type": "call"}, {"api_name": "xlwt.easyxf", "line_number": 22, "usage_type": "call"}, {"api_name": "xlwt.easyxf", "line_number": 23, "usage_type": "call"}, {"api_name": "base64.encodestring", "line_number": 96, "usage_type": "call"}, {"api_name": "odoo._", "line_number": 100, "usage_type": "call"}, {"api_name": "odoo.api.multi", "line_number": 12, "usage_type": "attribute"}, {"api_name": "odoo.api", "line_number": 12, "usage_type": "name"}, {"api_name": "odoo.models.TransientModel", "line_number": 112, "usage_type": "attribute"}, {"api_name": "odoo.models", "line_number": 112, "usage_type": "name"}, {"api_name": "odoo.fields.Char", "line_number": 115, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 115, "usage_type": "name"}, {"api_name": "odoo.fields.Binary", "line_number": 116, "usage_type": "call"}, {"api_name": "odoo.fields", "line_number": 116, "usage_type": "name"}]}
+{"seq_id": "80557602", "text": "# Copyright 2018 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Softfloor bijector.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow.compat.v2 as tf\n\nfrom tensorflow_probability.python import math as tfp_math\nfrom tensorflow_probability.python.bijectors import bijector\nfrom tensorflow_probability.python.internal import assert_util\nfrom tensorflow_probability.python.internal import distribution_util\n\n\n__all__ = [\n \"Softfloor\",\n]\n\n\nclass Softfloor(bijector.Bijector):\n \"\"\"Compute a differentiable approximation to `tf.math.floor`.\n\n Given `x`, compute a differentiable approximation to `tf.math.floor(x)`.\n It is parameterized by a temperature parameter `t` to control the closeness\n of the approximation at the cost of numerical stability of the inverse.\n\n This `Bijector` has the following properties:\n * This `Bijector` is a map between `R` to `R`.\n * For `t` close to `0`, this bijector mimics the identity function.\n * For `t` approaching `infinity`, this bijector converges pointwise\n to `tf.math.floor` (except at integer points).\n\n Note that for lower temperatures `t`, this bijector becomes more numerically\n unstable. In particular, the inverse for this bijector is not numerically\n stable at lower temperatures, because flooring is not a bijective function (\n and hence any pointwise limit towards the floor function will start to have a\n non-numerically stable inverse).\n\n #### Mathematical details\n\n Let `x` be in `[0.5, 1.5]`. We would like to simulate the floor function on\n this interval. We will do this via a shifted and rescaled `sigmoid`.\n\n `floor(x) = 0` for `x < 1` and `floor(x) = 1` for `x >= 1`.\n If we take `f(x) = sigmoid((x - 1.) / t)`, where `t > 0`, we can see that\n when `t` goes to zero, we get that when `x > 1`, the `f(x)` tends towards `1`\n while `f(x)` tends to `0` when `x < 1`, thus giving us a function that looks\n like the floor function. If we shift `f(x)` by `-sigmoid(-0.5 / t)` and\n rescale by `1 / (sigmoid(0.5 / t) - sigmoid(-0.5 / t))`, we preserve the\n pointwise limit, but also fix `f(0.5) = 0.` and `f(1.5) = 1.`.\n\n Thus we can define `softfloor(x, t) = a * sigmoid((x - 1.) / t) + b`\n\n where\n * `a = 1 / (sigmoid(0.5 / t) - sigmoid(-0.5 / t))`\n * `b = -sigmoid(-0.5 / t) / (sigmoid(0.5 / t) - sigmoid(-0.5 / t))`\n\n\n The implementation of the `Softfloor` bijector follows this, with the caveat\n that we extend the function to all of the real line, by appropriately shifting\n this function for each integer.\n\n #### Examples\n\n Example use:\n\n ```python\n # High temperature.\n soft_floor = Softfloor(temperature=100.)\n x = [2.1, 3.2, 5.5]\n soft_floor.forward(x)\n\n # Low temperature. This acts like a floor.\n soft_floor = Softfloor(temperature=0.01)\n soft_floor.forward(x) # Should be close to [2., 3., 5.]\n\n # Ceiling is just a shifted floor at non-integer points.\n soft_ceiling = tfb.Chain(\n [tfb.AffineScalar(1.),\n tfb.Softfloor(temperature=1.)])\n soft_ceiling.forward(x) # Should be close to [3., 5., 6.]\n ```\n \"\"\"\n\n def __init__(self,\n temperature,\n validate_args=False,\n name=\"softfloor\"):\n with tf.name_scope(name) as name:\n self._temperature = tf.convert_to_tensor(temperature, name=\"temperature\")\n if validate_args:\n self._temperature = distribution_util.with_dependencies([\n assert_util.assert_positive(\n self._temperature,\n message=\"Argument temperature was not positive\")\n ], self._temperature)\n super(Softfloor, self).__init__(\n forward_min_event_ndims=0,\n validate_args=validate_args,\n dtype=self._temperature.dtype,\n name=name)\n\n def _forward(self, x):\n # This has a well defined derivative with respect to x.\n # This is because in the range [a, a + 1.] this is just a rescaled\n # logit function and hence has a derivative. At the end points, because\n # the logit function satisfies 1 - sigma(-x) = sigma(x), we have that\n # the derivative is symmetric around the center of the interval (a + 0.5),\n # and hence is continuous at the endpoints.\n x = x - 0.5\n fractional_part = x - tf.math.floor(x)\n cyclic_part = tf.math.sigmoid((fractional_part - 0.5) / self.temperature)\n # Rescale so the left tail is 0., and the right tail is 1. This\n # will also guarantee us continuity. Differentiability comes from the\n # fact that the derivative of the sigmoid is symmetric, and hence\n # the two endpoints will have the same value for derivatives.\n rescaled_part = (\n cyclic_part / tf.math.tanh(1. / (self.temperature * 4)) -\n tf.math.exp(-0.5 / self.temperature) / (\n -tf.math.expm1(-0.5 / self.temperature)))\n return tf.math.floor(x) + rescaled_part\n\n # TODO(b/134588121): Improve the numerical stability of this function.\n def _inverse(self, y):\n fractional_part = y - tf.math.floor(y)\n # The naive thing to do is affine scale the fractional part, and apply\n # a logit function (to invert the _forward). However that has bad numerics\n # at lower temperatures, whereas this rewriting allows for lower\n # temperature scaling.\n new_fractional_part = (\n tf.math.log1p(fractional_part * -tf.math.expm1(\n -0.5 / self.temperature)) -\n tf.math.log(tf.math.exp(-0.5 / self.temperature) -\n fractional_part * tf.math.expm1(-0.5 / self.temperature)))\n new_fractional_part = self.temperature * new_fractional_part + 0.5\n return tf.math.floor(y) + new_fractional_part\n\n def _forward_log_det_jacobian(self, x):\n x = x - 0.5\n fractional_part = x - tf.math.floor(x)\n inner_part = (fractional_part - 0.5) / self.temperature\n\n offset = (tf.math.log(self.temperature) - tf.math.softplus(\n 0.5 / self.temperature) + tfp_math.softplus_inverse(\n 0.5 / self.temperature))\n\n return (-tf.math.softplus(-inner_part) -\n tf.math.softplus(inner_part) -\n offset)\n\n @property\n def temperature(self):\n return self._temperature\n", "sub_path": "tensorflow_probability/python/bijectors/softfloor.py", "file_name": "softfloor.py", "file_ext": "py", "file_size_in_byte": 6769, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "tensorflow_probability.python.bijectors.bijector.Bijector", "line_number": 34, "usage_type": "attribute"}, {"api_name": "tensorflow_probability.python.bijectors.bijector", "line_number": 34, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.name_scope", "line_number": 103, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 103, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.convert_to_tensor", "line_number": 104, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2", "line_number": 104, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.internal.distribution_util.with_dependencies", "line_number": 106, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.distribution_util", "line_number": 106, "usage_type": "name"}, {"api_name": "tensorflow_probability.python.internal.assert_util.assert_positive", "line_number": 107, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.internal.assert_util", "line_number": 107, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.math.floor", "line_number": 125, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.math", "line_number": 125, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 125, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.math.sigmoid", "line_number": 126, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.math", "line_number": 126, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 126, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.math.tanh", "line_number": 132, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.math", "line_number": 132, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 132, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.math.exp", "line_number": 133, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.math", "line_number": 133, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 133, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.math.expm1", "line_number": 134, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.math", "line_number": 134, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 134, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.math.floor", "line_number": 135, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.math", "line_number": 135, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 135, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.math.floor", "line_number": 139, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.math", "line_number": 139, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 139, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.math.log1p", "line_number": 145, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.math", "line_number": 145, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 145, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.math.expm1", "line_number": 145, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.math.log", "line_number": 147, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.math", "line_number": 147, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 147, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.math.exp", "line_number": 147, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.math.expm1", "line_number": 148, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.math", "line_number": 148, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 148, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.math.floor", "line_number": 150, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.math", "line_number": 150, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 150, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.math.floor", "line_number": 154, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.math", "line_number": 154, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 154, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.math.log", "line_number": 157, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.math", "line_number": 157, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 157, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.math.softplus", "line_number": 157, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.math.softplus_inverse", "line_number": 158, "usage_type": "call"}, {"api_name": "tensorflow_probability.python.math", "line_number": 158, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.math.softplus", "line_number": 161, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.math", "line_number": 161, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 161, "usage_type": "name"}, {"api_name": "tensorflow.compat.v2.math.softplus", "line_number": 162, "usage_type": "call"}, {"api_name": "tensorflow.compat.v2.math", "line_number": 162, "usage_type": "attribute"}, {"api_name": "tensorflow.compat.v2", "line_number": 162, "usage_type": "name"}]}
+{"seq_id": "546350413", "text": "\nfrom panda3d.core import Texture, NodePath, ShaderAttrib, Vec4, Vec3\nfrom panda3d.core import Shader\nfrom panda3d.core import Vec2, LMatrix4f, LVecBase3i, Camera, Mat4\nfrom panda3d.core import Mat4, OmniBoundingVolume, OrthographicLens\nfrom panda3d.core import PStatCollector, BoundingBox, Point3, CullFaceAttrib\nfrom panda3d.core import DepthTestAttrib, PTALVecBase3f\nfrom direct.stdpy.file import isfile, open, join\n\nfrom Globals import Globals\nfrom DebugObject import DebugObject\nfrom BetterShader import BetterShader\nfrom LightType import LightType\nfrom GUI.BufferViewerGUI import BufferViewerGUI\nfrom RenderTarget import RenderTarget\nfrom GIHelperLight import GIHelperLight\nfrom LightType import LightType\nfrom SettingsManager import SettingsManager\n\nimport time\nimport math\n\npstats_PopulateVoxelGrid = PStatCollector(\n \"App:GlobalIllumnination:PopulateVoxelGrid\")\npstats_GenerateVoxelOctree = PStatCollector(\n \"App:GlobalIllumnination:GenerateVoxelOctree\")\npstats_ClearGI = PStatCollector(\"App:GlobalIllumnination:Clear\")\npstats_GenerateMipmaps = PStatCollector(\"App:GlobalIllumnination::GenerateMipmaps\")\n\nclass GlobalIllumination(DebugObject):\n\n \"\"\" This class handles the global illumination processing. It is still\n experimental, and thus not commented. \"\"\"\n\n updateEnabled = False\n\n def __init__(self, pipeline):\n DebugObject.__init__(self, \"GlobalIllumnination\")\n self.pipeline = pipeline\n\n self.targetCamera = Globals.base.cam\n self.targetSpace = Globals.base.render\n\n self.voxelBaseResolution = 512 * 4\n self.voxelGridSizeWS = Vec3(50, 50, 20)\n self.voxelGridResolution = LVecBase3i(512, 512, 128)\n self.targetLight = None\n self.helperLight = None\n self.ptaGridPos = PTALVecBase3f.emptyArray(1)\n self.gridPos = Vec3(0)\n\n @classmethod\n def setUpdateEnabled(self, enabled):\n self.updateEnabled = enabled\n\n def setTargetLight(self, light):\n \"\"\" Sets the sun light which is the main source of GI \"\"\"\n\n if light._getLightType() != LightType.Directional:\n self.error(\"setTargetLight expects a directional light!\")\n return\n\n self.targetLight = light\n self._createHelperLight()\n\n def _prepareVoxelScene(self):\n \"\"\" Creates the internal buffer to voxelize the scene on the fly \"\"\"\n self.voxelizeScene = Globals.render\n self.voxelizeCamera = Camera(\"VoxelizeScene\")\n self.voxelizeCameraNode = self.voxelizeScene.attachNewNode(self.voxelizeCamera)\n self.voxelizeLens = OrthographicLens()\n self.voxelizeLens.setFilmSize(self.voxelGridSizeWS.x*2, self.voxelGridSizeWS.y*2)\n self.voxelizeLens.setNearFar(0.0, self.voxelGridSizeWS.x*2)\n self.voxelizeCamera.setLens(self.voxelizeLens)\n self.voxelizeCamera.setTagStateKey(\"VoxelizePassShader\")\n\n self.targetSpace.setTag(\"VoxelizePassShader\", \"Default\")\n\n self.voxelizeCameraNode.setPos(0,0,0)\n self.voxelizeCameraNode.lookAt(0,0,0)\n\n self.voxelizeTarget = RenderTarget(\"DynamicVoxelization\")\n self.voxelizeTarget.setSize(self.voxelBaseResolution) \n # self.voxelizeTarget.addDepthTexture()\n # self.voxelizeTarget.addColorTexture()\n # self.voxelizeTarget.setColorBits(16)\n self.voxelizeTarget.setSource(self.voxelizeCameraNode, Globals.base.win)\n self.voxelizeTarget.prepareSceneRender()\n\n self.voxelizeTarget.getQuad().node().removeAllChildren()\n self.voxelizeTarget.getInternalRegion().setSort(-400)\n self.voxelizeTarget.getInternalBuffer().setSort(-399)\n\n # for tex in [self.voxelizeTarget.getColorTexture()]:\n # tex.setWrapU(Texture.WMClamp)\n # tex.setWrapV(Texture.WMClamp)\n # tex.setMinfilter(Texture.FTNearest)\n # tex.setMagfilter(Texture.FTNearest)\n\n voxelSize = Vec3(\n self.voxelGridSizeWS.x * 2.0 / self.voxelGridResolution.x,\n self.voxelGridSizeWS.y * 2.0 / self.voxelGridResolution.y,\n self.voxelGridSizeWS.z * 2.0 / self.voxelGridResolution.z\n )\n\n self.targetSpace.setShaderInput(\"dv_gridSize\", self.voxelGridSizeWS * 2)\n self.targetSpace.setShaderInput(\"dv_voxelSize\", voxelSize)\n self.targetSpace.setShaderInput(\"dv_gridResolution\", self.voxelGridResolution)\n\n\n def _createVoxelizeState(self):\n \"\"\" Creates the tag state and loades the voxelizer shader \"\"\"\n self.voxelizeShader = Shader.load(Shader.SLGLSL, \n \"GI/Voxelize.vertex\",\n \"GI/Voxelize.fragment\"\n # \"GI/Voxelize.geometry\"\n )\n\n initialState = NodePath(\"VoxelizerState\")\n initialState.setShader(self.voxelizeShader, 50)\n initialState.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullNone))\n initialState.setDepthWrite(False)\n initialState.setDepthTest(False)\n initialState.setAttrib(DepthTestAttrib.make(DepthTestAttrib.MNone))\n\n initialState.setShaderInput(\"dv_dest_tex\", self.voxelGenTex)\n\n self.voxelizeCamera.setTagState(\n \"Default\", initialState.getState())\n\n def _createHelperLight(self):\n \"\"\" Creates the helper light. We can't use the main directional light\n because it uses PSSM, so we need an extra shadow map \"\"\"\n self.helperLight = GIHelperLight()\n self.helperLight.setPos(Vec3(50,50,100))\n self.helperLight.setShadowMapResolution(512)\n self.helperLight.setFilmSize(math.sqrt( (self.voxelGridSizeWS.x**2) * 2) * 2 )\n self.helperLight.setCastsShadows(True)\n self.pipeline.addLight(self.helperLight)\n\n self.targetSpace.setShaderInput(\"dv_uv_size\", \n float(self.helperLight.shadowResolution) / self.pipeline.settings.shadowAtlasSize)\n self.targetSpace.setShaderInput(\"dv_atlas\", \n self.pipeline.getLightManager().getAtlasTex())\n\n self._updateGridPos()\n\n def setup(self):\n \"\"\" Setups everything for the GI to work \"\"\"\n\n # if self.pipeline.settings.useHardwarePCF:\n # self.fatal(\n # \"Global Illumination does not work in combination with PCF!\")\n # return\n\n self._prepareVoxelScene()\n\n # Create 3D Texture to store the voxel generation grid\n self.voxelGenTex = Texture(\"VoxelsTemp\")\n self.voxelGenTex.setup3dTexture(self.voxelGridResolution.x, self.voxelGridResolution.y, self.voxelGridResolution.z,\n Texture.TInt, Texture.FR32i)\n self.voxelGenTex.setMinfilter(Texture.FTLinearMipmapLinear)\n self.voxelGenTex.setMagfilter(Texture.FTLinear)\n\n # Create 3D Texture which is a copy of the voxel generation grid but\n # stable, as the generation grid is updated part by part\n self.voxelStableTex = Texture(\"VoxelsStable\")\n self.voxelStableTex.setup3dTexture(self.voxelGridResolution.x, self.voxelGridResolution.y, self.voxelGridResolution.z,\n Texture.TFloat, Texture.FRgba8)\n self.voxelStableTex.setMinfilter(Texture.FTLinearMipmapLinear)\n self.voxelStableTex.setMagfilter(Texture.FTLinear) \n\n for prepare in [self.voxelGenTex, self.voxelStableTex]:\n prepare.setMagfilter(Texture.FTLinear)\n prepare.setMinfilter(Texture.FTLinearMipmapLinear)\n prepare.setWrapU(Texture.WMBorderColor)\n prepare.setWrapV(Texture.WMBorderColor)\n prepare.setWrapW(Texture.WMBorderColor)\n prepare.setBorderColor(Vec4(0,0,0,0))\n\n self.voxelGenTex.setMinfilter(Texture.FTNearest)\n self.voxelGenTex.setMagfilter(Texture.FTNearest)\n self.voxelGenTex.setWrapU(Texture.WMClamp)\n self.voxelGenTex.setWrapV(Texture.WMClamp)\n self.voxelGenTex.setWrapW(Texture.WMClamp)\n\n # self.voxelStableTex.generateRamMipmapImages() \n\n self._createVoxelizeState()\n\n self.clearTextureNode = NodePath(\"ClearTexture\")\n self.copyTextureNode = NodePath(\"CopyTexture\")\n self.generateMipmapsNode = NodePath(\"GenerateMipmaps\")\n self.convertGridNode = NodePath(\"ConvertGrid\")\n\n self.reloadShader()\n\n def _generateMipmaps(self, tex):\n \"\"\" Generates all mipmaps for a 3D texture, using a gaussian function \"\"\"\n\n pstats_GenerateMipmaps.start()\n currentMipmap = 0\n computeSize = LVecBase3i(self.voxelGridResolution)\n self.generateMipmapsNode.setShaderInput(\"source\", tex)\n self.generateMipmapsNode.setShaderInput(\n \"pixelSize\", 1.0 / computeSize.x)\n\n while computeSize.z > 1:\n computeSize /= 2\n self.generateMipmapsNode.setShaderInput(\n \"sourceMipmap\", LVecBase3i(currentMipmap))\n self.generateMipmapsNode.setShaderInput(\n \"currentMipmapSize\", LVecBase3i(computeSize))\n self.generateMipmapsNode.setShaderInput(\n \"dest\", tex, False, True, -1, currentMipmap + 1)\n self._executeShader(self.generateMipmapsNode,\n (computeSize.x + 7) / 8,\n (computeSize.y + 7) / 8,\n (computeSize.z + 7) / 8)\n currentMipmap += 1\n\n pstats_GenerateMipmaps.stop()\n\n def _createCleanShader(self):\n #shader = BetterShader.loadCompute(\"GI/ClearTexture.compute\")\n shader = Shader.loadCompute(Shader.SLGLSL, \"GI/ClearTexture.compute\")\n self.clearTextureNode.setShader(shader)\n\n def _createConvertShader(self):\n #shader = BetterShader.loadCompute(\"GI/ConvertGrid.compute\")\n shader = Shader.loadCompute(Shader.SLGLSL, \"GI/ConvertGrid.compute\")\n self.convertGridNode.setShader(shader)\n\n def _createGenerateMipmapsShader(self):\n #shader = BetterShader.loadCompute(\"GI/GenerateMipmaps.compute\")\n shader = Shader.loadCompute(Shader.SLGLSL, \"GI/GenerateMipmaps.compute\")\n self.generateMipmapsNode.setShader(shader)\n\n def reloadShader(self):\n self._createCleanShader()\n self._createGenerateMipmapsShader()\n self._createConvertShader()\n self._createVoxelizeState()\n self.frameIndex = 0\n\n def _clear3DTexture(self, tex, clearVal=None):\n \"\"\" Clears a 3D Texture to \"\"\"\n if clearVal is None:\n clearVal = Vec4(0)\n\n self.clearTextureNode.setShaderInput(\"target\", tex, False, True, -1, 0)\n self.clearTextureNode.setShaderInput(\n \"clearValue\", clearVal)\n\n self._executeShader(\n self.clearTextureNode,\n (tex.getXSize() + 7) / 8,\n (tex.getYSize() + 7) / 8,\n (tex.getZSize() + 7) / 8)\n\n def _updateGridPos(self):\n\n snap = 32.0\n stepSizeX = float(self.voxelGridSizeWS.x * 2.0) / float(self.voxelGridResolution.x) * snap\n stepSizeY = float(self.voxelGridSizeWS.y * 2.0) / float(self.voxelGridResolution.y) * snap\n stepSizeZ = float(self.voxelGridSizeWS.z * 2.0) / float(self.voxelGridResolution.z) * snap\n\n self.gridPos = self.targetCamera.getPos(self.targetSpace)\n self.gridPos.x -= self.gridPos.x % stepSizeX\n self.gridPos.y -= self.gridPos.y % stepSizeY\n self.gridPos.z -= self.gridPos.z % stepSizeZ\n\n def process(self):\n if self.targetLight is None:\n self.fatal(\"The GI cannot work without a target light! Set one \"\n \"with setTargetLight() first!\")\n\n if not self.updateEnabled:\n self.voxelizeTarget.setActive(False)\n return\n\n direction = self.targetLight.getDirection()\n\n # time.sleep(0.4)\n\n if self.frameIndex == 0:\n # Find out cam pos\n \n self.targetSpace.setShaderInput(\"dv_uv_start\", \n self.helperLight.shadowSources[0].getAtlasPos())\n\n self.voxelizeTarget.setActive(True)\n # self.voxelizeTarget.setActive(False)\n\n self.voxelizeLens.setFilmSize(self.voxelGridSizeWS.y*2, self.voxelGridSizeWS.z*2)\n self.voxelizeLens.setNearFar(0.0, self.voxelGridSizeWS.x*2)\n\n self.targetSpace.setShaderInput(\"dv_mvp\", Mat4(self.helperLight.shadowSources[0].mvp))\n self.targetSpace.setShaderInput(\"dv_gridStart\", self.gridPos - self.voxelGridSizeWS)\n self.targetSpace.setShaderInput(\"dv_gridEnd\", self.gridPos + self.voxelGridSizeWS)\n self.targetSpace.setShaderInput(\"dv_lightdir\", direction)\n\n # Clear textures\n self._clear3DTexture(self.voxelGenTex, Vec4(0,0,0,0))\n\n # Voxelize from x axis\n self.voxelizeCameraNode.setPos(self.gridPos - Vec3(self.voxelGridSizeWS.x, 0, 0))\n self.voxelizeCameraNode.lookAt(self.gridPos)\n self.targetSpace.setShaderInput(\"dv_direction\", LVecBase3i(0))\n\n\n elif self.frameIndex == 1:\n # Voxelize from y axis\n\n # self.voxelizeTarget.setActive(False)\n\n self.voxelizeLens.setFilmSize(self.voxelGridSizeWS.x*2, self.voxelGridSizeWS.z*2)\n self.voxelizeLens.setNearFar(0.0, self.voxelGridSizeWS.y*2)\n\n self.voxelizeCameraNode.setPos(self.gridPos - Vec3(0, self.voxelGridSizeWS.y, 0))\n self.voxelizeCameraNode.lookAt(self.gridPos)\n self.targetSpace.setShaderInput(\"dv_direction\", LVecBase3i(1))\n\n elif self.frameIndex == 2:\n\n # self.voxelizeTarget.setActive(False)\n # Voxelize from z axis\n self.voxelizeLens.setFilmSize(self.voxelGridSizeWS.x*2, self.voxelGridSizeWS.y*2)\n self.voxelizeLens.setNearFar(0.0, self.voxelGridSizeWS.z*2)\n\n self.voxelizeCameraNode.setPos(self.gridPos + Vec3(0, 0, self.voxelGridSizeWS.z))\n self.voxelizeCameraNode.lookAt(self.gridPos)\n self.targetSpace.setShaderInput(\"dv_direction\", LVecBase3i(2))\n\n elif self.frameIndex == 3:\n\n\n self.voxelizeTarget.setActive(False)\n\n # Copy the cache to the actual texture\n self.convertGridNode.setShaderInput(\"src\", self.voxelGenTex)\n self.convertGridNode.setShaderInput(\"dest\", self.voxelStableTex)\n self._executeShader(\n self.convertGridNode, (self.voxelGridResolution.x+7) / 8, (self.voxelGridResolution.y+7) / 8, (self.voxelGridResolution.z+7) / 8)\n\n # Generate the mipmaps\n self._generateMipmaps(self.voxelStableTex)\n\n self.helperLight.setPos(self.gridPos)\n self.helperLight.setDirection(direction)\n\n # We are done now, update the inputs\n self.ptaGridPos[0] = Vec3(self.gridPos)\n self._updateGridPos()\n \n\n self.frameIndex += 1\n self.frameIndex = self.frameIndex % 5\n\n\n def bindTo(self, node, prefix):\n \"\"\" Binds all required shader inputs to a target to compute / display\n the global illumination \"\"\"\n\n normFactor = Vec3(\n 1.0,\n float(self.voxelGridResolution.y) / float(self.voxelGridResolution.x) * self.voxelGridSizeWS.y / self.voxelGridSizeWS.x,\n float(self.voxelGridResolution.z) / float(self.voxelGridResolution.x) * self.voxelGridSizeWS.z / self.voxelGridSizeWS.x\n )\n node.setShaderInput(prefix + \".gridPos\", self.ptaGridPos)\n node.setShaderInput(prefix + \".gridHalfSize\", self.voxelGridSizeWS)\n node.setShaderInput(prefix + \".gridResolution\", self.voxelGridResolution)\n node.setShaderInput(prefix + \".voxels\", self.voxelStableTex)\n node.setShaderInput(prefix + \".voxelNormFactor\", normFactor)\n node.setShaderInput(prefix + \".geometry\", self.voxelStableTex)\n\n def _executeShader(self, node, threadsX, threadsY, threadsZ=1):\n \"\"\" Executes a compute shader, fetching the shader attribute from a NodePath \"\"\"\n sattr = node.getAttrib(ShaderAttrib)\n Globals.base.graphicsEngine.dispatchCompute(\n (threadsX, threadsY, threadsZ), sattr, Globals.base.win.get_gsg())\n", "sub_path": "Code/GlobalIllumination.py", "file_name": "GlobalIllumination.py", "file_ext": "py", "file_size_in_byte": 16078, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "panda3d.core.PStatCollector", "line_number": 23, "usage_type": "call"}, {"api_name": "panda3d.core.PStatCollector", "line_number": 25, "usage_type": "call"}, {"api_name": "panda3d.core.PStatCollector", "line_number": 27, "usage_type": "call"}, {"api_name": "panda3d.core.PStatCollector", "line_number": 28, "usage_type": "call"}, {"api_name": "DebugObject.DebugObject", "line_number": 30, "usage_type": "name"}, {"api_name": "DebugObject.DebugObject.__init__", "line_number": 38, "usage_type": "call"}, {"api_name": "DebugObject.DebugObject", "line_number": 38, "usage_type": "name"}, {"api_name": "Globals.Globals.base", "line_number": 41, "usage_type": "attribute"}, {"api_name": "Globals.Globals", "line_number": 41, "usage_type": "name"}, {"api_name": "Globals.Globals.base", "line_number": 42, "usage_type": "attribute"}, {"api_name": "Globals.Globals", "line_number": 42, "usage_type": "name"}, {"api_name": "panda3d.core.Vec3", "line_number": 45, "usage_type": "call"}, {"api_name": "panda3d.core.LVecBase3i", "line_number": 46, "usage_type": "call"}, {"api_name": "panda3d.core.PTALVecBase3f.emptyArray", "line_number": 49, "usage_type": "call"}, {"api_name": "panda3d.core.PTALVecBase3f", "line_number": 49, "usage_type": "name"}, {"api_name": "panda3d.core.Vec3", "line_number": 50, "usage_type": "call"}, {"api_name": "LightType.LightType.Directional", "line_number": 59, "usage_type": "attribute"}, {"api_name": "LightType.LightType", "line_number": 59, "usage_type": "name"}, {"api_name": "Globals.Globals.render", "line_number": 68, "usage_type": "attribute"}, {"api_name": "Globals.Globals", "line_number": 68, "usage_type": "name"}, {"api_name": "panda3d.core.Camera", "line_number": 69, "usage_type": "call"}, {"api_name": "panda3d.core.OrthographicLens", "line_number": 71, "usage_type": "call"}, {"api_name": "RenderTarget.RenderTarget", "line_number": 82, "usage_type": "call"}, {"api_name": "Globals.Globals.base", "line_number": 87, "usage_type": "attribute"}, {"api_name": "Globals.Globals", "line_number": 87, "usage_type": "name"}, {"api_name": "panda3d.core.Vec3", "line_number": 100, "usage_type": "call"}, {"api_name": "panda3d.core.Shader.load", "line_number": 113, "usage_type": "call"}, {"api_name": "panda3d.core.Shader", "line_number": 113, "usage_type": "name"}, {"api_name": "panda3d.core.Shader.SLGLSL", "line_number": 113, "usage_type": "attribute"}, {"api_name": "panda3d.core.NodePath", "line_number": 119, "usage_type": "call"}, {"api_name": "panda3d.core.CullFaceAttrib.make", "line_number": 121, "usage_type": "call"}, {"api_name": "panda3d.core.CullFaceAttrib", "line_number": 121, "usage_type": "name"}, {"api_name": "panda3d.core.CullFaceAttrib.MCullNone", "line_number": 121, "usage_type": "attribute"}, {"api_name": "panda3d.core.DepthTestAttrib.make", "line_number": 124, "usage_type": "call"}, {"api_name": "panda3d.core.DepthTestAttrib", "line_number": 124, "usage_type": "name"}, {"api_name": "panda3d.core.DepthTestAttrib.MNone", "line_number": 124, "usage_type": "attribute"}, {"api_name": "GIHelperLight.GIHelperLight", "line_number": 134, "usage_type": "call"}, {"api_name": "panda3d.core.Vec3", "line_number": 135, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 137, "usage_type": "call"}, {"api_name": "panda3d.core.Texture", "line_number": 159, "usage_type": "call"}, {"api_name": "panda3d.core.Texture.TInt", "line_number": 161, "usage_type": "attribute"}, {"api_name": "panda3d.core.Texture", "line_number": 161, "usage_type": "name"}, {"api_name": "panda3d.core.Texture.FR32i", "line_number": 161, "usage_type": "attribute"}, {"api_name": "panda3d.core.Texture.FTLinearMipmapLinear", "line_number": 162, "usage_type": "attribute"}, {"api_name": "panda3d.core.Texture", "line_number": 162, "usage_type": "name"}, {"api_name": "panda3d.core.Texture.FTLinear", "line_number": 163, "usage_type": "attribute"}, {"api_name": "panda3d.core.Texture", "line_number": 163, "usage_type": "name"}, {"api_name": "panda3d.core.Texture", "line_number": 167, "usage_type": "call"}, {"api_name": "panda3d.core.Texture.TFloat", "line_number": 169, "usage_type": "attribute"}, {"api_name": "panda3d.core.Texture", "line_number": 169, "usage_type": "name"}, {"api_name": "panda3d.core.Texture.FRgba8", "line_number": 169, "usage_type": "attribute"}, {"api_name": "panda3d.core.Texture.FTLinearMipmapLinear", "line_number": 170, "usage_type": "attribute"}, {"api_name": "panda3d.core.Texture", "line_number": 170, "usage_type": "name"}, {"api_name": "panda3d.core.Texture.FTLinear", "line_number": 171, "usage_type": "attribute"}, {"api_name": "panda3d.core.Texture", "line_number": 171, "usage_type": "name"}, {"api_name": "panda3d.core.Texture.FTLinear", "line_number": 174, "usage_type": "attribute"}, {"api_name": "panda3d.core.Texture", "line_number": 174, "usage_type": "name"}, {"api_name": "panda3d.core.Texture.FTLinearMipmapLinear", "line_number": 175, "usage_type": "attribute"}, {"api_name": "panda3d.core.Texture", "line_number": 175, "usage_type": "name"}, {"api_name": "panda3d.core.Texture.WMBorderColor", "line_number": 176, "usage_type": "attribute"}, {"api_name": "panda3d.core.Texture", "line_number": 176, "usage_type": "name"}, {"api_name": "panda3d.core.Texture.WMBorderColor", "line_number": 177, "usage_type": "attribute"}, {"api_name": "panda3d.core.Texture", "line_number": 177, "usage_type": "name"}, {"api_name": "panda3d.core.Texture.WMBorderColor", "line_number": 178, "usage_type": "attribute"}, {"api_name": "panda3d.core.Texture", "line_number": 178, "usage_type": "name"}, {"api_name": "panda3d.core.Vec4", "line_number": 179, "usage_type": "call"}, {"api_name": "panda3d.core.Texture.FTNearest", "line_number": 181, "usage_type": "attribute"}, {"api_name": "panda3d.core.Texture", "line_number": 181, "usage_type": "name"}, {"api_name": "panda3d.core.Texture.FTNearest", "line_number": 182, "usage_type": "attribute"}, {"api_name": "panda3d.core.Texture", "line_number": 182, "usage_type": "name"}, {"api_name": "panda3d.core.Texture.WMClamp", "line_number": 183, "usage_type": "attribute"}, {"api_name": "panda3d.core.Texture", "line_number": 183, "usage_type": "name"}, {"api_name": "panda3d.core.Texture.WMClamp", "line_number": 184, "usage_type": "attribute"}, {"api_name": "panda3d.core.Texture", "line_number": 184, "usage_type": "name"}, {"api_name": "panda3d.core.Texture.WMClamp", "line_number": 185, "usage_type": "attribute"}, {"api_name": "panda3d.core.Texture", "line_number": 185, "usage_type": "name"}, {"api_name": "panda3d.core.NodePath", "line_number": 191, "usage_type": "call"}, {"api_name": "panda3d.core.NodePath", "line_number": 192, "usage_type": "call"}, {"api_name": "panda3d.core.NodePath", "line_number": 193, "usage_type": "call"}, {"api_name": "panda3d.core.NodePath", "line_number": 194, "usage_type": "call"}, {"api_name": "panda3d.core.LVecBase3i", "line_number": 203, "usage_type": "call"}, {"api_name": "panda3d.core.LVecBase3i", "line_number": 211, "usage_type": "call"}, {"api_name": "panda3d.core.LVecBase3i", "line_number": 213, "usage_type": "call"}, {"api_name": "panda3d.core.Shader.loadCompute", "line_number": 226, "usage_type": "call"}, {"api_name": "panda3d.core.Shader", "line_number": 226, "usage_type": "name"}, {"api_name": "panda3d.core.Shader.SLGLSL", "line_number": 226, "usage_type": "attribute"}, {"api_name": "panda3d.core.Shader.loadCompute", "line_number": 231, "usage_type": "call"}, {"api_name": "panda3d.core.Shader", "line_number": 231, "usage_type": "name"}, {"api_name": "panda3d.core.Shader.SLGLSL", "line_number": 231, "usage_type": "attribute"}, {"api_name": "panda3d.core.Shader.loadCompute", "line_number": 236, "usage_type": "call"}, {"api_name": "panda3d.core.Shader", "line_number": 236, "usage_type": "name"}, {"api_name": "panda3d.core.Shader.SLGLSL", "line_number": 236, "usage_type": "attribute"}, {"api_name": "panda3d.core.Vec4", "line_number": 249, "usage_type": "call"}, {"api_name": "panda3d.core.Mat4", "line_number": 298, "usage_type": "call"}, {"api_name": "panda3d.core.Vec4", "line_number": 304, "usage_type": "call"}, {"api_name": "panda3d.core.Vec3", "line_number": 307, "usage_type": "call"}, {"api_name": "panda3d.core.LVecBase3i", "line_number": 309, "usage_type": "call"}, {"api_name": "panda3d.core.Vec3", "line_number": 320, "usage_type": "call"}, {"api_name": "panda3d.core.LVecBase3i", "line_number": 322, "usage_type": "call"}, {"api_name": "panda3d.core.Vec3", "line_number": 331, "usage_type": "call"}, {"api_name": "panda3d.core.LVecBase3i", "line_number": 333, "usage_type": "call"}, {"api_name": "panda3d.core.Vec3", "line_number": 353, "usage_type": "call"}, {"api_name": "panda3d.core.Vec3", "line_number": 365, "usage_type": "call"}, {"api_name": "panda3d.core.ShaderAttrib", "line_number": 379, "usage_type": "argument"}, {"api_name": "Globals.Globals.base.graphicsEngine.dispatchCompute", "line_number": 380, "usage_type": "call"}, {"api_name": "Globals.Globals.base", "line_number": 380, "usage_type": "attribute"}, {"api_name": "Globals.Globals", "line_number": 380, "usage_type": "name"}, {"api_name": "Globals.Globals.base.win.get_gsg", "line_number": 381, "usage_type": "call"}, {"api_name": "Globals.Globals.base", "line_number": 381, "usage_type": "attribute"}, {"api_name": "Globals.Globals", "line_number": 381, "usage_type": "name"}]}
+{"seq_id": "71667163", "text": "from jinja2 import StrictUndefined\n\nfrom flask import Flask, render_template, request, flash, redirect, session, jsonify, Response\nfrom flask_debugtoolbar import DebugToolbarExtension\nfrom model import Show, Show_Color, Brand, Color, connect_to_db, db\nfrom flask_sqlalchemy import SQLAlchemy\nimport flask_sqlalchemy\nimport flask_restless\nimport json\n\n\nfrom sqlalchemy import create_engine, Column, Integer, String, Date, Float\n\n\napp = Flask(__name__)\n# app.config['DEBUG'] = True\n# app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres:///showme'\ndb = flask_sqlalchemy.SQLAlchemy(app)\n\nmanager = flask_restless.APIManager(app, flask_sqlalchemy_db=db)\nshow_blueprint = manager.create_api(Show, methods=['GET'])\nbrand_blueprint = manager.create_api(Brand, methods=['GET'])\ncolor_blueprint = manager.create_api(Color, methods=['GET'])\nshow_color_blueprint = manager.create_api(Show_Color, methods=['GET'])\n\n# Required to use Flask sessions and the debug toolbar\napp.secret_key = \"ABC\"\n\n# Normally, if you use an undefined variable in Jinja2, it fails silently.\n# This is horrible. Fix this so that, instead, it raises an error.\napp.jinja_env.undefined = StrictUndefined\napp.jinja_env.auto_reload = True\n\n\n@app.route('/')\ndef index():\n \"\"\"Homepage.\"\"\"\n shows = Show.query.all()\n show_colors = Show_Color.query.all()\n colors = Color.query.all()\n brands = Brand.query.all()\n\n return render_template(\"bleep.html\",\n shows=shows,\n show_colors=show_colors,\n colors=colors,\n brands=brands)\n\n\n# @app.route('/api/all')\n# def api_all():\n# shows = Show.query.all()\n# show_colors = Show_Color.query.all()\n# colors = Color.query.all()\n# brands = Brand.query.all()\n\n# resp = Response(response=jsonify({'key': 'value'}),\n# status=200,\n# mimetype=\"application/json\")\n# return resp\n\n\n@app.route('/_get_brands')\ndef get_brands_json():\n brands = {}\n for brand in Brand.query.all():\n brands[brand.brand_id] = {\n 'brand_name': brand.brand_name,\n }\n\n return jsonify(brands)\n\n\n@app.route('/_get_shows')\ndef get_shows_json():\n shows = {}\n for show in Show.query.all():\n shows[show.show_id] = {\n 'show_id': show.show_id,\n 'show_season': show.season,\n 'show_year': show.year,\n 'brand_name': show.brands.brand_name,\n }\n\n return jsonify(shows)\n\n\n@app.route('/_get_colors')\ndef get_colors_json():\n colors = {}\n for color in Color.query.all():\n colors[color.color_id] = {\n 'color_id': color.color_id,\n 'color': color.color_name,\n 'color_hex': color.color_hex,\n }\n\n return jsonify(colors)\n\n\n@app.route('/_get_show_colors')\ndef get_show_colors_json():\n show_colors_json = {}\n for show_color in Show_Color.query.all():\n show_colors_json[show_color.show_colors_id] = {\n 'show_color': show_color.colors.color_id,\n 'brand_name': show_color.shows.brands.brand_name,\n 'color_id': show_color.color_id,\n 'color_name': show_color.colors.color_name,\n }\n\n return jsonify(show_colors_json)\n\n# ')\n# def api_by_season(color_hex):\n# events = Events.query.filter_by(event_type=event_type).all()\n# return jsonify(json_list=[event.serialize for event in events])\n\n\n# @app.route('/', methods=['GET'])\n# def register_form():\n# \"\"\"Show form for user signup.\"\"\"\n\n# return render_template(\"base.html\")\n\n\n# @app.route('/register', methods=['POST'])\n# def register_process():\n# \"\"\"Process registration.\"\"\"\n\n# # Get form variables\n# email = request.form[\"email\"]\n# password = request.form[\"password\"]\n# age = int(request.form[\"age\"])\n# zipcode = request.form[\"zipcode\"]\n\n# new_user = User(email=email, password=password, age=age, zipcode=zipcode)\n\n# db.session.add(new_user)\n# db.session.commit()\n\n# flash(\"User %s added.\" % email)\n# return redirect(\"/\")\n\n\n# @app.route('/login', methods=['GET'])\n# def login_form():\n# \"\"\"Show login form.\"\"\"\n\n# return render_template(\"login_form.html\")\n\n\n# @app.route('/login', methods=['POST'])\n# def login_process():\n# \"\"\"Process login.\"\"\"\n\n# # Get form variables\n# email = request.form[\"email\"]\n# password = request.form[\"password\"]\n\n# user = User.query.filter_by(email=email).first()\n\n# if not user:\n# flash(\"No such user\")\n# return redirect(\"/login\")\n\n# if user.password != password:\n# flash(\"Incorrect password\")\n# return redirect(\"/login\")\n\n# session[\"user_id\"] = user.user_id\n\n# flash(\"Logged in\")\n# return redirect(\"/users/%s\" % user.user_id)\n\n\n# @app.route('/logout')\n# def logout():\n# \"\"\"Log out.\"\"\"\n\n# del session[\"user_id\"]\n# flash(\"Logged Out.\")\n# return redirect(\"/\")\n\n\n# @app.route(\"/users\")\n# def user_list():\n# \"\"\"Show list of users.\"\"\"\n\n# users = User.query.all()\n# return render_template(\"user_list.html\", users=users)\n\n\n# @app.route(\"/users/\")\n# def user_detail(user_id):\n# \"\"\"Show info about user.\"\"\"\n\n# user = User.query.get(user_id)\n# return render_template(\"user.html\", user=user)\n\n\n# @app.route(\"/movies\")\n# def movie_list():\n# \"\"\"Show list of movies.\"\"\"\n\n# movies = Movie.query.order_by('title').all()\n# return render_template(\"movie_list.html\", movies=movies)\n\n\n# @app.route(\"/movies/\", methods=['GET'])\n# def movie_detail(movie_id):\n# \"\"\"Show info about movie.\n\n# If a user is logged in, let them add/edit a rating.\n# \"\"\"\n\n# movie = Movie.query.get(movie_id)\n\n# user_id = session.get(\"user_id\")\n\n# if user_id:\n# user_rating = Rating.query.filter_by(\n# movie_id=movie_id, user_id=user_id).first()\n\n# else:\n# user_rating = None\n\n# # Get average rating of movie\n\n# rating_scores = [r.score for r in movie.ratings]\n# avg_rating = float(sum(rating_scores)) / len(rating_scores)\n\n# prediction = None\n\n# # Prediction code: only predict if the user hasn't rated it.\n\n# if (not user_rating) and user_id:\n# user = User.query.get(user_id)\n# if user:\n# prediction = user.predict_rating(movie)\n\n# # Either use the prediction or their real rating\n\n# if prediction:\n# # User hasn't scored; use our prediction if we made one\n# effective_rating = prediction\n\n# elif user_rating:\n# # User has already scored for real; use that\n# effective_rating = user_rating.score\n\n# else:\n# # User hasn't scored, and we couldn't get a prediction\n# effective_rating = None\n\n# # Get the eye's rating, either by predicting or using real rating\n\n# the_eye = (User.query.filter_by(email=\"the-eye@of-judgment.com\")\n# .one())\n# eye_rating = Rating.query.filter_by(\n# user_id=the_eye.user_id, movie_id=movie.movie_id).first()\n\n# if eye_rating is None:\n# eye_rating = the_eye.predict_rating(movie)\n\n# else:\n# eye_rating = eye_rating.score\n\n# if eye_rating and effective_rating:\n# difference = abs(eye_rating - effective_rating)\n\n# else:\n# # We couldn't get an eye rating, so we'll skip difference\n# difference = None\n\n # Depending on how different we are from the Eye, choose a\n # message\n\n# BERATEMENT_MESSAGES = [\n# \"I suppose you don't have such bad taste after all.\",\n# \"I regret every decision that I've ever made that has \" +\n# \"brought me to listen to your opinion.\",\n# \"Words fail me, as your taste in movies has clearly \" +\n# \"failed you.\",\n# \"That movie is great. For a clown to watch. Idiot.\",\n# \"Words cannot express the awfulness of your taste.\"\n# ]\n\n# if difference is not None:\n# beratement = BERATEMENT_MESSAGES[int(difference)]\n\n# else:\n# beratement = None\n\n# return render_template(\n# \"movie.html\",\n# movie=movie,\n# user_rating=user_rating,\n# average=avg_rating,\n# prediction=prediction,\n# eye_rating=eye_rating,\n# difference=difference,\n# beratement=beratement\n# )\n\n\n# @app.route(\"/movies/\", methods=['POST'])\n# def movie_detail_process(movie_id):\n# \"\"\"Add/edit a rating.\"\"\"\n\n# # Get form variables\n# score = int(request.form[\"score\"])\n\n# user_id = session.get(\"user_id\")\n# if not user_id:\n# raise Exception(\"No user logged in.\")\n\n# rating = Rating.query.filter_by(user_id=user_id, movie_id=movie_id).first()\n\n# if rating:\n# rating.score = score\n# flash(\"Rating updated.\")\n\n# else:\n# rating = Rating(user_id=user_id, movie_id=movie_id, score=score)\n# flash(\"Rating added.\")\n# db.session.add(rating)\n\n# db.session.commit()\n\n# return redirect(\"/movies/%s\" % movie_id)\n\n\nif __name__ == \"__main__\":\n # We have to set debug=True here, since it has to be True at the point\n # that we invoke the DebugToolbarExtension\n app.debug = True\n\n connect_to_db(app)\n\n # Use the DebugToolbar\n DebugToolbarExtension(app)\n\n app.run(host=\"0.0.0.0\")\n", "sub_path": "server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 12346, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "flask.Flask", "line_number": 15, "usage_type": "call"}, {"api_name": "model.db", "line_number": 18, "usage_type": "name"}, {"api_name": "flask_sqlalchemy.SQLAlchemy", "line_number": 18, "usage_type": "call"}, {"api_name": "flask_restless.APIManager", "line_number": 20, "usage_type": "call"}, {"api_name": "model.db", "line_number": 20, "usage_type": "name"}, {"api_name": "model.Show", "line_number": 21, "usage_type": "argument"}, {"api_name": "model.Brand", "line_number": 22, "usage_type": "argument"}, {"api_name": "model.Color", "line_number": 23, "usage_type": "argument"}, {"api_name": "model.Show_Color", "line_number": 24, "usage_type": "argument"}, {"api_name": "jinja2.StrictUndefined", "line_number": 31, "usage_type": "name"}, {"api_name": "model.Show.query.all", "line_number": 38, "usage_type": "call"}, {"api_name": "model.Show.query", "line_number": 38, "usage_type": "attribute"}, {"api_name": "model.Show", "line_number": 38, "usage_type": "name"}, {"api_name": "model.Show_Color.query.all", "line_number": 39, "usage_type": "call"}, {"api_name": "model.Show_Color.query", "line_number": 39, "usage_type": "attribute"}, {"api_name": "model.Show_Color", "line_number": 39, "usage_type": "name"}, {"api_name": "model.Color.query.all", "line_number": 40, "usage_type": "call"}, {"api_name": "model.Color.query", "line_number": 40, "usage_type": "attribute"}, {"api_name": "model.Color", "line_number": 40, "usage_type": "name"}, {"api_name": "model.Brand.query.all", "line_number": 41, "usage_type": "call"}, {"api_name": "model.Brand.query", "line_number": 41, "usage_type": "attribute"}, {"api_name": "model.Brand", "line_number": 41, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 43, "usage_type": "call"}, {"api_name": "model.Brand.query.all", "line_number": 66, "usage_type": "call"}, {"api_name": "model.Brand.query", "line_number": 66, "usage_type": "attribute"}, {"api_name": "model.Brand", "line_number": 66, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 71, "usage_type": "call"}, {"api_name": "model.Show.query.all", "line_number": 77, "usage_type": "call"}, {"api_name": "model.Show.query", "line_number": 77, "usage_type": "attribute"}, {"api_name": "model.Show", "line_number": 77, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 85, "usage_type": "call"}, {"api_name": "model.Color.query.all", "line_number": 91, "usage_type": "call"}, {"api_name": "model.Color.query", "line_number": 91, "usage_type": "attribute"}, {"api_name": "model.Color", "line_number": 91, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 98, "usage_type": "call"}, {"api_name": "model.Show_Color.query.all", "line_number": 104, "usage_type": "call"}, {"api_name": "model.Show_Color.query", "line_number": 104, "usage_type": "attribute"}, {"api_name": "model.Show_Color", "line_number": 104, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 112, "usage_type": "call"}, {"api_name": "model.Brand.query.all", "line_number": 119, "usage_type": "call"}, {"api_name": "model.Brand.query", "line_number": 119, "usage_type": "attribute"}, {"api_name": "model.Brand", "line_number": 119, "usage_type": "name"}, {"api_name": "model.Show.query.filter_by", "line_number": 122, "usage_type": "call"}, {"api_name": "model.Show.query", "line_number": 122, "usage_type": "attribute"}, {"api_name": "model.Show", "line_number": 122, "usage_type": "name"}, {"api_name": "model.Show_Color.query.filter_by", "line_number": 126, "usage_type": "call"}, {"api_name": "model.Show_Color.query", "line_number": 126, "usage_type": "attribute"}, {"api_name": "model.Show_Color", "line_number": 126, "usage_type": "name"}, {"api_name": "model.Color.query.filter_by", "line_number": 130, "usage_type": "call"}, {"api_name": "model.Color.query", "line_number": 130, "usage_type": "attribute"}, {"api_name": "model.Color", "line_number": 130, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 138, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 143, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 143, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 143, "usage_type": "name"}, {"api_name": "model.Show.query.filter_by", "line_number": 148, "usage_type": "call"}, {"api_name": "model.Show.query", "line_number": 148, "usage_type": "attribute"}, {"api_name": "model.Show", "line_number": 148, "usage_type": "name"}, {"api_name": "model.Show_Color.query.filter_by", "line_number": 151, "usage_type": "call"}, {"api_name": "model.Show_Color.query", "line_number": 151, "usage_type": "attribute"}, {"api_name": "model.Show_Color", "line_number": 151, "usage_type": "name"}, {"api_name": "model.Color.query.filter_by", "line_number": 153, "usage_type": "call"}, {"api_name": "model.Color.query", "line_number": 153, "usage_type": "attribute"}, {"api_name": "model.Color", "line_number": 153, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 181, "usage_type": "call"}, {"api_name": "model.connect_to_db", "line_number": 441, "usage_type": "call"}, {"api_name": "flask_debugtoolbar.DebugToolbarExtension", "line_number": 444, "usage_type": "call"}]}
+{"seq_id": "429650232", "text": "import requests\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom datetime import datetime, timedelta\nimport time\nimport os\nimport queue\nimport threading\nfrom . import var\n\n\ndef floorsheets():\n \"\"\"\n Threaded Scraper For FloorSheets as we need to scrape more than 75k Data\n Returns in less than 2 seconds.\n \"\"\"\n q = queue.Queue()\n contents = []\n response = requests.get(\n 'https://newweb.nepalstock.com.np/api/' +\n 'nots/nepse-data/floorsheet?size=2000&sort=contractId,desc',\n headers=var.header)\n pages = response.json()['floorsheets']['totalPages']\n\n def scrapePage(pageNUM):\n response = requests.get(\n 'https://newweb.nepalstock.com.np/api/' +\n f'nots/nepse-data/floorsheet?page={pageNUM}&size=2000&sort=contractId,desc',\n headers=var.header)\n return response.json()['floorsheets']['content']\n\n def queGET(q):\n while True:\n task = q.get()\n contents.extend(scrapePage(task))\n q.task_done()\n\n for i in range(30):\n worker = threading.Thread(target=queGET, args=(q, ), daemon=True)\n worker.start()\n\n for j in range(pages):\n q.put(j)\n\n q.join()\n\n return pd.DataFrame(contents)\n\n\nclass Floorsheet:\n def __init__(self):\n self.fs = floorsheets()\n\n def update(self):\n self.fs = floorsheets()\n\n def volume(self, scrip):\n return self.fs[self.fs.stockSymbol == scrip].contractQuantity.sum()\n\n def matching_amt(self):\n return len(self.fs[self.fs.buyerMemberId == self.fs.sellerMemberId].\n index) / len(self.fs.index) * 100\n\n def buy_to_sell(self, bid, scrip=None):\n if not scrip:\n return self.fs[self.fs.buyerMemberId == bid].contractQuantity.sum(\n ) / self.fs[self.fs.sellerMemberId == bid].contractQuantity.sum()\n else:\n return self.fs[self.fs.buyerMemberId == bid][\n self.fs.stockSymbol == scrip].contractQuantity.sum() / self.fs[\n self.fs.sellerMemberId == bid][\n self.fs.stockSymbol == scrip].contractQuantity.sum()\n\n\nclass NEPSE:\n def __init__(self):\n self.headers = var.header\n self.sectors = var.sectors\n self.host = 'https://newweb.nepalstock.com.np/api/'\n # self.securities = requests.get(self.host +\n # 'nots/securityDailyTradeStat/58',\n # headers=self.headers).json()\n pass\n\n def dateFilter(self, working_date, data):\n \"\"\"\n Function to return next working day , if the date provided is non-working day.\n\n Returns either first or last date if the date provided is too ahead or too back.\n\n \"\"\"\n\n all_dates = [date['businessDate'] for date in data]\n if working_date in all_dates:\n return working_date\n else:\n i = 0\n while 1:\n\n date = datetime.strptime(working_date, '%Y-%m-%d')\n new_date = str(date + timedelta(days=i)).split(' ')[0]\n if new_date in all_dates:\n return new_date\n i += 1\n if i >= 7:\n month = working_date.split('-')[1]\n year = working_date.split('-')[0]\n day = working_date.split('-')[-1]\n if year > all_dates[-1].split(\n '-')[0] and month > all_dates[-1].split('-')[1]:\n return all_dates[-1]\n return all_dates[0]\n\n def isOpen(self):\n \"\"\"\n Returns True if the market is Open .\n\n \"\"\"\n response = requests.get(self.host + '/nots/nepse-data/market-open',\n headers=self.headers).json()\n if response['isOpen'] != 'CLOSE':\n return True\n return False\n\n def nonthreadedfloorsheets(self):\n content = []\n page = 0\n while 1:\n response = requests.get(\n 'https://newweb.nepalstock.com.np/api/nots/nepse-data/floorsheet?page={page}&size=2000&sort=contractId,desc',\n headers=self.headers)\n data = (response.json())['floorsheets']['content']\n isLast = response.json()['floorsheets']['last']\n content.extend(data)\n page += 1\n if isLast:\n return content\n\n def indices(self, sector='NEPSE Index', start_date=None, end_date=None):\n index = sector\n index_id = [\n id['id'] for id in self.sectors if id['indexName'] == index\n ][0]\n resp = requests.get(self.host + 'nots/graph/index/58',\n headers=self.headers).json()\n # if start_date:\n # start_date = self.dateFilter(start_date, resp)\n # start_index = next((index for (index, d) in enumerate(resp)\n # if d[\"businessDate\"] == start_date), None)\n # resp = resp[start_index:]\n # if end_date:\n\n # end_date = self.dateFilter(end_date, resp)\n # end_index = next((index for (index, d) in enumerate(resp)\n # if d[\"businessDate\"] == end_date), None) + 1\n # if start_date and end_date:\n # if end_index == start_index:\n # end_index = -1\n # resp = resp[:end_index]\n return resp\n\n def brokers(self):\n \"\"\" \n Returns all the registered brokers along with tms url and other information\n\n \"\"\"\n resp = requests.get(self.host + 'nots/member?&size=500',\n headers=self.headers).json()\n return resp\n\n def alerts(self):\n \"\"\"\n\n returns alerts and news published by \n\n \"\"\"\n resp = requests.get(self.host + 'nots/news/media/news-and-alerts',\n headers=self.headers).json()\n return resp\n\n def todayPrice(self, scrip=None):\n \"\"\"\n\n Get Live Price of All The Securities in one call or specify\n\n \"\"\"\n resp = requests.get(self.host +\n 'nots/nepse-data/today-price?&size=500',\n headers=self.headers).json()['content']\n if scrip == None:\n return resp\n return [\n script for script in resp if script['symbol'] == scrip.upper()\n ][0]\n\n def markCap(self):\n \"\"\"\n\n Get Market Caps\n\n \"\"\"\n resp = requests.get(self.host + 'nots/nepse-data/marcapbydate/?',\n headers=self.headers).json()\n return resp\n\n def getChartHistory(self, scrip, start_date=None, end_date=None):\n \"\"\"\n\n returns charts data \n raises Exception if start_date or end_date != working_days (will fix it)\n\n \"\"\"\n\n scripID = [\n security for security in self.securities\n if security['symbol'] == scrip.upper()\n ][0]['securityId']\n resp = requests.get(self.host + f'nots/market/graphdata/{scripID}',\n headers=self.headers).json()\n if start_date:\n start_date = self.dateFilter(start_date, resp)\n start_index = next((index for (index, d) in enumerate(resp)\n if d[\"businessDate\"] == start_date), None)\n resp = resp[start_index:]\n if end_date:\n\n end_date = self.dateFilter(end_date, resp)\n end_index = next((index for (index, d) in enumerate(resp)\n if d[\"businessDate\"] == end_date), None) + 1\n if start_date and end_date:\n if end_index == start_index:\n end_index = -1\n resp = resp[:end_index]\n return resp\n\n def createChart(self,\n scrip,\n theme='dark',\n start_date=None,\n end_date=None,\n close=True,\n high=True,\n low=True):\n\n symbol = scrip.upper()\n if theme.upper() == 'DARK':\n plt.style.use(['dark_background'])\n\n data = self.getChartHistory(symbol, start_date, end_date)\n open_price = [d['openPrice'] for d in data]\n x = [d['businessDate'] for d in data]\n high_data = [d['highPrice'] for d in data]\n low_data = [d['lowPrice'] for d in data]\n close_price = [d['closePrice'] for d in data]\n\n plt.plot(open_price, label='Open Price')\n if close:\n plt.plot(close_price, label=\"Close Price\")\n if high:\n plt.plot(high_data, label=\"High\")\n if low:\n plt.plot(low_data, label=\"Low\")\n\n plt.legend(loc=\"upper left\")\n\n plt.title(f'{symbol} Prices As of {x[-1]}')\n\n plt.xlabel(\n f\"Start Date : {x[0]} | END DATE : {x[-1]}\\n\\nOPEN PRICE : {open_price[-1]} | ClOSE PRICE : {close_price[-1]} | High : {high_data[-1]} | Low : {low_data[-1]}\"\n )\n ax = plt.gcf().autofmt_xdate()\n ax = plt.gca()\n ax.axes.xaxis.set_ticks([])\n filename = f'{symbol}_{str(time.time())}.png'\n data = plt.savefig(filename)\n abspath = os.path.abspath(filename)\n plt.clf()\n return {'file': abspath}\n\n def saveCSV(self, scrip, start_date=None, end_date=None, filename=None):\n scripID = [\n security for security in self.securities\n if security['symbol'] == scrip.upper()\n ][0]['securityId']\n resp = self.getChartHistory(scrip, start_date, end_date)\n if not filename:\n filename = f'{scrip.upper()}_{str(time.time())}.csv'\n pd.DataFrame(resp).to_csv(filename)\n return os.path.abspath(filename)\n\n def watch(self, watchlist):\n watchlist = [scrip.upper() for scrip in watchlist]\n priceList = self.todayPrice()\n data = [scrip for scrip in priceList if scrip[\"symbol\"] in watchlist]\n\n text = \" SCRIP PCT-CH PrevCLOSE LTP\" + \"\\n\" + \"=\" * 40 + \"\\n\"\n for datum in data:\n scrip = datum[\"symbol\"]\n closing = int(datum[\"previousDayClosePrice\"])\n ltp = int(datum[\"lastUpdatedPrice\"])\n pctchange = (ltp - closing) * 100 / closing\n text = text + (scrip.upper().center(8) +\n \"%.2f\".center(9) % pctchange +\n str(closing).center(12) + str(ltp).center(8)) + \"\\n\"\n return (text)\n\n\ndef checkIPO(scripID, boid):\n \"\"\"\n CHECK IPO RESULT\n\n \"\"\"\n\n # published = requests.get('https://iporesult.cdsc.com.np/result/companyShares/fileUploaded').json()['body']\n # print()\n\n # scripID = [\n # resp['id'] for resp in if resp['scrip'] == scrip.upper()\n # ][0]\n\n return requests.post('https://iporesult.cdsc.com.np/result/result/check',\n json={\n \"companyShareId\": scripID,\n \"boid\": boid\n }).json()[\"success\"]\n\n\nif __name__ == '__main__':\n data = NEPSE()\n print(data.indices())\n", "sub_path": "nepse/stonk.py", "file_name": "stonk.py", "file_ext": "py", "file_size_in_byte": 11190, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "queue.Queue", "line_number": 17, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 19, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 26, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 39, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 47, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 100, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 100, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 101, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 119, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 129, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 144, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 167, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 177, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 187, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 202, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 218, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.style.use", "line_number": 247, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.style", "line_number": 247, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 247, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 256, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 256, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 258, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 258, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 260, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 260, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 262, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 262, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 264, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 264, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 266, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 266, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 268, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 268, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gcf", "line_number": 271, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 271, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 272, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 272, "usage_type": "name"}, {"api_name": "time.time", "line_number": 274, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 275, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 275, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 276, "usage_type": "call"}, {"api_name": "os.path", "line_number": 276, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 277, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 277, "usage_type": "name"}, {"api_name": "time.time", "line_number": 287, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 288, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 289, "usage_type": "call"}, {"api_name": "os.path", "line_number": 289, "usage_type": "attribute"}, {"api_name": "requests.post", "line_number": 321, "usage_type": "call"}]}
+{"seq_id": "478502931", "text": "\"\"\"\nCS/BIOS 112 - Program Design I\n\nFor this project, I will work with a portion of this gene, known as ALX1, from four species, 5-10 individuals each, of Darwin’s finches + 1 outgroup, L. noctis (the Lesser Antillean Bullfinch).\n Synthesizing Python knowledge: loops, conditions, strings, lists, functions, random functions, modules, plotting.\n DNA vs phenotype.\n\nFile: project_02.py\n\n@author: \nDue Date: <11/02/2020>\n\"\"\"\n\n# species named in the data file finches_2020.csv \nfinch1 = 'G.conirostris_Espanola'\nfinch2 = 'G.conirostris_Genovesa'\nfinch3 = 'G.difficilis'\nfinch4 = 'G.magnirostris'\noutgroup = 'L.noctis'\n\ndef read_input(fileName):\n ''' This function is to read the CSV file, assuming the column input format is [species, Individual ID, allele (A or B), gene sequence, beak shape score (i.e., the degree of pointedness), beak type] and creating a list variable for each individual of length 7 with the format [species, Individual ID, alleleA gene, alleleB gene, alleleA beak shape score, alleleB beak shape score, beak type]. '''\n \n import csv\n \n fileref = open(fileName, \"r\")\n data_reader = csv.reader(fileref)\n row = []\n \n for i in data_reader:\n if(i[2] == 'A'):\n x = i\n del x[2]\n else:\n x.insert(3, i[3])\n x.insert(4, i[5])\n row.append(x)\n \n fileref.close()\n \n return row\n \ndef allele_dist(gene1, gene2):\n ''' Takes 2 strings as arguments. Returns the Hamming Distance between the two arguments. Assumes both argument strings are of same length. ''' \n \n x = 0\n \n for i in range(len(gene1)):\n if (gene1[i] != gene2[i]):\n x = x + 1\n \n return x\n \ndef gene_dist(finch1, finch2):\n ''' Takes 2 arguments: list for an individual finch. Returns average Hamming Distance between the genes of the two individual finches given as arguments. '''\n \n a = allele_dist(finch1[2], finch2[2])\n b = allele_dist(finch1[2], finch2[3])\n c = allele_dist(finch1[3], finch2[2])\n d = allele_dist(finch1[3], finch2[3])\n \n avg = float((a + b + c + d) / 4)\n \n return avg\n\ndef beak_dist(finch1, finch2):\n ''' Takes 2 arguments: list for an individual finch. Returns average difference between the beak score of the two individual finches given as arguments. '''\n \n a = abs(finch1[4] - finch2[4])\n b = abs(finch1[4] - finch2[5])\n c = abs(finch1[5] - finch2[4])\n d = abs(finch1[5] - finch2[5])\n \n avg = float((a + b + c + d) / 4)\n \n return avg\n\n\ndef outgroup_distance(finches, speciesName, outgroupName):\n ''' Takes 3 arguments:\n – list of lists returned by read_input( )\n – name of Finch Species on which to collect information\n – name of Outgroup Species\n • used to standard basis for comparing the distance\n • will always be the species: L.noctis\n Returns two lists as a Tuple:\n – list of the gene differences for all individuals in that Finch Species\n – list of the beak differences for all individuals in that Finch Species '''\n \n o = [finch for finch in finches if finch[0] == outgroupName]\n s = [finch for finch in finches if finch[0] == speciesName]\n \n gd_list = []\n bd_list = []\n \n for finch1 in o:\n for finch2 in s:\n gd_list.append(gene_dist(finch1, finch2))\n bd_list.append(beak_dist(finch1, finch2))\n \n return (gd_list, bd_list)\n \n\ndef plot_data(file_name, x_column, y_column) :\n ''' Is the primary function that will call the other two functions and call the actual plotting functions. '''\n \n import matplotlib.pyplot as plt\n finch_data = read_input(file_name)\n \n x = outgroup_distance(finch_data, x_column, outgroup)\n y = outgroup_distance(finch_data, y_column, outgroup)\n plt.plot(x,y, \"ro\", label = \"G.conirostris_Espanola\")\n \n x = outgroup_distance(finch_data, x_column, outgroup)\n y = outgroup_distance(finch_data, y_column, outgroup)\n plt.plot(x,y, \"bo\", label = \"G.conirostris_Genovesa\")\n \n x = outgroup_distance(finch_data, x_column, outgroup)\n y = outgroup_distance(finch_data, y_column, outgroup)\n plt.plot(x,y, \"go\", label = \"G.difficilis\")\n \n x = outgroup_distance(finch_data, x_column, outgroup)\n y = outgroup_distance(finch_data, y_column, outgroup)\n plt.plot(x,y, \"ko\", label = \"G.magnirostris\")\n \n plt.xlabel('Gene Distance')\n plt.ylabel('Beak Distance')\n plt.legend(shadow=True, loc=\"upper right\")\n plt.title(\"Beak Distance vs. Gene Distance for Finches\")\n \nplot_data (\"finches.csv\", 0, 1)\n \n\n''' \n\n\n This dataset is perhaps the best known database in the pattern recognition literature. \n One flinch species is linearly separable from the other four, but the other three are not linearly separable from each other.\n\n G.difficilis is linearly seperate when plotting Beak Distance vs. Gene Distance for Finches. G.conirostris_Espanola, G.conirostris_Genovesa, and G.magnirostris are not linearly separable from each other when plotting Beak Distance vs. Gene Distance for Finches.\n The two species would cluster together if they are indeed different species because they have similar attributes of Finches such as the obvious from the scatterplot, Beak Distance lineraly alligning with Gene Distance.\n\n\n'''\n", "sub_path": "project_02.py", "file_name": "project_02.py", "file_ext": "py", "file_size_in_byte": 5438, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "csv.reader", "line_number": 27, "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": 116, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 116, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 120, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 120, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 124, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 124, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 126, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 126, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 127, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 127, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 128, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 128, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 129, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 129, "usage_type": "name"}]}
+{"seq_id": "533275529", "text": "import os\nfrom http.cookiejar import MozillaCookieJar\n\nfrom macaroonbakery import httpbakery\n\n\ndef run(url, request, payload=None):\n client = httpbakery.Client(cookies=MozillaCookieJar(\".login\"))\n\n if os.path.exists(client.cookies.filename):\n client.cookies.load(ignore_discard=True)\n\n if payload:\n response = client.request(request, url=url, json=payload)\n else:\n response = client.request(request, url=url)\n\n client.cookies.save(ignore_discard=True)\n print(response, response.text)\n\n\nnew_release = {\n \"name\": \"New Version\",\n \"version\": \"30.30\",\n \"codename\": \"version\",\n \"lts\": False,\n \"development\": True,\n \"release_date\": \"2021-04-22\",\n \"esm_expires\": \"2022-01-31\",\n \"support_expires\": \"2022-01-31\",\n}\n\nhippo = {\n \"name\": \"Hirsute Hippo\",\n \"version\": \"21.04\",\n \"codename\": \"hirsute\",\n \"lts\": False,\n \"development\": True,\n \"release_date\": \"2021-04-22\",\n \"esm_expires\": \"2022-01-31\",\n \"support_expires\": \"2022-01-31\",\n}\n\n\n# RELEASE TESTS\nbase_url = \"http://0.0.0.0:8030/security\"\n\nprint(\"Test create release => 200\")\nrun(f\"{base_url}/releases.json\", \"POST\", new_release)\n\nprint(\"Test edit release => 404\")\nrun(f\"{base_url}/releases/no-exist.json\", \"PUT\", new_release)\n\nprint(\"Test edit release => 422\")\nhippo[\"name\"] = \"Bionic Beaver\"\nrun(f\"{base_url}/releases/hirsute.json\", \"PUT\", hippo)\n\nprint(\"Test edit release => 200\")\nhippo[\"name\"] = \"Hirsute Hippo\"\nhippo[\"development\"] = True\nrun(f\"{base_url}/releases/hirsute.json\", \"PUT\", hippo)\n\nprint(\"Test delete non-existing release => 404\")\nrun(f\"{base_url}/releases/no-exist.json\", \"DELETE\")\n\nprint(\"Test delete release => 200\")\nrun(f\"{base_url}/releases/version.json\", \"DELETE\")\n", "sub_path": "scripts/api-release-tests.py", "file_name": "api-release-tests.py", "file_ext": "py", "file_size_in_byte": 1718, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "macaroonbakery.httpbakery.Client", "line_number": 8, "usage_type": "call"}, {"api_name": "macaroonbakery.httpbakery", "line_number": 8, "usage_type": "name"}, {"api_name": "http.cookiejar.MozillaCookieJar", "line_number": 8, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 10, "usage_type": "call"}, {"api_name": "os.path", "line_number": 10, "usage_type": "attribute"}]}
+{"seq_id": "471574668", "text": "import pandas as pd\r\nfrom matplotlib import pyplot as plt\r\nimport numpy as np\r\nfrom log_regression2 import log_regression\r\nfrom NaiveBayes3 import NaiveBayes\r\nfrom cross_validation2 import cross_validation\r\nimport separate\r\n\r\n# dictionary of categories: contains a dictionary for each feature, mapping an integer\r\n# to each category\r\ncategories = {}\r\n\r\n# Makes all the inputs of the dataset numerical\r\ndef transform(data):\r\n for j in range(len(data[0])):\r\n \r\n \r\n category_number = 0 # keeps track of the category number in the feature\r\n for i in range(len(data)):\r\n ## All features are categorical, even if some inputs are numerical \r\n # Ignore features that are already numerical\r\n #if (isinstance(data[i][j], int) or isinstance(data[i][j], float)):\r\n # break\r\n \r\n # Create a dictionary for a feature if it does not exist\r\n if j not in categories:\r\n categories[j] = {}\r\n \r\n # Add a numerical value to each category\r\n if data[i][j] not in categories[j]:\r\n categories[j][data[i][j]] = category_number\r\n category_number += 1\r\n \r\n data[i][j] = categories[j][data[i][j]]\r\n \r\n# Makes data one-hot encoded\r\ndef oneHot(data): \r\n one_hot = [] \r\n for i in range(len(data)):\r\n one_hot.append(list())\r\n \r\n for j in range(len(data[0])):\r\n # Just copy non-categorical features\r\n if j not in categories:\r\n one_hot[i].append(data[i][j])\r\n # Make categorical features one-hot encoded\r\n else:\r\n # Array of 0s of the length of the categories in that feature\r\n temp = [0]*len(categories[j])\r\n \r\n # Put 1 to the correct category\r\n temp[data[i][j]] = 1\r\n \r\n one_hot[i].extend(temp)\r\n \r\n one_hot = np.array(one_hot) \r\n return one_hot \r\n \r\n \r\n\r\n\r\ndata = pd.read_csv(\"car.csv\", header=None)\r\n\r\n# Transform data in numpy arrays\r\ndata = data.values\r\n\r\ndata_temp = np.zeros(data.shape, dtype = 'O')\r\n \r\nrow = 0\r\n# Detect oddities\r\nfor i in range(len(data)):\r\n \r\n # Test for missing data (row length)\r\n if len(data[0]) != len(data[i]):\r\n print(\"values on row \",i, \" are missing\")\r\n \r\n # Test for malformed features\r\n include = True # Only include rows that don't have missing features (?)\r\n for j in range(len(data[0])):\r\n # remove leading/trailing spaces\r\n if isinstance(data[i][j], str):\r\n data[i][j] = data[i][j].strip()\r\n \r\n # remove instances with missing data\r\n if data[i][j] == \"?\":\r\n include = False\r\n break\r\n \r\n # Only include rows that don't have missing features (?)\r\n if include == True:\r\n data_temp[row,:] = data[i,:]\r\n row += 1 \r\n\r\ndata = data_temp[0:row] \r\ndata_raw = data.copy()\r\n\r\n# Transform data into numerical values\r\ntransform(data)\r\n\r\n\r\nres = np.zeros(len(data))\r\n\r\n# Transform targets in a binary representation\r\n# combine unacc into bad and acc, good and vgood into good\r\n \r\nfor i in range(len(data)):\r\n #if data[i][len(data[0])-1] == 0 or data[i][len(data[0])-1] == 1:\r\n if data[i][len(data[0])-1] != 0:\r\n res[i] = 1\r\n else:\r\n res[i] = 0\r\n \r\n# if data[i][len(data[0])-1] == \">50K\":\r\n# res[i]=1\r\n# elif data[i][len(data[0])-1] == \"<=50K\":\r\n# res[i]=0\r\n\r\n# delete target from data (last column from data)\r\ndata = np.delete(data, len(data[0])-1, 1)\r\n\r\n# Make the input categories one_hot encoded\r\none_hot = oneHot(data)\r\n\r\n#print(data)\r\n\r\n# Histogram of the targets\r\nplt.figure(1)\r\n#plt.hist(res) \r\nplt.hist([res[np.argwhere(res == 0)], res[np.argwhere(res == 1)]], label=['bad', 'good'])\r\nplt.legend(loc='upper right') \r\nplt.title(\"Distribution of the positive vs negative classes\") \r\nplt.show()\r\n\r\n# Note: there are no numerical features in this dataset\r\n# Distributions of some categorical features (feature columns 0,1,2,3 were considered)\r\nf = (0,1,2,3)\r\n\r\npos = np.argwhere(res == 1)\r\nneg = np.argwhere(res == 0)\r\n\r\n# matrices (feature, data point) - separation between positive and negative features\r\npos_features = np.zeros((4,len(pos))) \r\nneg_features = np.zeros((4,len(neg)))\r\nfor i in range(4):\r\n neg_features[i,:] = np.squeeze(data[neg, f[i]])\r\n pos_features[i,:] = np.squeeze(data[pos, f[i]])\r\n\r\n\r\nplt.figure(2)\r\n\r\nfor i in range(4):\r\n plt.subplot(2,2,i+1)\r\n \r\n # Set bin boundaries by the minimum and maximum values of the features\r\n bins = np.linspace(min(min(neg_features[i,:]), min(pos_features[i,:])),\r\n max(max(neg_features[i,:]), max(pos_features[i,:])), 30)\r\n \r\n # Plot the histogram of the positive and negative features\r\n plt.hist([neg_features[i,:], pos_features[i,:]], bins, label=['neg', 'pos'])\r\n plt.legend(loc='upper right') \r\n \r\n plt.title(\"Distribution of feature #\" + str(f[i]))\r\n\r\nplt.show()\r\n\r\n# This dataset does not have numerical features, so correlation between features is not helpful\r\n# Correlation between some numerical features (feature columns 2,3,4,5 were considered)\r\n\r\n#plt.figure(3)\r\n\r\n#for i in range(4):\r\n #plt.subplot(2,2,i+1)\r\n \r\n ## Correlation coefficients\r\n #r_neg = np.corrcoef(neg_features[i,:], neg_features[(i+1)%4,:])\r\n #r_pos = np.corrcoef(pos_features[i,:], pos_features[(i+1)%4,:])\r\n \r\n ## Labels for the legend\r\n #lbl_neg = \"r_neg = \" + str(round(r_neg[0,1],4))\r\n #lbl_pos = \"r_pos = \" + str(round(r_pos[0,1],4))\r\n \r\n #plt.scatter(neg_features[i,:], neg_features[(i+1)%4,:], label=lbl_neg)\r\n #plt.scatter(pos_features[i,:], pos_features[(i+1)%4,:], label=lbl_pos)\r\n \r\n #plt.legend(loc='upper right') \r\n \r\n #plt.title(\"Correlation between feature #\" + str(f[i]) + \" and #\" + str(f[(i+1)%4])) \r\n \r\n\r\n#plt.show()\r\n\r\n# Final data variables X and target variables Y\r\nX = np.array(one_hot)\r\nY = np.array(res)\r\n\r\n##fit log model\r\n#log_model = log_regression(0.01, 20000)\r\n#X = log_model.bias(X) # add bias column\r\n\r\n## Separate training and testing sets \r\n#X_train, Y_train, X_test, Y_test = separate.separate(X,Y)\r\n\r\n## train the data\r\n#fit_iono = log_model.fit(X_train,Y_train) \r\n\r\n## test data\r\n#pre = log_model.predict(X_test,fit_iono) \r\n#acc = log_model.evaluate_acc(pre,Y_test)\r\n#print(acc)\r\n\r\n## Cross validation\r\n#validation = cross_validation(5)\r\n#score = validation.evaluate_log(X_train,Y_train)\r\n#print(score)\r\n\r\n#print(\"Naive Bayes:\")\r\n## fit naive bayes\r\n#bayes_model = NaiveBayes()\r\n#fit_bayes = bayes_model.fit(X_train,Y_train)\r\n#pre = bayes_model.predict(X_test)\r\n##acc = log_model.evaluate_acc(pre,Y_test)\r\n#acc = bayes_model.evaluate_acc(pre,Y_test)\r\n#print(acc)\r\n\r\n## Cross validation\r\n#score = bayes_model.cross_validation(X_train,Y_train, 5)\r\n#print(score)\r\n\r\n### Compare accuracy of naive Bayes and logistic regression\r\n\r\n## All datasets will use for logistic regression the same learning rate = 0.01 and # iterations = 500\r\n#rate = 0.01\r\n#iterations = 500\r\n\r\n#log_model = log_regression(rate, iterations)\r\n#X = log_model.bias(X) # add bias column\r\n\r\n## Separate training and testing sets \r\n#X_train, Y_train, X_test, Y_test = separate.separate(X,Y)\r\n\r\n\r\n\r\n## Compare accuracy of naive Bayes and logistic regression\r\n\r\n# All datasets will use for logistic regression the same learning rate = 0.01 and # iterations = 500\r\nrate = 0.01\r\niterations = 500\r\n\r\nlog_model = log_regression(rate, iterations)\r\nX = log_model.bias(X) # add bias column\r\n\r\n# Separate training and testing sets \r\nX_train, Y_train, X_test, Y_test = separate.separate(X,Y)\r\n\r\n## Logistic regression\r\n\r\n# train the data\r\nfit_iono = log_model.fit(X_train,Y_train) \r\n\r\n# Cross validation\r\nvalidation = cross_validation(rate, max_iterations = 500)\r\nscore = validation.evaluate_log(X_train,Y_train)\r\nprint(\"Averaged training accuracy for Logistic Regression: \", score)\r\n\r\n# Test data\r\npre = log_model.predict(X_test,fit_iono) \r\nacc = log_model.evaluate_acc(pre,Y_test)\r\nprint(\"Accuracy on testing data for Logistic Regression: \", acc)\r\n\r\n## Naive Bayes\r\n\r\n# train the data\r\nbayes_model = NaiveBayes()\r\nfit_bayes = bayes_model.fit(X_train,Y_train)\r\n\r\n\r\n# Cross validation\r\nscore = bayes_model.cross_validation(X_train,Y_train)\r\nprint(\"Averaged training accuracy for Naive Bayes: \", score)\r\n\r\n\r\n# Test data\r\npre = bayes_model.predict(X_test)\r\nacc = bayes_model.evaluate_acc(pre,Y_test)\r\nprint(\"Accuracy on testing data for Naive Bayes: \", acc)\r\n\r\nprint()\r\n## Test different learning rates for gradient descent\r\n\r\n# Loss function threshold = 5*10^-5; maximum number of iterations = 1000\r\niters = []\r\nacc=[]\r\nrate = 10**-15\r\nfor i in range(20):\r\n \r\n # Cross validation\r\n validation = cross_validation(rate, threshold = True)\r\n score, iterations = validation.evaluate_log(X_train,Y_train)\r\n #print(\"Averaged training accuracy for Logistic Regression: \", score)\r\n print(\"rate = \", rate, \"; iterations = \", iterations, \"; accuracy = \", score)\r\n acc.append(score)\r\n iters.append(iterations)\r\n rate *= 10\r\n\r\n\r\n\r\nrate = 1\r\n\r\nplt.scatter(iters, acc)\r\nplt.xlabel(\"iterations\")\r\nplt.ylabel(\"accurary\")\r\nplt.title(\"the accuracy on train set as a function of iterations of gradient descent\")\r\n\r\nplt.show()\r\n#size of x and accuracy\r\nacc = []\r\nsize = []\r\nsplit_size = 0.1\r\n\r\nfor i in range(9):\r\n X_train, Y_train, X_test, Y_test = separate.separate(X,Y, split=split_size)\r\n # Cross validation\r\n validation = cross_validation(rate, threshold = True)\r\n score, iterations = validation.evaluate_log(X_train,Y_train)\r\n #print(\"Averaged training accuracy for Logistic Regression: \", score)\r\n print(\"size of X = \", X_train.shape[0], \"; iterations = \", iterations, \"; accuracy = \", score)\r\n size.append(X_train.shape[0])\r\n acc.append(score)\r\n split_size += 0.1\r\n \r\nplt.scatter(size, acc)\r\nplt.xlabel(\"size of X_train\")\r\nplt.ylabel(\"accurary\")\r\nplt.title(\"the accuracy on train set as a function of size of X on logistic model\")\r\n\r\nplt.show()\r\n#bayes model\r\nacc = []\r\nsize = []\r\nsplit_size = 0.1\r\n\r\nfor i in range(9):\r\n X_train, Y_train, X_test, Y_test = separate.separate(X,Y, split=split_size)\r\n # Cross validation\r\n score = bayes_model.cross_validation(X_train,Y_train)\r\n #print(\"Averaged training accuracy for Logistic Regression: \", score)\r\n print(\"size of X = \", X_train.shape[0], \"; accuracy = \", score)\r\n size.append(X_train.shape[0])\r\n acc.append(score)\r\n split_size += 0.1\r\n \r\nplt.xlabel(\"size of X_train\")\r\nplt.ylabel(\"accurary\")\r\nplt.title(\"the accuracy on train set as a function of size od X on Naive Bayes model\")\r\nplt.scatter(size, acc)\r\nplt.show()", "sub_path": "car.py", "file_name": "car.py", "file_ext": "py", "file_size_in_byte": 10839, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "numpy.array", "line_number": 56, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 101, "usage_type": "call"}, {"api_name": "numpy.delete", "line_number": 119, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 127, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 127, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 129, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 129, "usage_type": "name"}, {"api_name": "numpy.argwhere", "line_number": 129, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 130, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 130, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "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.argwhere", "line_number": 138, "usage_type": "call"}, {"api_name": "numpy.argwhere", "line_number": 139, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 142, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 143, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 145, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 146, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 149, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 149, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 152, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 152, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 155, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 159, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 159, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 160, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 160, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 162, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 162, "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": "numpy.array", "line_number": 193, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 194, "usage_type": "call"}, {"api_name": "log_regression2.log_regression", "line_number": 249, "usage_type": "call"}, {"api_name": "separate.separate", "line_number": 253, "usage_type": "call"}, {"api_name": "cross_validation2.cross_validation", "line_number": 261, "usage_type": "call"}, {"api_name": "NaiveBayes3.NaiveBayes", "line_number": 273, "usage_type": "call"}, {"api_name": "cross_validation2.cross_validation", "line_number": 297, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 309, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 309, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 310, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 310, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 311, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 311, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 312, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 312, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 314, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 314, "usage_type": "name"}, {"api_name": "separate.separate", "line_number": 321, "usage_type": "call"}, {"api_name": "cross_validation2.cross_validation", "line_number": 323, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 331, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 331, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 332, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 332, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 333, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 333, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 334, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 334, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 336, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 336, "usage_type": "name"}, {"api_name": "separate.separate", "line_number": 343, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 352, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 352, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 353, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 353, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 354, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 354, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 355, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 355, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 356, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 356, "usage_type": "name"}]}
+{"seq_id": "423177826", "text": "import pandas as pd\nimport numpy as np\nimport pickle\n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.impute import SimpleImputer\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.ensemble import RandomForestClassifier\n\nCAT_FEATS = ['Gender',\n 'Married',\n 'Dependents',\n 'Education',\n 'Self_Employed',\n 'Property_Area']\n\nNUM_FEATS = ['ApplicantIncome',\n 'CoapplicantIncome',\n 'LoanAmount',\n 'Loan_Amount_Term',\n 'Credit_History']\n\n###########################\n# DATA PROCESSING FUNCTIONS\n###########################\n\n\nclass Transformer():\n def __init__(self, func):\n self.func = func\n\n def transform(self, input_df, **transform_params):\n return self.func(input_df)\n\n def fit(self, X, y=None, **fit_params):\n return self\n\n\ndef outliers(data):\n \"\"\"\n Removes ApplicantIncome and Loan Amount rows less than or equal to three standard deviations from mean\n \"\"\"\n data = data[np.abs(data.ApplicantIncome-data.ApplicantIncome.mean()) <= (3*data.ApplicantIncome.std())]\n data = data[np.abs(data.LoanAmount-data.LoanAmount.mean()) <= (3*data.LoanAmount.std())]\n return data\n\n\ndef impute_credit(data):\n \"\"\"\n Imputes credit history binary value.\n Probability for this random choice is hardcoded and based on the distribution of the population.\n \"\"\"\n data['Credit_History'] = data['Credit_History'].fillna(pd.Series(np.random.choice([1.0,0.0],\n p=[0.842199, 0.157801],\n size=len(data))))\n return data\n\n\ndef impute_gender(data):\n \"\"\"\n Imputes gender binary value. Non-Binary gender was not included in dataset.\n Probability for this random choice is hardcoded and based on the distribution of the population.\n \"\"\"\n data['Gender'] = data['Gender'].fillna(pd.Series(np.random.choice(['Male','Female'],\n p=[0.81, 0.19],\n size=len(data))))\n return data\n\n\ndef impute_marriage(data):\n data['Married'] = data['Married'].fillna(pd.Series(np.random.choice(['Yes','No'], \n p=[0.65, 0.35],\n size=len(data))))\n data['Dependents'] = data['Dependents'].replace('3+', 3)\n data['Dependents'] = data[['Dependents']].fillna(0).astype('int16')\n return data\n\n\ndef impute_employment(data):\n data['Self_Employed'] = data['Self_Employed'].fillna(pd.Series(np.random.choice(['Yes','No'],\n p=[0.86, 0.14],\n size=len(data))))\n return data\n\n\ndef binarizer(data):\n \"\"\"\n Manually label encodes binary features\n \"\"\"\n data['Male'] = np.where(data['Gender'] == 'Male', 1, 0)\n data['Graduated'] = np.where(data['Education'] == 'Graduate', 1, 0)\n data['Married'] = np.where(data['Married'] == 'Yes', 1, 0)\n data['Self_Employed'] = np.where(data['Self_Employed'] == 'Yes', 1, 0)\n return data\n\n\ndef dummy(data):\n data = pd.get_dummies(data, columns=['Property_Area'])\n return data\n\n\ndef dummies(data):\n \"\"\"\n Manually creates labels for property type. sklearn label encoder was breaking the model shape.\n \"\"\"\n data['Property_Area'] = data['Property_Area'].replace('Rural', 0, regex=True)\n data['Property_Area'] = data['Property_Area'].replace('Semiurban', 1, regex=True)\n data['Property_Area'] = data['Property_Area'].replace('Urban', 2, regex=True)\n return data\n\n\ndef shed(data):\n \"\"\"\n Drops columns that have been encoded\n \"\"\"\n data = data.drop(['Gender','Education','Married','Self_Employed'],axis=1)\n return data\n\n\ndef impute_loan_term(data):\n \"\"\"\n Imputes loan term value with the mean loan term.\n \"\"\"\n data['Loan_Amount_Term'] = data['Loan_Amount_Term'].fillna(data['Loan_Amount_Term'].mean())\n data['Loan_Amount_Term'] = data['Loan_Amount_Term']/12\n return data\n\n#######################\n# PIPELINE\n#######################\n#\n# Numerical and categorical data will have separate pipelines.\n# Both pieplines feed into the prediction pipeline.\n\n\nnumeric_transformer = Pipeline(steps=[\n ('credit', Transformer(impute_credit)),\n ('term', Transformer(impute_loan_term)),\n ('imputer', SimpleImputer(strategy='mean', fill_value='missing')),\n ('scaler', StandardScaler())\n ])\n\ncategorical_transformer = Pipeline(steps=[\n ('gender', Transformer(impute_gender)),\n ('marriage', Transformer(impute_marriage)),\n ('employment', Transformer(impute_employment)),\n ('dummies', Transformer(dummies)),\n ('shed', Transformer(shed)),\n ])\n\npreprocessor = ColumnTransformer(\n transformers=[\n ('num', numeric_transformer, NUM_FEATS),\n ('cat', categorical_transformer, CAT_FEATS)])\n\nrf_clf = Pipeline(steps=[('preprocessor', preprocessor),\n ('rf_clf', RandomForestClassifier())])", "sub_path": "functions.py", "file_name": "functions.py", "file_ext": "py", "file_size_in_byte": 5352, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "numpy.abs", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 46, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 55, "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": "pandas.Series", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 66, "usage_type": "attribute"}, {"api_name": "pandas.Series", "line_number": 73, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 73, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 73, "usage_type": "attribute"}, {"api_name": "pandas.Series", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 82, "usage_type": "attribute"}, {"api_name": "numpy.where", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 95, "usage_type": "call"}, {"api_name": "pandas.get_dummies", "line_number": 100, "usage_type": "call"}, {"api_name": "sklearn.pipeline.Pipeline", "line_number": 138, "usage_type": "call"}, {"api_name": "sklearn.impute.SimpleImputer", "line_number": 141, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.StandardScaler", "line_number": 142, "usage_type": "call"}, {"api_name": "sklearn.pipeline.Pipeline", "line_number": 145, "usage_type": "call"}, {"api_name": "sklearn.compose.ColumnTransformer", "line_number": 153, "usage_type": "call"}, {"api_name": "sklearn.pipeline.Pipeline", "line_number": 158, "usage_type": "call"}, {"api_name": "sklearn.ensemble.RandomForestClassifier", "line_number": 159, "usage_type": "call"}]}
+{"seq_id": "166149396", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n flask.ext.fragment\n ------------------\n\n Flask extension to implement fragment caching.\n\n :copyright: (c) 2013 by Alexey Poryadin.\n :license: MIT, see LICENSE for more details.\n\"\"\"\nimport flask\nimport jinja2\nimport inspect\nfrom functools import partial\nfrom flask import Flask, Blueprint\nfrom flask import _app_ctx_stack as stack\n\n\nclass Fragment(object):\n\n def __init__(self, app=None):\n self.mod = None\n self.endpoint_url = None\n self.resethandler = None\n self.app = app\n if app is not None:\n self.init_app(app)\n\n def __call__(self, mod, endpoint_url=None, resethandler=None):\n \"\"\"Decorator to define function as fragment cached view\n\n Args:\n mod: Flask app or blueprint\n endpoint_url: Access point\n \"\"\"\n self.mod = mod\n self.endpoint_url = endpoint_url\n self.resethandler = resethandler\n\n def decorator(fragment_view):\n fragment_view_name = fragment_view.__name__\n fragment_view.cache_endpoint_url = self.endpoint_url if self.endpoint_url else fragment_view_name\n fragment_view.cache_resethandler = resethandler\n if self.endpoint_url:\n rule = '/{0}'.format(self.endpoint_url)\n elif isinstance(mod, Blueprint):\n rule = '/{0}.{1}'.format(mod.name, fragment_view_name)\n else:\n rule = '/{0}'.format(fragment_view_name)\n fragment_view_signature = inspect.signature(fragment_view)\n fragment_view.args_names = fragment_view_signature.parameters\n for arg_name in fragment_view.args_names:\n rule += '/<{0}>'.format(arg_name)\n mod.add_url_rule(rule, fragment_view_name, fragment_view)\n return fragment_view\n return decorator\n\n def init_app(self, app):\n self.app = app\n self.app.context_processor(lambda: {'fragment': self._fragment_tmpl_func})\n \n def resethandler(self, fragment_view):\n \"\"\"Decorator sets reset fragment cache handler for `fragment_view` function.\"\"\"\n def decorator(handler):\n fragment_view.cache_resethandler = handler\n return handler\n return decorator \n\n def reset(self, target, *args, **kwargs):\n \"\"\"Resets cache for fragment cached view\n \n Args:\n target: Endpoint or the view itself.\n \"\"\"\n if isinstance(target, str):\n fragment_view = flask.current_app.view_functions.get(target)\n if fragment_view is None:\n raise ValueError('Not found view for endpoint \"{0}\"'.format(target))\n else:\n fragment_view = target\n if fragment_view.cache_resethandler is None:\n # Tries default resethandler handler\n try:\n for N in range(0, len(args)):\n kwargs[fragment_view.args_names[N]] = args[N]\n url = flask.url_for(fragment_view.cache_endpoint_url, **kwargs)\n except Exception as exc:\n raise RuntimeError('Cannot reset cache for \"{0}\",'\n ' resethandler is not set and default handler canot'\n ' build URL. Detail: \"{1}\"'.format(fragment_view, exc))\n self.reset_url(url)\n else:\n fragment_view.cache_resethandler(*args, **kwargs)\n \n \n def reset_url(self, url):\n \"\"\"Resets cache for URL\n \n Args:\n url: URL value\n \"\"\"\n raise NotImplementedError('Need to look around ngx_cache_purge')\n\n def _fragment_tmpl_func(self, endpoint, *args, **kwargs):\n \"\"\"Template context function that renders fragment cached view.\n \n Accepts `*args`, `**kwargs` that must match by the number and by the\n order of parameters from function that defined with 'endpoint'.\n \n Args:\n endpoint: The endpoint name.\n \"\"\"\n func = flask.current_app.view_functions.get(endpoint)\n if func is not None:\n for N in range(0, len(args)):\n kwargs[func.args_names[N]] = args[N]\n url = flask.url_for(endpoint, **kwargs)\n return self._render(url, partial(func, **kwargs))\n raise ValueError('Not found view for endpoint \"{0}\"'.format(endpoint))\n\n def _render(self, url, deferred_view):\n if self.app.config.get('FRAGMENT_SSI', False):\n content = ''.format(url)\n else:\n response = deferred_view()\n content = response.get_data().decode(response.mimetype_params['charset'])\n return jinja2.Markup(content)\n", "sub_path": "flask_ssi/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 4729, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "flask.Blueprint", "line_number": 46, "usage_type": "argument"}, {"api_name": "inspect.signature", "line_number": 50, "usage_type": "call"}, {"api_name": "flask.current_app.view_functions.get", "line_number": 76, "usage_type": "call"}, {"api_name": "flask.current_app", "line_number": 76, "usage_type": "attribute"}, {"api_name": "flask.url_for", "line_number": 86, "usage_type": "call"}, {"api_name": "flask.current_app.view_functions.get", "line_number": 113, "usage_type": "call"}, {"api_name": "flask.current_app", "line_number": 113, "usage_type": "attribute"}, {"api_name": "flask.url_for", "line_number": 117, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 118, "usage_type": "call"}, {"api_name": "jinja2.Markup", "line_number": 127, "usage_type": "call"}]}
+{"seq_id": "595059139", "text": "# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass ContainerExecRequestTerminalSize(Model):\n \"\"\"The size of the terminal.\n\n :param rows: The row size of the terminal\n :type rows: int\n :param cols: The column size of the terminal\n :type cols: int\n \"\"\"\n\n _attribute_map = {\n 'rows': {'key': 'rows', 'type': 'int'},\n 'cols': {'key': 'cols', 'type': 'int'},\n }\n\n def __init__(self, rows=None, cols=None):\n super(ContainerExecRequestTerminalSize, self).__init__()\n self.rows = rows\n self.cols = cols\n", "sub_path": "azure-mgmt-containerinstance/azure/mgmt/containerinstance/models/container_exec_request_terminal_size.py", "file_name": "container_exec_request_terminal_size.py", "file_ext": "py", "file_size_in_byte": 1027, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "msrest.serialization.Model", "line_number": 15, "usage_type": "name"}]}
+{"seq_id": "30590007", "text": "#!/usr/bin/env python3\n# coding=utf-8\nimport os\nimport sys\nfrom time import sleep\nimport re\nimport socket\nimport shutil\nimport subprocess\nimport logging\nimport traceback\nfrom urllib.parse import urljoin\n\n__AUTHOR__ = 'Aploium '\n__VERSION__ = '0.7.0'\n__ZMIRROR_PROJECT_URL__ = 'https://github.com/aploium/zmirror/'\n__ZMIRROR_GIT_URL__ = 'https://github.com/aploium/zmirror.git'\n__ONKEY_PROJECT_URL__ = 'https://github.com/aploium/zmirror-onekey/'\n__ONKEY_PROJECT_URL_CONTENT__ = 'https://raw.githubusercontent.com/aploium/zmirror-onekey/master/'\n__REPORT_URLS__ = {\n \"error\": \"https://report.zmirror.org/onekey/log/error\",\n \"success\": \"https://report.zmirror.org/onekey/log/success\",\n}\n\nDEBUG = '--debug' in sys.argv\n\n\ndef cmd(command, cwd=None, **kwargs):\n \"\"\"运行shell命令\"\"\"\n return subprocess.check_call(command, shell=True, cwd=cwd or os.getcwd(), **kwargs)\n\n\ncmd('export LC_ALL=C.UTF-8') # 设置bash环境为utf-8\n\ncmd('apt-get update && apt-get install python3 python3-pip -y')\n\n# for some old version Linux, pip has bugs, causing:\n# ImportError: cannot import name 'IncompleteRead'\n# so we need to upgrade pip first\ncmd('easy_install3 -U pip')\n\n# 安装本脚本必须的python包\ncmd('python3 -m pip install -U requests')\ncmd('python3 -m pip install -U distro')\n\nimport distro\n\n\ndef onekey_report(report_type=\"success\", installing_mirror=None, traceback_str=None):\n \"\"\"\n 发送报告到服务器\n \"\"\"\n import json\n import distro\n import re\n\n dist = json.dumps(distro.info(best=True))\n data = {\"linux_dist\": dist}\n\n if installing_mirror is not None:\n if isinstance(installing_mirror, (list, tuple)):\n installing_mirror = ','.join(installing_mirror)\n data['installing_mirror'] = installing_mirror\n\n if traceback_str is not None:\n data['traceback'] = traceback_str\n\n try:\n meminfo = open('/proc/meminfo').read()\n matched = re.search(r'^MemTotal:\\s+(\\d+)', meminfo)\n if matched:\n mem_total_KB = int(matched.groups()[0])\n data['memory'] = mem_total_KB\n except:\n pass\n\n if DEBUG:\n print(__REPORT_URLS__[report_type], data)\n\n try:\n r = requests.post(__REPORT_URLS__[report_type], data=data)\n except:\n if DEBUG:\n traceback.print_exc()\n else:\n if DEBUG:\n print(r.text, r.headers, r.request.body)\n\n\ntry:\n import requests\nexcept:\n print('Could not install requests, program exit')\n exit(1)\n\nif DEBUG:\n logging.basicConfig(\n level=logging.NOTSET,\n format='[%(levelname)s %(asctime)s %(funcName)s] %(message)s',\n )\n\nif sys.platform != 'linux':\n print('This program can ONLY be used in debian-like Linux (debian, ubuntu and some others)')\n exit(1)\nif os.geteuid() != 0:\n print('Root privilege is required for this program. Please use `sudo python3 deploy.py`')\n exit(2)\n\nserver_configs = {\n \"apache\": {\n \"config_root\": \"/etc/apache2/\",\n \"htdoc\": \"/var/www/\",\n\n \"common_configs\": [\"http_generic\", \"apache_boilerplate\"],\n \"site_unique_configs\": [\"https\"],\n\n \"pre_delete_files\": [\n \"{config_root}/sites-enabled/000-default.conf\",\n \"{config_root}/conf-enabled/apache2-doc.conf\",\n \"{config_root}/conf-enabled/security.conf\",\n ],\n\n \"configs\": {\n \"apache_boilerplate\": {\n \"url\": urljoin(__ONKEY_PROJECT_URL_CONTENT__, \"configs/apache2-boilerplate.conf\"),\n \"file_path\": \"conf-enabled/zmirror-apache-boilerplate.conf\",\n },\n\n \"http_generic\": {\n \"url\": urljoin(__ONKEY_PROJECT_URL_CONTENT__, \"configs/apache2-http.conf\"),\n \"file_path\": \"sites-enabled/zmirror-http-redirection.conf\",\n },\n\n \"https\": {\n \"url\": urljoin(__ONKEY_PROJECT_URL_CONTENT__, \"configs/apache2-https.conf\"),\n \"file_path\": \"sites-enabled/zmirror-{mirror_name}-https.conf\",\n },\n }\n\n }\n}\n\nmirrors_settings = {\n 'google': {\n 'domain': None,\n 'cfg': [('more_configs/config_google_and_zhwikipedia.py', 'config.py'), ],\n },\n\n 'youtubePC': {\n 'domain': None,\n 'cfg': [('more_configs/config_youtube.py', 'config.py'),\n ('more_configs/custom_func_youtube.py', 'custom_func.py')],\n },\n\n 'twitterPC': {\n 'domain': None,\n 'cfg': [('more_configs/config_twitter_pc.py', 'config.py'),\n ('more_configs/custom_func_twitter.py', 'custom_func.py'), ],\n },\n\n 'twitterMobile': {\n 'domain': None,\n 'cfg': [('more_configs/config_twitter_mobile.py', 'config.py'),\n ('more_configs/custom_func_twitter.py', 'custom_func.py'), ],\n },\n\n 'instagram': {\n 'domain': None,\n 'cfg': [('more_configs/config_instagram.py', 'config.py'), ],\n },\n}\n\nprint('OneKey deploy script for zmirror. version', __VERSION__)\nprint('This script will automatically deploy mirror(s) using zmirror in your ubuntu')\nprint('You could cancel this script in the config stage by precessing Ctrl-C')\nprint('Installation will start after 1 second')\nprint()\nsleep(1)\n\n# ################# 安装一些依赖包 ####################\nprint('[zmirror] Installing some necessarily packages')\n\ntry:\n # 设置本地时间为北京时间\n cmd('cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime')\n # 告诉apt-get要安静\n cmd('export DEBIAN_FRONTEND=noninteractive')\n # 更新apt-get\n cmd('apt-get update')\n # 安装必须的包\n cmd('apt-get install git python3 python3-pip wget curl -y')\n # 安装非必须的包\n try:\n # 更新一下openssl\n cmd('apt-get install openssl -y')\n # 如果安装了, 则可以启用http2\n cmd('apt-get install software-properties-common python-software-properties -y')\n except:\n pass\n\n if distro.id() == 'ubuntu':\n # 安装高版本的Apache2(支持http2), 仅限ubuntu\n cmd(\"\"\"LC_ALL=C.UTF-8 add-apt-repository -y ppa:ondrej/apache2 &&\n apt-key update &&\n apt-get update &&\n apt-get install apache2 -y\"\"\")\n elif distro.id() == 'debian':\n # debian 只有低版本的可以用\n cmd(\"apt-get install apache2 -y\")\n\n cmd(\"\"\"a2enmod rewrite mime include headers filter expires deflate autoindex setenvif ssl http2\"\"\")\n\n # (可选) 更新一下各种包\n if not (distro.id() == 'ubuntu' and distro.version() == '14.04'): # 系统不是ubuntu 14.04\n # Ubuntu 14.04 执行本命令的时候会弹一个postfix的交互, 所以不执行\n cmd('apt-get upgrade -y')\n\n cmd(\"\"\"apt-get install libapache2-mod-wsgi-py3 -y && a2enmod wsgi\"\"\")\n\n # 安装和更新必须的python包\n cmd('python3 -m pip install -U requests flask')\n # 安装和更新非必须, 但是有好处的python包\n try:\n cmd('python3 -m pip install -U chardet fastcache cchardet')\n except:\n pass # 允许安装失败\n\n print('[zmirror] Dependency packages install completed')\n print('[zmirror] Installing letsencrypt...')\n sleep(1)\n\n if not os.path.exists('/etc/certbot/'):\n # certbot 不存在, 则安装\n cmd('git clone https://github.com/certbot/certbot.git', cwd='/etc/')\n cmd('chmod a+x /etc/certbot/certbot-auto', cwd='/etc/certbot/')\n cmd('service apache2 stop')\n cmd('./certbot-auto renew --agree-tos -n --standalone '\n '--pre-hook \"service apache2 stop\" '\n '--post-hook \"service apache2 start\"',\n cwd='/etc/certbot/')\n else:\n # 否则升级一下\n cmd('git pull', cwd='/etc/certbot/')\n\n print(\"[zmirror] let's encrypt Installation Completed\")\n sleep(1)\n\n print('\\n\\n\\n-------------------------------\\n'\n '[zmirror] Now we need some information:')\nexcept:\n onekey_report('error', traceback_str=traceback.format_exc())\n raise\n\nmirrors_to_deploy = []\ntry:\n _input = -1\n while _input: # 不断循环输入, 因为用户可能想要安装多个镜像\n print('----------------------')\n _input = input(\n \"\"\"Please select mirror you want to deploy?\n select one mirror a time, you could select zero or more mirror(s)\n\n 1. Google (include scholar, image, zh_wikipedia) {google}\n 2. twitter (PC) {twitterPC}\n 3. twitter (Mobile) {twitterMobile}\n 4. youtube (pc) {youtubePC}\n 5. instagram {instagram}\n 0. Go to next steps. (OK, I have selected all mirror(s) I want to deploy)\n\n input 0-5: \"\"\".format(\n google='[SELECTED]' if 'google' in mirrors_to_deploy else '',\n twitterPC='[SELECTED]' if 'twitterPC' in mirrors_to_deploy else '',\n twitterMobile='[SELECTED]' if 'twitterMobile' in mirrors_to_deploy else '',\n youtubePC='[SELECTED]' if 'youtubePC' in mirrors_to_deploy else '',\n instagram='[SELECTED]' if 'instagram' in mirrors_to_deploy else '',\n )\n\n )\n\n if not _input:\n break\n\n logging.debug(\"input:\" + _input)\n\n try:\n _input = int(_input)\n except:\n print(\"Please input correct number\")\n _input = -1\n\n if _input == 0:\n break\n if not (0 <= _input <= 5):\n print('[ERROR] please input correct number (0-5), only select one mirror a time\\n'\n '-------------------------\\n\\n')\n continue\n\n # 将数字选项转化为字符串\n mirror_type = {\n 1: \"google\",\n 2: \"twitterPC\",\n 3: \"twitterMobile\",\n 4: \"youtubePC\",\n 5: \"instagram\",\n }[_input]\n\n # 在选项里, 镜像已存在, 则删去, 并且跳过下面的步骤\n if mirror_type in mirrors_to_deploy:\n mirrors_to_deploy.remove(mirror_type)\n print(\"Mirror:{mirror_type} unchecked.\".format(mirror_type=mirror_type))\n continue\n\n # 输入镜像对应的域名, 要求已经在DNS设置中用一个A记录指向了本服务器\n while True: # 这里面会检查输入的是否是三级域名\n domain = input(\"Please input your domain for this mirror: \")\n domain = domain.strip(' /.\\t').replace('https://', '').replace('http://', '') # 修剪\n if domain.count('.') != 2:\n if input((\"Your domain [{domain}] is not an third-level domain, \"\n \"which contains three parts and two dots. \\n\"\n \"eg1: lovelucia.zmirrordemo.com eg2: g.mymirror.com\\n\"\n \"zmirror officially only support third-level domain\\n\"\n \"a none third-level domain MAY work, but may cause potential errors\\n\"\n \"Continue anyway(y/N)?\"\n ).format(domain=domain)) in ('y', 'yes', 'Yes', 'YES'):\n break\n # 如果选择的是 N, 则重新输入\n else: # 输入的是三级域名\n break\n\n # 初步检验域名是否已经被正确设置\n try:\n domain_ip = socket.gethostbyname(domain)\n local_ip = socket.gethostbyname(socket.gethostname())\n except Exception as e: # 查询目标域名的IP失败\n print(\"Sorry, your domain [{domain}] is not setting correctly. {exc}\".format(domain=domain, exc=str(e)))\n continue_anyway = input(\"Continue anyway? (y/N): \")\n if continue_anyway not in ('y', 'yes', 'Yes', 'YES'):\n continue # 重新来\n else:\n # 仍然继续的话, 把domain_ip当做local_ip\n domain_ip = local_ip\n\n # 域名检验--目标域名的IP不等于本地机器的IP\n if domain_ip != local_ip:\n print(\"\"\"Sorry, your domain({domain})'s ip does not equals to this machine's ip.\n domain's ip is: {domain_ip}\n this machine's ip is: {local_ip}\n \"\"\".format(domain=domain, domain_ip=domain_ip, local_ip=local_ip)\n )\n continue_anyway = input(\"Continue anyway? (y/N): \")\n if continue_anyway not in ('y', 'yes', 'Yes', 'YES'):\n continue # 重新来\n\n # 域名检验--域名是否重复\n _dup_flag = False\n for mirror in mirrors_to_deploy:\n if mirrors_settings[mirror_type]['domain'] == domain:\n print(\"Duplicated domain! conflict with mirror: \" + mirror)\n _dup_flag = True\n break\n if _dup_flag:\n continue\n\n # 将镜像添加到待安装列表中\n mirrors_to_deploy.append(mirror_type)\n mirrors_settings[mirror_type]['domain'] = domain\n print(\"Mirror:{mirror_type} Domain:{domain} checked\".format(mirror_type=mirror_type, domain=domain))\n\n logging.debug(mirrors_to_deploy)\n\n if not mirrors_to_deploy:\n print('[ERROR] you didn\\'t select any mirror.\\nAbort installation')\n exit(4)\n\n email = input('Please input your email (because letsencrypt requires an email for certification)\\n')\n\n print('Your email:', email)\n\n # 最后确认一遍设置\n print('----------------------')\n print('Now, we are going to install, please check your settings here:')\n print(\"Email: \" + email)\n print()\n for mirror in mirrors_to_deploy:\n print(\"Mirror: {mirror} Domain: {domain}\".format(mirror=mirror, domain=mirrors_settings[mirror]['domain']))\n\n if input('Are these settings correct (Y/n)? ') in ('N', 'No', 'n', 'no', 'not', 'none'):\n print('installation aborted.')\n exit(5)\n\n # ############### Really Install ###################\n\n # 通过 letsencrypt 获取HTTPS证书\n print(\"Fetching HTTPS certifications\")\n cmd(\"service apache2 stop\") # 先关掉apache\n for mirror in mirrors_to_deploy:\n domain = mirrors_settings[mirror]['domain']\n\n if os.path.exists('/etc/letsencrypt/live/{domain}'.format(domain=domain)):\n # 如果证书已存在, 则跳过\n print(\"Certification for {domain} already exists, skipping\".format(domain=domain))\n continue\n\n print(\"Obtaining: {domain}\".format(domain=domain))\n cmd(\n ('./certbot-auto certonly -n --agree-tos -t -m \"{email}\" --standalone -d \"{domain}\" '\n '--pre-hook \"/usr/sbin/service apache2 stop\" '\n '--post-hook \"/usr/sbin/service apache2 start\"'\n ).format(email=email, domain=domain),\n cwd='/etc/certbot/'\n )\n\n # 检查是否成功获取证书\n if not os.path.exists('/etc/letsencrypt/live/{domain}'.format(domain=domain)):\n print('[ERROR] Could NOT obtain an ssl cert, '\n 'please check your DNS record, '\n 'and then run again.\\n'\n 'Installation abort')\n exit(3)\n print(\"Succeed: {domain}\".format(domain=domain))\n cmd(\"service apache2 start\") # 重新启动apache\n\n # ####### 安装zmirror自身 #############\n print('[zmirror] Successfully obtain SSL cert, now installing zmirror itself...')\n sleep(1)\n\n this_server = server_configs['apache']\n htdoc = this_server['htdoc']\n config_root = this_server['config_root']\n assert isinstance(htdoc, str)\n assert isinstance(config_root, str)\n os.chdir(htdoc)\n cmd('git clone %s zmirror' % __ZMIRROR_GIT_URL__, cwd=htdoc)\n zmirror_source_folder = os.path.join(htdoc, 'zmirror')\n\n # 预删除文件\n for pre_delete_file in this_server['pre_delete_files']:\n abs_path = pre_delete_file.format(\n config_root=config_root, htdoc=htdoc\n )\n print(\"deleting: \" + abs_path)\n try:\n os.remove(abs_path)\n except:\n logging.debug(\"Unable to remove file:\" + abs_path + \"\\n\" + traceback.format_exc())\n\n # 拷贝并设置各个镜像\n for mirror in mirrors_to_deploy:\n domain = mirrors_settings[mirror]['domain']\n this_mirror_folder = os.path.join(htdoc, mirror)\n\n # 如果文件夹已存在, 则报错\n if os.path.exists(this_mirror_folder):\n print(\n (\"Folder {folder} already exists.\"\n \"If you want to override, please delete that folder manually and run this script again\"\n ).format(folder=this_mirror_folder)\n )\n raise FileExistsError(\"Folder {folder} for mirror [{mirror_name}] already exists.\".format(\n folder=this_mirror_folder, mirror_name=mirror))\n\n # 将 zmirror 文件夹复制一份\n shutil.copytree(zmirror_source_folder, this_mirror_folder)\n # 更改文件夹所有者为 www-data (apache的用户)\n shutil.chown(this_mirror_folder, \"www-data\", \"www-data\")\n\n this_mirror = mirrors_settings[mirror]\n\n for file_from, file_to in this_mirror['cfg']:\n shutil.copy(os.path.join(this_mirror_folder, file_from),\n os.path.join(this_mirror_folder, file_to))\n\n with open(os.path.join(this_mirror_folder, 'config.py'), 'r+', encoding='utf-8') as fp:\n # noinspection PyRedeclaration\n content = fp.read()\n\n # 将 my_host_name 修改为对应的域名\n content = re.sub(r\"\"\"my_host_name *= *(['\"])[-.\\w]+\\1\"\"\",\n \"my_host_name = '{domain}' # Modified by zmirror-onekey\".format(domain=domain),\n content, count=1)\n # 将 my_host_scheme 修改为 https://\n content = re.sub(r\"\"\"my_host_scheme *= *(['\"])https?://\\1\"\"\",\n \"my_host_scheme = 'https://' # Modified by zmirror-onekey\",\n content, count=1)\n # 在文件末尾添加 verbose_level = 2\n content += '\\nverbose_level = 2 # Added by zmirror-onekey\\n'\n\n fp.seek(0) # 指针返回文件头\n fp.write(content) # 回写\n\n shutil.rmtree(zmirror_source_folder) # 删除无用的 zmirror 文件夹\n\n print(\"[zmirror] zmirror program folders deploy completed\")\n\n # ############# 配置Apache ###############\n print(\"[zmirror] Now installing apache configs...\")\n sleep(0.5)\n\n os.chdir(config_root)\n\n # 下载通用配置文件\n for conf_name in this_server['common_configs']:\n assert isinstance(config_root, str)\n url = this_server['configs'][conf_name]['url']\n file_path = os.path.join(config_root, this_server['configs'][conf_name]['file_path'])\n\n if os.path.exists(file_path): # 若配置文件已存在则跳过\n print(\"Config {path} already exists, skipping\".format(path=file_path))\n continue\n\n with open(file_path, 'w', encoding='utf-8') as fp:\n print(\"downloading: \", conf_name)\n fp.write(requests.get(url).text)\n\n # 下载并设置各个镜像的Apache配置文件\n for mirror in mirrors_to_deploy:\n domain = mirrors_settings[mirror]['domain']\n this_mirror_folder = os.path.join(htdoc, mirror)\n\n for conf_name in this_server['site_unique_configs']:\n url = this_server['configs'][conf_name]['url']\n file_path = os.path.join(config_root, this_server['configs'][conf_name]['file_path'])\n file_path = file_path.format(mirror_name=mirror, conf_name=conf_name)\n\n if os.path.exists(file_path): # 若配置文件已存在则跳过\n print(\"Config {path} already exists, skipping\".format(path=file_path))\n continue\n\n print(\"downloading: \", mirror, conf_name)\n\n conf = requests.get(url).text\n\n # 因为Apache conf里面有 {Ascii字符} 这种结构, 与python的string format冲突\n # 这边只能手动format\n for key, value in [\n ('domain', domain),\n ('mirror_name', mirror),\n ('path_to_wsgi_py', os.path.join(this_mirror_folder, 'wsgi.py')),\n ]:\n conf = conf.replace(\"{{%s}}\" % key, value)\n\n with open(file_path, 'w', encoding='utf-8') as fp:\n fp.write(conf)\n\n # ##### Add linux cron script for letsencrypt auto renewal ######\n if not os.path.exists(\"/etc/cron.weekly/zmirror-letsencrypt-renew.sh\"): # 若脚本已存在则跳过\n print(\"Adding cert auto renew script to `/etc/cron.weekly/zmirror-letsencrypt-renew.sh`\")\n cron_script = \"\"\"#!/bin/bash\n cd /etc/certbot\n ./certbot-auto renew -n --agree-tos --standalone --pre-hook \"/usr/sbin/service apache2 stop\" --post-hook \"/usr/sbin/service apache2 start\"\n exit 0\n \"\"\"\n with open(\"/etc/cron.weekly/zmirror-letsencrypt-renew.sh\", \"w\", encoding='utf-8') as fp:\n fp.write(cron_script)\n\n cmd('chmod +x /etc/cron.weekly/zmirror-letsencrypt-renew.sh')\n cmd('/etc/cron.weekly/zmirror-letsencrypt-renew.sh')\n\n # 重启一下apache\n print(\"Restarting apache2\")\n cmd('service apache2 restart')\n\nexcept:\n onekey_report('error', traceback_str=traceback.format_exc(), installing_mirror=mirrors_to_deploy)\n raise\n\nonekey_report('success', installing_mirror=mirrors_to_deploy)\n\n# ####### 完成 ########\nprint(\"Completed.\")\n# 最后打印一遍配置\nprint(\"------------ mirrors ------------\")\nfor mirror in mirrors_to_deploy:\n print(\"Mirror: {mirror} URL: https://{domain}/\".format(mirror=mirror, domain=mirrors_settings[mirror]['domain']))\n\nprint(\"\\nFor more information, please view zmirror's github: \", __ZMIRROR_PROJECT_URL__)\nprint(\"Contribution and Issues are more than welcomed.\")\nprint(\"btw, if you feeling good, I'll be grateful for your Star in github :)\")\n", "sub_path": "deploy.py", "file_name": "deploy.py", "file_ext": "py", "file_size_in_byte": 21716, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "sys.argv", "line_number": 25, "usage_type": "attribute"}, {"api_name": "subprocess.check_call", "line_number": 30, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 30, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 57, "usage_type": "call"}, {"api_name": "distro.info", "line_number": 57, "usage_type": "call"}, {"api_name": "re.search", "line_number": 70, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 84, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 97, "usage_type": "call"}, {"api_name": "logging.NOTSET", "line_number": 98, "usage_type": "attribute"}, {"api_name": "sys.platform", "line_number": 102, "usage_type": "attribute"}, {"api_name": "os.geteuid", "line_number": 105, "usage_type": "call"}, {"api_name": "urllib.parse.urljoin", "line_number": 125, "usage_type": "call"}, {"api_name": "urllib.parse.urljoin", "line_number": 130, "usage_type": "call"}, {"api_name": "urllib.parse.urljoin", "line_number": 135, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 178, "usage_type": "call"}, {"api_name": "distro.id", "line_number": 201, "usage_type": "call"}, {"api_name": "distro.id", "line_number": 207, "usage_type": "call"}, {"api_name": "distro.id", "line_number": 214, "usage_type": "call"}, {"api_name": "distro.version", "line_number": 214, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 230, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 232, "usage_type": "call"}, {"api_name": "os.path", "line_number": 232, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 246, "usage_type": "call"}, {"api_name": "traceback.format_exc", "line_number": 251, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 283, "usage_type": "call"}, {"api_name": "socket.gethostbyname", "line_number": 332, "usage_type": "call"}, {"api_name": "socket.gethostbyname", "line_number": 333, "usage_type": "call"}, {"api_name": "socket.gethostname", "line_number": 333, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 369, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 399, "usage_type": "call"}, {"api_name": "os.path", "line_number": 399, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 414, "usage_type": "call"}, {"api_name": "os.path", "line_number": 414, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 425, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 432, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 434, "usage_type": "call"}, {"api_name": "os.path", "line_number": 434, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 443, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 445, "usage_type": "call"}, {"api_name": "traceback.format_exc", "line_number": 445, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 450, "usage_type": "call"}, {"api_name": "os.path", "line_number": 450, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 453, "usage_type": "call"}, {"api_name": "os.path", "line_number": 453, "usage_type": "attribute"}, {"api_name": "shutil.copytree", "line_number": 463, "usage_type": "call"}, {"api_name": "shutil.chown", "line_number": 465, "usage_type": "call"}, {"api_name": "shutil.copy", "line_number": 470, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 470, "usage_type": "call"}, {"api_name": "os.path", "line_number": 470, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 471, "usage_type": "call"}, {"api_name": "os.path", "line_number": 471, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 473, "usage_type": "call"}, {"api_name": "os.path", "line_number": 473, "usage_type": "attribute"}, {"api_name": "re.sub", "line_number": 478, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 482, "usage_type": "call"}, {"api_name": "shutil.rmtree", "line_number": 491, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 497, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 499, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 505, "usage_type": "call"}, {"api_name": "os.path", "line_number": 505, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 507, "usage_type": "call"}, {"api_name": "os.path", "line_number": 507, "usage_type": "attribute"}, {"api_name": "requests.get", "line_number": 513, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 518, "usage_type": "call"}, {"api_name": "os.path", "line_number": 518, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 522, "usage_type": "call"}, {"api_name": "os.path", "line_number": 522, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 525, "usage_type": "call"}, {"api_name": "os.path", "line_number": 525, "usage_type": "attribute"}, {"api_name": "requests.get", "line_number": 531, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 538, "usage_type": "call"}, {"api_name": "os.path", "line_number": 538, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 546, "usage_type": "call"}, {"api_name": "os.path", "line_number": 546, "usage_type": "attribute"}, {"api_name": "traceback.format_exc", "line_number": 564, "usage_type": "call"}]}
+{"seq_id": "496885302", "text": "#\n# License: BSD\n# https://raw.github.com/robotics-in-concert/rocon_concert/license/LICENSE\n#\n##############################################################################\n# Imports\n##############################################################################\n\nimport yaml\nimport zlib # crc32\n\nimport genpy\nimport rospkg\nimport rocon_console.console as console\nimport rocon_python_utils\nimport rocon_interaction_msgs.msg as interaction_msgs\n\nfrom .exceptions import InvalidInteraction, MalformedInteractionsYaml, YamlResourceNotFoundException\n\n##############################################################################\n# Utility Methods\n##############################################################################\n\n\ndef generate_hash(name, role, namespace):\n '''\n Compute a unique hash for this interaction corresponding to the\n name-role-namespace triple. We use zlib's crc32 here instead of unique_id because\n of it's brevity which is important when trying to id a remocon app by its hash\n from an nfc tag.\n\n Might be worth checking here http://docs.python.org/2.7/library/zlib.html#zlib.crc32 if\n his doesn't produce the same hash on all platforms.\n\n :param name: the executable name of the interaction\n :type name: str\n :param role: the role the interaction is embedded in\n :type role: str\n :param namespace: the namespace in which to embed this interaction\n :type namespace: str\n '''\n return zlib.crc32(name + \"-\" + role + \"-\" + namespace)\n\n\ndef load_msgs_from_yaml_resource(resource_name):\n \"\"\"\n Load interactions from a yaml resource.\n\n :param resource_name: pkg/filename of a yaml formatted interactions file (ext=.interactions).\n :type resource_name: str\n\n :returns: a list of ros msg interaction specifications\n :rtype: concert_msgs.Interaction[]\n\n :raises: :exc:`rocon_interactions.YamlResourceNotFoundException,` if yaml is not found.\n :raises: :exc:`rocon_interactions.MalformedInteractionsYaml,` if yaml is malformed.\n \"\"\"\n interactions = []\n try:\n yaml_filename = rocon_python_utils.ros.find_resource_from_string(resource_name, extension='interactions')\n except rospkg.ResourceNotFound as e: # resource not found.\n raise YamlResourceNotFoundException(str(e))\n with open(yaml_filename) as f:\n # load the interactions from yaml into a python object\n interaction_yaml_objects = yaml.load(f)\n # now drop it into message format\n for interaction_yaml_object in interaction_yaml_objects:\n # convert the parameters from a freeform yaml variable to a yaml string suitable for\n # shipping off in ros msgs (where parameters is a string variable)\n if 'parameters' in interaction_yaml_object: # it's an optional key\n # chomp trailing newlines\n interaction_yaml_object['parameters'] = yaml.dump(interaction_yaml_object['parameters']).rstrip()\n interaction = interaction_msgs.Interaction()\n try:\n genpy.message.fill_message_args(interaction, interaction_yaml_object)\n except genpy.MessageException as e:\n raise MalformedInteractionsYaml(\n \"malformed yaml preventing converting of yaml to interaction msg type [%s]\" % str(e))\n interactions.append(interaction)\n return interactions\n\n##############################################################################\n# Classes\n##############################################################################\n\n\nclass Interaction(object):\n '''\n Defines an interaction. This wraps the base ros msg data structure with\n a few convenient management handles.\n '''\n __slots__ = [\n 'msg', # rocon_interaction_msgs.Interaction\n # aliases\n 'name',\n 'compatibility',\n 'namespace',\n 'display_name',\n 'role',\n 'hash',\n 'max',\n ]\n\n def __init__(self, msg):\n '''\n Validate the incoming fields and populate remaining fields with sane defaults.\n Also compute a unique hash for this object based on the incoming\n name-role-namespace triple.\n\n @param msg\n @type rocon_interaction_msgs.Interaction\n\n @raise exceptions.InvalidInteraction\n '''\n self.msg = msg\n if self.msg.max < -1:\n raise InvalidInteraction(\"maximum instance configuration cannot be negative [%s]\" % self.msg.display_name)\n if self.msg.max == 0:\n self.msg.max = 1\n if self.msg.role == '':\n raise InvalidInteraction(\"role not configured [%s]\" % self.msg.display_name)\n if self.msg.icon.resource_name == \"\":\n self.msg.icon.resource_name = 'rocon_bubble_icons/rocon.png'\n if not self.msg.icon.data:\n self.msg.icon = rocon_python_utils.ros.icon_resource_to_msg(self.msg.icon.resource_name)\n if self.msg.namespace == '':\n self.msg.namespace = '/'\n self.msg.hash = generate_hash(self.msg.name, self.msg.role, self.msg.namespace)\n # some convenient aliases\n self.role = self.msg.role\n self.name = self.msg.name\n self.namespace = self.msg.namespace\n self.display_name = self.msg.display_name\n self.hash = self.msg.hash\n self.compatibility = self.msg.compatibility\n self.max = self.msg.max\n\n def _eq__(self, other):\n if type(other) is type(self):\n return self.msg.hash == other.msg.hash\n else:\n return False\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __str__(self):\n '''\n Format the interaction into a human-readable string.\n '''\n s = ''\n s += console.green + \"%s\" % self.msg.display_name + console.reset + '\\n'\n s += console.cyan + \" Name\" + console.reset + \" : \" + console.yellow + \"%s\" % self.msg.name + console.reset + '\\n' # noqa\n s += console.cyan + \" Description\" + console.reset + \" : \" + console.yellow + \"%s\" % self.msg.description + console.reset + '\\n' # noqa\n s += console.cyan + \" Icon\" + console.reset + \" : \" + console.yellow + \"%s\" % str(self.msg.icon.resource_name) + console.reset + '\\n' # noqa\n s += console.cyan + \" Rocon URI\" + console.reset + \" : \" + console.yellow + \"%s\" % self.msg.compatibility + console.reset + '\\n' # noqa\n s += console.cyan + \" Namespace\" + console.reset + \" : \" + console.yellow + \"%s\" % self.msg.namespace + console.reset + '\\n' # noqa\n if self.msg.max == -1:\n s += console.cyan + \" Max\" + console.reset + \" : \" + console.yellow + \"infinity\" + console.reset + '\\n' # noqa\n else:\n s += console.cyan + \" Max\" + console.reset + \" : \" + console.yellow + \"%s\" % self.msg.max + console.reset + '\\n' # noqa\n already_prefixed = False\n for remapping in self.msg.remappings:\n if not already_prefixed:\n s += console.cyan + \" Remapping\" + console.reset + \" : \" + console.yellow + \"%s->%s\" % (remapping.remap_from, remapping.remap_to) + console.reset + '\\n' # noqa\n already_prefixed = True\n else:\n s += \" : \" + console.yellow + \"%s->%s\" % (remapping.remap_from, remapping.remap_to) + console.reset + '\\n' # noqa\n if self.msg.parameters != '':\n s += console.cyan + \" Parameters\" + console.reset + \" : \" + console.yellow + \"%s\" % self.msg.parameters + console.reset + '\\n' # noqa\n s += console.cyan + \" Hash\" + console.reset + \" : \" + console.yellow + \"%s\" % str(self.msg.hash) + console.reset + '\\n' # noqa\n return s\n", "sub_path": "rocon_interactions/src/rocon_interactions/interactions.py", "file_name": "interactions.py", "file_ext": "py", "file_size_in_byte": 7792, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "zlib.crc32", "line_number": 42, "usage_type": "call"}, {"api_name": "rocon_python_utils.ros.find_resource_from_string", "line_number": 60, "usage_type": "call"}, {"api_name": "rocon_python_utils.ros", "line_number": 60, "usage_type": "attribute"}, {"api_name": "rospkg.ResourceNotFound", "line_number": 61, "usage_type": "attribute"}, {"api_name": "exceptions.YamlResourceNotFoundException", "line_number": 62, "usage_type": "call"}, {"api_name": "yaml.load", "line_number": 65, "usage_type": "call"}, {"api_name": "yaml.dump", "line_number": 72, "usage_type": "call"}, {"api_name": "rocon_interaction_msgs.msg.Interaction", "line_number": 73, "usage_type": "call"}, {"api_name": "rocon_interaction_msgs.msg", "line_number": 73, "usage_type": "name"}, {"api_name": "genpy.message.fill_message_args", "line_number": 75, "usage_type": "call"}, {"api_name": "genpy.message", "line_number": 75, "usage_type": "attribute"}, {"api_name": "genpy.MessageException", "line_number": 76, "usage_type": "attribute"}, {"api_name": "exceptions.MalformedInteractionsYaml", "line_number": 77, "usage_type": "call"}, {"api_name": "exceptions.InvalidInteraction", "line_number": 117, "usage_type": "call"}, {"api_name": "exceptions.InvalidInteraction", "line_number": 121, "usage_type": "call"}, {"api_name": "rocon_python_utils.ros.icon_resource_to_msg", "line_number": 125, "usage_type": "call"}, {"api_name": "rocon_python_utils.ros", "line_number": 125, "usage_type": "attribute"}, {"api_name": "rocon_console.console.green", "line_number": 152, "usage_type": "attribute"}, {"api_name": "rocon_console.console", "line_number": 152, "usage_type": "name"}, {"api_name": "rocon_console.console.reset", "line_number": 152, "usage_type": "attribute"}, {"api_name": "rocon_console.console.cyan", "line_number": 153, "usage_type": "attribute"}, {"api_name": "rocon_console.console", "line_number": 153, "usage_type": "name"}, {"api_name": "rocon_console.console.reset", "line_number": 153, "usage_type": "attribute"}, {"api_name": "rocon_console.console.yellow", "line_number": 153, "usage_type": "attribute"}, {"api_name": "rocon_console.console.cyan", "line_number": 154, "usage_type": "attribute"}, {"api_name": "rocon_console.console", "line_number": 154, "usage_type": "name"}, {"api_name": "rocon_console.console.reset", "line_number": 154, "usage_type": "attribute"}, {"api_name": "rocon_console.console.yellow", "line_number": 154, "usage_type": "attribute"}, {"api_name": "rocon_console.console.cyan", "line_number": 155, "usage_type": "attribute"}, {"api_name": "rocon_console.console", "line_number": 155, "usage_type": "name"}, {"api_name": "rocon_console.console.reset", "line_number": 155, "usage_type": "attribute"}, {"api_name": "rocon_console.console.yellow", "line_number": 155, "usage_type": "attribute"}, {"api_name": "rocon_console.console.cyan", "line_number": 156, "usage_type": "attribute"}, {"api_name": "rocon_console.console", "line_number": 156, "usage_type": "name"}, {"api_name": "rocon_console.console.reset", "line_number": 156, "usage_type": "attribute"}, {"api_name": "rocon_console.console.yellow", "line_number": 156, "usage_type": "attribute"}, {"api_name": "rocon_console.console.cyan", "line_number": 157, "usage_type": "attribute"}, {"api_name": "rocon_console.console", "line_number": 157, "usage_type": "name"}, {"api_name": "rocon_console.console.reset", "line_number": 157, "usage_type": "attribute"}, {"api_name": "rocon_console.console.yellow", "line_number": 157, "usage_type": "attribute"}, {"api_name": "rocon_console.console.cyan", "line_number": 159, "usage_type": "attribute"}, {"api_name": "rocon_console.console", "line_number": 159, "usage_type": "name"}, {"api_name": "rocon_console.console.reset", "line_number": 159, "usage_type": "attribute"}, {"api_name": "rocon_console.console.yellow", "line_number": 159, "usage_type": "attribute"}, {"api_name": "rocon_console.console.cyan", "line_number": 161, "usage_type": "attribute"}, {"api_name": "rocon_console.console", "line_number": 161, "usage_type": "name"}, {"api_name": "rocon_console.console.reset", "line_number": 161, "usage_type": "attribute"}, {"api_name": "rocon_console.console.yellow", "line_number": 161, "usage_type": "attribute"}, {"api_name": "rocon_console.console.cyan", "line_number": 165, "usage_type": "attribute"}, {"api_name": "rocon_console.console", "line_number": 165, "usage_type": "name"}, {"api_name": "rocon_console.console.reset", "line_number": 165, "usage_type": "attribute"}, {"api_name": "rocon_console.console.yellow", "line_number": 165, "usage_type": "attribute"}, {"api_name": "rocon_console.console.yellow", "line_number": 168, "usage_type": "attribute"}, {"api_name": "rocon_console.console", "line_number": 168, "usage_type": "name"}, {"api_name": "rocon_console.console.reset", "line_number": 168, "usage_type": "attribute"}, {"api_name": "rocon_console.console.cyan", "line_number": 170, "usage_type": "attribute"}, {"api_name": "rocon_console.console", "line_number": 170, "usage_type": "name"}, {"api_name": "rocon_console.console.reset", "line_number": 170, "usage_type": "attribute"}, {"api_name": "rocon_console.console.yellow", "line_number": 170, "usage_type": "attribute"}, {"api_name": "rocon_console.console.cyan", "line_number": 171, "usage_type": "attribute"}, {"api_name": "rocon_console.console", "line_number": 171, "usage_type": "name"}, {"api_name": "rocon_console.console.reset", "line_number": 171, "usage_type": "attribute"}, {"api_name": "rocon_console.console.yellow", "line_number": 171, "usage_type": "attribute"}]}
+{"seq_id": "575721209", "text": "\"\"\"\n 14강. 이미지 Gradient를 이용한 경계 찾기\n\n 이미지 gradient(이미지 경사도 혹은 수학적인 용어로 이미지의 변화율)를 이용한 에지(경계선)를 찾는 방법에 대해 알아 보겠습니다.\n OpenCV는 Sobel, Scharr, Laplacian 이 세가지 타입의 Gradient 필터(High-pass filters;HPF)를 제공합니다.\n Sobel, Scharr 미분 (Sobel and Sharr Derivatives)\n Sobel 오퍼레이터는 가우스 스무딩(Gaussian Smoothing)과 미분연산을 결합한 형태의 연산을 수행함으로써 노이즈에 보다 강력한 저항성을 제공합니다.\n Sobel 오퍼레이션은 세로 방향 또는 가로 방향으로 연산 수행이 가능합니다. cv2.Sobel() 함수는 이미지에 sobel 연산을 수행하는 함수입니다.\n\n cv2.Sobel(src, ddepth, dx, dy, ksize)\n src: Sobel 미분을 적용할 원본 이미지\n ddepth: 결과 이미지 데이터 타입\n CV_8U: 이미지 픽셀값을 uint8 로 설정\n CV_16U: 이미지 픽셀값을 uint16으로 설정\n CV_32F: 이미지 픽셀값을 float32로 설정\n CV_64F: 이미지 픽셀값ㅇ르 float64로 설정\n dx, dy: 각각 x방향, y방향으로 미분 차수 (eg. 1, 0 이면, x 방향으로 1차 미분 수행, y 방향으로 그대로 두라는 의미)\n ksize: 확장 Sobel 커널의 크기. 1, 3, 5, 7 중 하나의 값으로 설정. -1로 설정되면 3x3 Soble 필터 대신 3x3 Scharr 필터를 적용하게 됨\n\n\"\"\"\n\nimport numpy as np\nimport cv2 as cv2\nimport matplotlib.pyplot as plt\nimport default_import as selImg\n#from default_import import select_img as selImg\n#img = cv2.imread(selImg.select_img(6), cv2.IMREAD_GRAYSCALE)\n\n\ndef grad():\n img = cv2.imread(selImg.select_img(6), cv2.IMREAD_GRAYSCALE)\n #img = cv2.imread(select_img('2'), cv2.IMREAD_GRAYSCALE)\n\n laplacian = cv2.Laplacian(img, cv2.CV_64F)\n sobelx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize = 3)\n sobely = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize = 3)\n\n plt.subplot(2, 2, 1), plt.imshow(img, cmap = 'gray')\n plt.title('orignal'), plt.xticks([]), plt.yticks([])\n\n plt.subplot(2, 2, 2), plt.imshow(laplacian, cmap = 'gray')\n plt.title('Laplacian'), plt.xticks([]), plt.yticks([])\n\n plt.subplot(2, 2, 3), plt.imshow(sobelx, cmap = 'gray')\n plt.title('sobel X'), plt.xticks([]), plt.yticks([])\n\n plt.subplot(2, 2, 4), plt.imshow(sobely, cmap = 'gray')\n plt.title('sobel Y'), plt.xticks([]), plt.yticks([])\n\n plt.show()\n\ngrad()\n\n\n\n", "sub_path": "OpenCV/gradient.py", "file_name": "gradient.py", "file_ext": "py", "file_size_in_byte": 2656, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "cv2.imread", "line_number": 31, "usage_type": "call"}, {"api_name": "default_import.select_img", "line_number": 31, "usage_type": "call"}, {"api_name": "cv2.IMREAD_GRAYSCALE", "line_number": 31, "usage_type": "attribute"}, {"api_name": "cv2.Laplacian", "line_number": 34, "usage_type": "call"}, {"api_name": "cv2.CV_64F", "line_number": 34, "usage_type": "attribute"}, {"api_name": "cv2.Sobel", "line_number": 35, "usage_type": "call"}, {"api_name": "cv2.CV_64F", "line_number": 35, "usage_type": "attribute"}, {"api_name": "cv2.Sobel", "line_number": 36, "usage_type": "call"}, {"api_name": "cv2.CV_64F", "line_number": 36, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 38, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 41, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 41, "usage_type": "call"}, {"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.xticks", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 44, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 44, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 44, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 45, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 47, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 48, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 48, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 48, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 48, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 50, "usage_type": "name"}]}
+{"seq_id": "266825334", "text": "# Copyright 2013 - Mirantis, Inc.\n# Copyright 2016 - Brocade Communications Systems, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom oslo_log import log as logging\nfrom osprofiler import profiler\n\nfrom mistral.actions import action_factory as a_f\nfrom mistral.engine import base\nfrom mistral.engine.rpc_backend import rpc\nfrom mistral import exceptions as exc\nfrom mistral.utils import inspect_utils as i_u\nfrom mistral.workflow import utils as wf_utils\n\n\nLOG = logging.getLogger(__name__)\n\n\nclass DefaultExecutor(base.Executor):\n def __init__(self):\n self._engine_client = rpc.get_engine_client()\n\n @profiler.trace('executor-run-action', hide_args=True)\n def run_action(self, action_ex_id, action_class_str, attributes,\n action_params, safe_rerun, redelivered=False):\n \"\"\"Runs action.\n\n :param action_ex_id: Action execution id.\n :param action_class_str: Path to action class in dot notation.\n :param attributes: Attributes of action class which will be set to.\n :param action_params: Action parameters.\n :param safe_rerun: Tells if given action can be safely rerun.\n :param redelivered: Tells if given action was run before on another\n executor.\n \"\"\"\n\n def send_error_back(error_msg):\n error_result = wf_utils.Result(error=error_msg)\n\n if action_ex_id:\n self._engine_client.on_action_complete(\n action_ex_id,\n error_result\n )\n\n return None\n\n return error_result\n\n if redelivered and not safe_rerun:\n msg = (\n \"Request to run action %s was redelivered, but action %s\"\n \" cannot be re-run safely. The only safe thing to do is fail\"\n \" action.\"\n % (action_class_str, action_class_str)\n )\n\n return send_error_back(msg)\n\n action_cls = a_f.construct_action_class(action_class_str, attributes)\n\n # Instantiate action.\n\n try:\n action = action_cls(**action_params)\n except Exception as e:\n msg = (\"Failed to initialize action %s. Action init params = %s.\"\n \" Actual init params = %s. More info: %s\"\n % (action_class_str, i_u.get_arg_list(action_cls.__init__),\n action_params.keys(), e))\n LOG.warning(msg)\n\n return send_error_back(msg)\n\n # Run action.\n\n try:\n result = action.run()\n\n # Note: it's made for backwards compatibility with already\n # existing Mistral actions which don't return result as\n # instance of workflow.utils.Result.\n if not isinstance(result, wf_utils.Result):\n result = wf_utils.Result(data=result)\n\n except Exception as e:\n msg = (\"Failed to run action [action_ex_id=%s, action_cls='%s',\"\n \" attributes='%s', params='%s']\\n %s\"\n % (action_ex_id, action_cls, attributes, action_params, e))\n LOG.exception(msg)\n\n return send_error_back(msg)\n\n # Send action result.\n\n try:\n if action_ex_id and (action.is_sync() or result.is_error()):\n self._engine_client.on_action_complete(\n action_ex_id,\n result,\n async_=True\n )\n\n except exc.MistralException as e:\n # In case of a Mistral exception we can try to send error info to\n # engine because most likely it's not related to the infrastructure\n # such as message bus or network. One known case is when the action\n # returns a bad result (e.g. invalid unicode) which can't be\n # serialized.\n msg = (\"Failed to call engine's on_action_complete() method due\"\n \" to a Mistral exception\"\n \" [action_ex_id=%s, action_cls='%s',\"\n \" attributes='%s', params='%s']\\n %s\"\n % (action_ex_id, action_cls, attributes, action_params, e))\n LOG.exception(msg)\n\n return send_error_back(msg)\n except Exception as e:\n # If it's not a Mistral exception all we can do is only\n # log the error.\n msg = (\"Failed to call engine's on_action_complete() method due\"\n \" to an unexpected exception\"\n \" [action_ex_id=%s, action_cls='%s',\"\n \" attributes='%s', params='%s']\\n %s\"\n % (action_ex_id, action_cls, attributes, action_params, e))\n LOG.exception(msg)\n\n return result\n", "sub_path": "mistral-4.0.2/mistral/engine/default_executor.py", "file_name": "default_executor.py", "file_ext": "py", "file_size_in_byte": 5258, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "oslo_log.log.getLogger", "line_number": 27, "usage_type": "call"}, {"api_name": "oslo_log.log", "line_number": 27, "usage_type": "name"}, {"api_name": "mistral.engine.base.Executor", "line_number": 30, "usage_type": "attribute"}, {"api_name": "mistral.engine.base", "line_number": 30, "usage_type": "name"}, {"api_name": "mistral.engine.rpc_backend.rpc.get_engine_client", "line_number": 32, "usage_type": "call"}, {"api_name": "mistral.engine.rpc_backend.rpc", "line_number": 32, "usage_type": "name"}, {"api_name": "mistral.workflow.utils.Result", "line_number": 49, "usage_type": "call"}, {"api_name": "mistral.workflow.utils", "line_number": 49, "usage_type": "name"}, {"api_name": "mistral.actions.action_factory.construct_action_class", "line_number": 71, "usage_type": "call"}, {"api_name": "mistral.actions.action_factory", "line_number": 71, "usage_type": "name"}, {"api_name": "mistral.utils.inspect_utils.get_arg_list", "line_number": 80, "usage_type": "call"}, {"api_name": "mistral.utils.inspect_utils", "line_number": 80, "usage_type": "name"}, {"api_name": "mistral.workflow.utils.Result", "line_number": 94, "usage_type": "attribute"}, {"api_name": "mistral.workflow.utils", "line_number": 94, "usage_type": "name"}, {"api_name": "mistral.workflow.utils.Result", "line_number": 95, "usage_type": "call"}, {"api_name": "mistral.workflow.utils", "line_number": 95, "usage_type": "name"}, {"api_name": "mistral.exceptions.MistralException", "line_number": 115, "usage_type": "attribute"}, {"api_name": "mistral.exceptions", "line_number": 115, "usage_type": "name"}, {"api_name": "osprofiler.profiler.trace", "line_number": 34, "usage_type": "call"}, {"api_name": "osprofiler.profiler", "line_number": 34, "usage_type": "name"}]}
+{"seq_id": "213680437", "text": "# Q14: write a Python program to find the factorial of a number provided by the user\nfrom functools import reduce\n\n\ndef input_positive_integer(msg):\n try:\n num = int(input(msg).strip())\n except ValueError:\n print(\"Please input positive integers only!\")\n num = int(input(msg))\n if num < 0:\n print(\"Please input positive integers only!\")\n num = int(input(msg))\n return num\n\n\ndef factorial():\n num = input_positive_integer(\"Please enter a positive integer: \")\n print(\"%d! = \"% num, int(reduce(lambda x, y: x * y, range(1, num + 1))))\n\n\nfactorial()\n", "sub_path": "Python/Assignment4/question14.py", "file_name": "question14.py", "file_ext": "py", "file_size_in_byte": 598, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "functools.reduce", "line_number": 19, "usage_type": "call"}]}
+{"seq_id": "56624966", "text": "import os\nfrom itertools import product\nimport numpy as np\nimport math\nfrom pymatgen.io.cif import CifWriter\nfrom ase.build import general_surface\nfrom ase.spacegroup import crystal\nfrom ase.visualize import view\nfrom ase.lattice.surface import *\nfrom ase.io import *\nimport pymatgen as mg\nfrom pymatgen.io.vasp.inputs import Poscar\nimport argparse\nimport pymatgen as mg\nfrom pymatgen.core.structure import Structure\nfrom pymatgen.io.vasp.inputs import Poscar\nfrom pymatgen.analysis.structure_matcher import StructureMatcher\nfrom pymatgen.core.surface import Slab, SlabGenerator, ReconstructionGenerator\nfrom pymatgen.analysis.substrate_analyzer import SubstrateAnalyzer, ZSLGenerator\nfrom core.utils.utils import *\n\ndef get_equiv_transformations_Sam(self, transformation_sets, film_vectors,\n substrate_vectors):\n # Monkey-patching the original function of pymatgen to generate the transformation matrices\n\n text_file = open(self.working_dir + \"film_sub_sets\", \"w\")\n film_sub_sets = []\n for (film_transformations, substrate_transformations) in \\\n transformation_sets:\n\n # Apply transformations and reduce using Zur reduce methodology\n films = [reduce_vectors(*np.dot(f, film_vectors))\n for f in film_transformations]\n Sam_films = []\n for i in films:\n Sam_films.append(mat_clean(i))\n\n substrates = [reduce_vectors(*np.dot(s, substrate_vectors))\n for s in substrate_transformations]\n\n sam_substrates = []\n for i in substrates:\n sam_substrates.append(mat_clean(i))\n # Check if equivelant super lattices\n\n for f, s in product(films, substrates):\n if self.is_same_vectors(f, s):\n f_index = Sam_films.index(mat_clean(f))\n s_index = sam_substrates.index(mat_clean(s))\n\n print([film_transformations[f_index].tolist(), substrate_transformations[s_index].tolist()],\n file=text_file)\n\n film_sub_sets.append(\n [film_transformations[f_index].tolist(), substrate_transformations[s_index].tolist()])\n yield [f, s]\n\n text_file.close()\n\n\ndef Interface_generator(Ini_sub_slab, Ini_film_slab, sub_tr_mat, film_tr_mat, distance, fparam):\n\n raw_ini_sub_slab_mat = np.array(Ini_sub_slab.lattice.matrix)\n raw_ini_film_slab_mat = np.array(Ini_film_slab.lattice.matrix)\n sub_reduction = reduce_vectors(\n raw_ini_sub_slab_mat[0], raw_ini_sub_slab_mat[1])\n film_reduction = reduce_vectors(\n raw_ini_film_slab_mat[0], raw_ini_film_slab_mat[1])\n reduced_sub_mat = np.array(\n [sub_reduction[0], sub_reduction[1], raw_ini_sub_slab_mat[2]])\n reduced_film_mat = np.array(\n [film_reduction[0], film_reduction[1], raw_ini_film_slab_mat[2]])\n red_Ini_sub_slab = Structure(mg.Lattice(reduced_sub_mat), Ini_sub_slab.species, Ini_sub_slab.cart_coords,\n coords_are_cartesian=True)\n red_Ini_film_slab = Structure(mg.Lattice(reduced_film_mat), Ini_film_slab.species, Ini_film_slab.cart_coords,\n coords_are_cartesian=True)\n red_Ini_sub_slab.make_supercell(scaling_matrix=scale_mat(sub_tr_mat))\n red_Ini_film_slab.make_supercell(scaling_matrix=scale_mat(film_tr_mat))\n Ini_sub_mat = red_Ini_sub_slab.lattice.matrix\n Ini_film_mat = red_Ini_film_slab.lattice.matrix\n sub_r_vecs = reduce_vectors(Ini_sub_mat[0], Ini_sub_mat[1])\n film_r_vecs = reduce_vectors(Ini_film_mat[0], Ini_film_mat[1])\n sub_mat = np.array([sub_r_vecs[0], sub_r_vecs[1], Ini_sub_mat[2]])\n film_mat = np.array([film_r_vecs[0], film_r_vecs[1], Ini_film_mat[2]])\n modif_sub_struc = mg.Structure(mg.Lattice(sub_mat), red_Ini_sub_slab.species, red_Ini_sub_slab.cart_coords,\n coords_are_cartesian=True)\n modif_film_struc = mg.Structure(mg.Lattice(film_mat), red_Ini_film_slab.species, red_Ini_film_slab.cart_coords,\n coords_are_cartesian=True)\n sub_sl_vecs = [modif_sub_struc.lattice.matrix[0],\n modif_sub_struc.lattice.matrix[1]]\n film_sl_vecs = [modif_film_struc.lattice.matrix[0],\n modif_film_struc.lattice.matrix[1]]\n film_angel = angle(film_sl_vecs[0], film_sl_vecs[1])\n sub_angel = angle(sub_sl_vecs[0], sub_sl_vecs[1])\n u_size = fparam * \\\n (np.linalg.norm(sub_sl_vecs[0])) + (1 -\n fparam) * (np.linalg.norm(film_sl_vecs[0]))\n v_size = fparam * \\\n (np.linalg.norm(sub_sl_vecs[1])) + (1 -\n fparam) * (np.linalg.norm(film_sl_vecs[1]))\n mean_angle = fparam * sub_angel + (1 - fparam) * film_angel\n sub_rot_mat = [[u_size, 0, 0], [v_size * math.cos(mean_angle), v_size * math.sin(mean_angle), 0],\n [0, 0, np.linalg.norm(modif_sub_struc.lattice.matrix[2])]]\n film_rot_mat = [[u_size, 0, 0], [v_size * math.cos(mean_angle), v_size * math.sin(mean_angle), 0],\n [0, 0, -np.linalg.norm(modif_film_struc.lattice.matrix[2])]]\n film_normal = np.cross(film_sl_vecs[0], film_sl_vecs[1])\n sub_normal = np.cross(sub_sl_vecs[0], sub_sl_vecs[1])\n film_un = film_normal / np.linalg.norm(film_normal)\n sub_un = sub_normal / np.linalg.norm(sub_normal)\n film_sl_vecs.append(film_un)\n L1_mat = np.transpose(film_sl_vecs)\n L1_res = [[u_size, v_size * math.cos(mean_angle), 0],\n [0, v_size * math.sin(mean_angle), 0], [0, 0, 1]]\n L1_mat_inv = np.linalg.inv(L1_mat)\n L1 = np.matmul(L1_res, L1_mat_inv)\n sub_sl_vecs.append(sub_un)\n L2_mat = np.transpose(sub_sl_vecs)\n L2_res = [[u_size, v_size * math.cos(mean_angle), 0],\n [0, v_size * math.sin(mean_angle), 0], [0, 0, -1]]\n L2_mat_inv = np.linalg.inv(L2_mat)\n L2 = np.matmul(L2_res, L2_mat_inv)\n sub_rot_lattice = mg.Lattice(sub_rot_mat)\n film_rot_lattice = mg.Lattice(film_rot_mat)\n r_sub_coords = np.array(modif_sub_struc.cart_coords)\n r_film_coords = np.array(modif_film_struc.cart_coords)\n\n for ii in range(len(r_sub_coords)):\n r_sub_coords[ii] = np.matmul(L2, r_sub_coords[ii])\n for ii in range(len(r_film_coords)):\n r_film_coords[ii] = np.matmul(L1, r_film_coords[ii])\n\n sub_slab = mg.Structure(\n sub_rot_lattice, modif_sub_struc.species, r_sub_coords, coords_are_cartesian=True)\n film_slab = mg.Structure(\n film_rot_lattice, modif_film_struc.species, r_film_coords, coords_are_cartesian=True)\n # SP_text = open(working_dir+ \"SP_typ\" , \"w\")\n sub_sp_num = len(sub_slab.types_of_specie)\n film_sp_num = len(film_slab.types_of_specie)\n # SP_text.close()\n sub_slab_mat = np.array(sub_slab.lattice.matrix)\n film_slab_mat = np.array(film_slab.lattice.matrix)\n sub_slab_coords = sub_slab.cart_coords\n film_slab_coords = film_slab.cart_coords\n sub_slab_zmat = sub_slab_coords[:, [2]]\n film_slab_zmat = film_slab_coords[:, [2]]\n sub_slab_zmat = sub_slab_zmat - min(sub_slab_zmat)\n film_slab_zmat = film_slab_zmat - min(film_slab_zmat)\n sub_max_z = max(sub_slab_zmat)\n sub_min_z = min(sub_slab_zmat)\n modif_film_slab_zmat = film_slab_zmat + sub_max_z - sub_min_z + distance\n film_slab_coords[:, [2]] = modif_film_slab_zmat\n sub_slab_coords[:, [2]] = sub_slab_zmat\n\n sub_max_z = max(sub_slab_zmat)\n film_min_z = min(modif_film_slab_zmat)\n sub_max_list = coords_sperator(sub_slab_zmat, sub_sp_num, True)\n film_min_list = coords_sperator(modif_film_slab_zmat, film_sp_num, False)\n\n interface_coords = np.concatenate(\n (sub_slab_coords, film_slab_coords), axis=0)\n interface_species = sub_slab.species + film_slab.species\n interface_latt = sub_slab_mat\n interface_latt[2][2] = abs(sub_slab_mat[2][2]) + \\\n abs(film_slab_mat[2][2]) + distance\n\n Adding_val = 0.5 * (interface_latt[2][2] - max(interface_coords[:, [2]]))\n sub_max_list += Adding_val\n film_min_list += Adding_val\n sub_max_z += Adding_val\n film_min_z += Adding_val\n\n interface_coords[:, [2]] += 0.5 * \\\n (interface_latt[2][2] - max(interface_coords[:, [2]]))\n sub_slab_coords[:, [2]] += Adding_val\n film_slab_coords[:, [2]] += Adding_val\n # sub_slab_coords[:, [2]] += 0.5 * \\\n # (interface_latt[2][2] - max(sub_slab_coords[:, [2]]))\n # film_slab_coords[:, [2]] += 0.5 * \\\n # (interface_latt[2][2] - max(film_slab_coords[:, [2]]))\n interface_lattice = mg.Lattice(interface_latt)\n interface_struc = mg.Structure(\n interface_lattice, interface_species, interface_coords, coords_are_cartesian=True)\n interface_struc = interface_struc.get_reduced_structure()\n # Poscar(interface_struc.get_reduced_structure()).write_file(working_dir + \"POSCAR_interface\", direct=False )\n\n ###################\n # Seperate the first two layers\n\n surf_int_species = []\n surf_int_coords = []\n\n for k in range(len(interface_coords)):\n for k1 in sub_max_list:\n if (round(interface_coords[k, 2], 8) == round(k1[0], 8)):\n surf_int_coords.append(interface_coords[k, :])\n surf_int_species.append(interface_species[k])\n for k2 in film_min_list:\n if (round(interface_coords[k, 2], 8) == round(k2[0], 8)):\n surf_int_coords.append(interface_coords[k, :])\n surf_int_species.append(interface_species[k])\n\n surf_int_coords = np.array(surf_int_coords)\n surf_int_coords[:, 2] -= min(surf_int_coords[:, 2])\n surf_int_lat = np.array([interface_latt[0], interface_latt[1], [\n 0, 0, 15*max(surf_int_coords[:, 2])]])\n surf_int_coords[:, 2] += 7 * max(surf_int_coords[:, 2])\n surf_struc = Structure(surf_int_lat, surf_int_species,\n surf_int_coords, coords_are_cartesian=True)\n # surf_cif = CifWriter(surf_struc)\n # surf_cif.write_file(working_dir+\"surf.cif\")\n surf_struc = surf_struc.get_reduced_structure()\n # Poscar(surf_struc.get_reduced_structure()).write_file(working_dir + \"POSCAR_Surf_int\", direct = False)\n\n return [interface_struc, surf_struc, sub_slab_coords, film_slab_coords]", "sub_path": "core/interface_generator.py", "file_name": "interface_generator.py", "file_ext": "py", "file_size_in_byte": 10240, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "numpy.dot", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 38, "usage_type": "call"}, {"api_name": "itertools.product", "line_number": 46, "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": 69, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 71, "usage_type": "call"}, {"api_name": "pymatgen.core.structure.Structure", "line_number": 73, "usage_type": "call"}, {"api_name": "pymatgen.Lattice", "line_number": 73, "usage_type": "call"}, {"api_name": "pymatgen.core.structure.Structure", "line_number": 75, "usage_type": "call"}, {"api_name": "pymatgen.Lattice", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 84, "usage_type": "call"}, {"api_name": "pymatgen.Structure", "line_number": 85, "usage_type": "call"}, {"api_name": "pymatgen.Lattice", "line_number": 85, "usage_type": "call"}, {"api_name": "pymatgen.Structure", "line_number": 87, "usage_type": "call"}, {"api_name": "pymatgen.Lattice", "line_number": 87, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 96, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 96, "usage_type": "attribute"}, {"api_name": "numpy.linalg.norm", "line_number": 97, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 97, "usage_type": "attribute"}, {"api_name": "numpy.linalg.norm", "line_number": 99, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 99, "usage_type": "attribute"}, {"api_name": "numpy.linalg.norm", "line_number": 100, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 100, "usage_type": "attribute"}, {"api_name": "math.cos", "line_number": 102, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 102, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 103, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 103, "usage_type": "attribute"}, {"api_name": "math.cos", "line_number": 104, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 105, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 105, "usage_type": "attribute"}, {"api_name": "numpy.cross", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.cross", "line_number": 107, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 108, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 108, "usage_type": "attribute"}, {"api_name": "numpy.linalg.norm", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 109, "usage_type": "attribute"}, {"api_name": "numpy.transpose", "line_number": 111, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 112, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 113, "usage_type": "call"}, {"api_name": "numpy.linalg.inv", "line_number": 114, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 114, "usage_type": "attribute"}, {"api_name": "numpy.matmul", "line_number": 115, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 117, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 118, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 119, "usage_type": "call"}, {"api_name": "numpy.linalg.inv", "line_number": 120, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 120, "usage_type": "attribute"}, {"api_name": "numpy.matmul", "line_number": 121, "usage_type": "call"}, {"api_name": "pymatgen.Lattice", "line_number": 122, "usage_type": "call"}, {"api_name": "pymatgen.Lattice", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 124, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 125, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 130, "usage_type": "call"}, {"api_name": "pymatgen.Structure", "line_number": 132, "usage_type": "call"}, {"api_name": "pymatgen.Structure", "line_number": 134, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 140, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 141, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 159, "usage_type": "call"}, {"api_name": "pymatgen.Lattice", "line_number": 180, "usage_type": "call"}, {"api_name": "pymatgen.Structure", "line_number": 181, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 202, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 204, "usage_type": "call"}, {"api_name": "pymatgen.core.structure.Structure", "line_number": 207, "usage_type": "call"}]}
+{"seq_id": "384162084", "text": "import select, socket, queue as Queue\nimport chat_utils as chat_utils\nfrom colorama import Fore, Style\n\n#This class implements the downgrade attack which Trudy does by blocking the chat_STARTTLS messages between Alice and Bob.\n\nclass Downgrade_Server:\n #Setting up the downgrade server with IP address and port 8000.\n def __init__(self, self_ip, server_ip, client_ip):\n self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.server.bind((self_ip, 8000))\n self.server.listen(5)\n print(Fore.GREEN + Style.BRIGHT + 'Server up and running! Waiting for connections...\\n')\n\n #Intercepting connections from the client to server.\n connection, client_address = self.server.accept()\n new_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n #Connecting to the server to now establish an indirect link between a client and server\n new_socket.connect((server_ip, 8000))\n print(Fore.CYAN + Style.BRIGHT + \"Intercepting messages...\\n\")\n # Setting the connection to non blocking, so that the Trudy can send and recieve messages whenever.\n self.server.setblocking(0)\n new_socket.setblocking(0)\n self.start_downgrade(connection, new_socket)\n\n def start_downgrade(self, client_side, server_side):\n #Setting up the client side and server side of the downgrade server\n self.client_side = client_side\n self.server_side = server_side\n # The list of input streams present.\n self.inputs = [client_side, server_side]\n # The list of entities with pending outgoing messages.\n self.outputs = []\n # message queues for the pending outgoing messages.\n self.message_queues = {}\n # A message queue for the pending outgoing messages to the client.\n self.message_queues[client_side] = Queue.Queue()\n # A message queue for the pending outgoing messages to the server.\n self.message_queues[server_side] = Queue.Queue()\n # Lists to contain the received fragments of a message untill all of its fragments have arrived.\n self.fragment_lists = {}\n # A list to contain the received fragments of a message untill all of its fragments have arrived on the client side.\n self.fragment_lists[client_side] = []\n # A list to contain the received fragments of a message untill all of its fragments have arrived on the server side.\n self.fragment_lists[server_side] = []\n # The number of messages sent so far.\n self.received_message_numbers = {}\n self.received_message_numbers[client_side] = 0\n self.received_message_numbers[server_side] = 0\n self.lastline_type = client_side\n # Now running a loop for as long as the connection between the server and client exists.\n while len(self.inputs) > 1:\n # Using the select library to filter the inputs and outputs list and obtain from them the entities that are ready for IO.\n readable, writable, exceptional = select.select(self.inputs, self.outputs, self.inputs)\n # Iterating over all the entities that have pending messages to be read\n for s in readable:\n incoming_msg = s.recv(4096).decode('UTF-8')\n # If the entity is the client, then there is an incoming message from the client to the server.\n if s is client_side:\n #If the incoming message from client is to establish TLS connection,downgrade server responds with CHAT_STARTTLS_NOT_SUPPORTED.\n #This message is not sent to the server so server assumes that the client doesn't wish to use TLS protocol.\n if incoming_msg == chat_utils.CHAT_STARTTLS:\n # Adding the server to the outputs list, implying that there are pending messages to be sent to the server.\n if client_side not in self.outputs:\n self.outputs.append(client_side)\n response = chat_utils.CHAT_STARTTLS_NOT_SUPPORTED\n self.message_queues[client_side].put(response)\n # Other incoming messages thus read are enqueued into the message queue, implying that it has to be sent to the server.\n else:\n self.message_queues[server_side].put(incoming_msg)\n if server_side not in self.outputs:\n # Adding the server to the outputs list, implying that there are pending messages to be sent to the server.\n self.outputs.append(server_side)\n if chat_utils.CHAT_MESSAGE in incoming_msg:\n self.handle_new_message(s, incoming_msg)\n # If the entity is the server, then there is an incoming message from the server to the client.\n else:\n # The message thus read is enqueued into the message queue, implying that it has to be sent to the client.\n self.message_queues[client_side].put(incoming_msg)\n # Adding the client to the outputs list, implying that there are pending messages to be sent to the client.\n if client_side not in self.outputs:\n self.outputs.append(client_side)\n if chat_utils.CHAT_MESSAGE in incoming_msg:\n self.handle_new_message(s, incoming_msg)\n\n # Now iterating over the list of entities that have pending messages to be written to.\n for s in writable:\n try:\n next_msg = self.message_queues[s].get_nowait()\n except Queue.Empty:\n self.outputs.remove(s)\n else:\n # If the user types CHAT_CLOSE, it means that he intends to close the connection.\n if next_msg == chat_utils.CHAT_CLOSE:\n person = 'Bob'\n if s is server_side:\n person = 'Alice'\n print(Fore.RED + Style.BRIGHT + '\\n' + person +' closed the connection!', Style.RESET_ALL+'\\n')\n s.send(next_msg.encode('UTF-8'))\n self.close_connection(s)\n break\n else:\n # If the message is not CHAT_CLOSE, then in accordance with the protocol,the message is sent.\n s.send(next_msg.encode('UTF-8'))\n # Iterating over the list of entities that have thrown an exception.\n for s in exceptional:\n self.close_connection(s)\n\n # This function handles the messages received from the user.\n def handle_new_message(self, s, data):\n # First the details of the message like the message number, number of fragments and the fragment number are obtained.\n msg_num, num_fragments, fragment_num = chat_utils.get_message_details(data)\n # if the message number is not equal to the number of messages received yet, it implies that this is a new message.\n if self.received_message_numbers[s] != msg_num:\n self.received_message_numbers[s] = msg_num\n # If the new message has only one fragment, then we just print it.\n if num_fragments == 1:\n self.print_message(s, data[28:])\n # If it has more than one fragment then we append it into the fragment list.\n else:\n self.fragment_lists[s].append(data)\n # If the message received is not an entirely new message but a fragment of a message,\n else:\n # If the fragment received is indeed the last fragment, then we can parse all the received fragments, reconstruct the message and display it.\n if num_fragments == fragment_num:\n self.fragment_lists[s].append(data)\n received_msg = chat_utils.parse(self.fragment_lists[s])\n self.print_message(s, received_msg)\n self.fragment_lists[s].clear()\n # If the received fragment is not the last fragment, then we simply append it into the fragment list.\n else:\n self.fragment_lists[s].append(data)\n\n # This is a handy function to print the messages.\n def print_message(self, s, message):\n if self.lastline_type != s:\n print(\"\")\n self.lastline_type = s\n if s is self.client_side:\n print(Fore.YELLOW + Style.BRIGHT +'Alice says: ', Fore.BLUE + Style.BRIGHT + message, Fore.CYAN + Style.BRIGHT)\n else:\n print(Fore.MAGENTA + Style.BRIGHT +'Bob says: ', Fore.GREEN + Style.BRIGHT + message, Fore.CYAN + Style.BRIGHT)\n \n\n # This is a handy function to help with the closing of the connection.\n def close_connection(self, s):\n if s in self.outputs:\n self.outputs.remove(s)\n self.inputs.remove(s)\n s.close()\n del self.message_queues[s]\n del self.received_message_numbers[s]\n del self.fragment_lists[s]\n", "sub_path": "trudy/downgrade.py", "file_name": "downgrade.py", "file_ext": "py", "file_size_in_byte": 9130, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "socket.socket", "line_number": 10, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 10, "usage_type": "attribute"}, {"api_name": "socket.SOCK_STREAM", "line_number": 10, "usage_type": "attribute"}, {"api_name": "colorama.Fore.GREEN", "line_number": 13, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 13, "usage_type": "name"}, {"api_name": "colorama.Style.BRIGHT", "line_number": 13, "usage_type": "attribute"}, {"api_name": "colorama.Style", "line_number": 13, "usage_type": "name"}, {"api_name": "socket.socket", "line_number": 17, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 17, "usage_type": "attribute"}, {"api_name": "socket.SOCK_STREAM", "line_number": 17, "usage_type": "attribute"}, {"api_name": "colorama.Fore.CYAN", "line_number": 20, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 20, "usage_type": "name"}, {"api_name": "colorama.Style.BRIGHT", "line_number": 20, "usage_type": "attribute"}, {"api_name": "colorama.Style", "line_number": 20, "usage_type": "name"}, {"api_name": "queue.Queue", "line_number": 37, "usage_type": "call"}, {"api_name": "queue.Queue", "line_number": 39, "usage_type": "call"}, {"api_name": "select.select", "line_number": 54, "usage_type": "call"}, {"api_name": "chat_utils.CHAT_STARTTLS", "line_number": 62, "usage_type": "attribute"}, {"api_name": "chat_utils.CHAT_STARTTLS_NOT_SUPPORTED", "line_number": 66, "usage_type": "attribute"}, {"api_name": "chat_utils.CHAT_MESSAGE", "line_number": 74, "usage_type": "attribute"}, {"api_name": "chat_utils.CHAT_MESSAGE", "line_number": 83, "usage_type": "attribute"}, {"api_name": "queue.Empty", "line_number": 90, "usage_type": "attribute"}, {"api_name": "chat_utils.CHAT_CLOSE", "line_number": 94, "usage_type": "attribute"}, {"api_name": "colorama.Fore.RED", "line_number": 98, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 98, "usage_type": "name"}, {"api_name": "colorama.Style.BRIGHT", "line_number": 98, "usage_type": "attribute"}, {"api_name": "colorama.Style", "line_number": 98, "usage_type": "name"}, {"api_name": "colorama.Style.RESET_ALL", "line_number": 98, "usage_type": "attribute"}, {"api_name": "chat_utils.get_message_details", "line_number": 112, "usage_type": "call"}, {"api_name": "chat_utils.parse", "line_number": 127, "usage_type": "call"}, {"api_name": "colorama.Fore.YELLOW", "line_number": 140, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 140, "usage_type": "name"}, {"api_name": "colorama.Style.BRIGHT", "line_number": 140, "usage_type": "attribute"}, {"api_name": "colorama.Style", "line_number": 140, "usage_type": "name"}, {"api_name": "colorama.Fore.BLUE", "line_number": 140, "usage_type": "attribute"}, {"api_name": "colorama.Fore.CYAN", "line_number": 140, "usage_type": "attribute"}, {"api_name": "colorama.Fore.MAGENTA", "line_number": 142, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 142, "usage_type": "name"}, {"api_name": "colorama.Style.BRIGHT", "line_number": 142, "usage_type": "attribute"}, {"api_name": "colorama.Style", "line_number": 142, "usage_type": "name"}, {"api_name": "colorama.Fore.GREEN", "line_number": 142, "usage_type": "attribute"}, {"api_name": "colorama.Fore.CYAN", "line_number": 142, "usage_type": "attribute"}]}
+{"seq_id": "495463671", "text": "from django.db import models\r\nfrom consulta.models_login import User\r\n\r\n# Create your models here.\r\n\r\nclass Pacientes(User):\r\n role = models.CharField(max_length=9, default='paciente')\r\n birth = models.DateField(verbose_name='Data de Nascimento') # formato: 1991-11-15\r\n cpf = models.CharField(max_length=11, null=True, verbose_name='CPF')\r\n\r\n def __str__(self):\r\n return self.get_full_name()\r\n\r\n class Meta:\r\n verbose_name = 'Paciente'\r\n verbose_name_plural = 'Pacientes'\r\n\r\n\r\nclass Medicos(User):\r\n role = models.CharField(max_length=9, default='medico')\r\n birth = models.DateField(verbose_name='Data de Nascimento') # formato: 1991-11-15\r\n cpf = models.CharField(max_length=11, null=True, verbose_name='CPF')\r\n crm = models.CharField(max_length=20, null=True)\r\n foto = models.ImageField(null=True, blank=True)\r\n\r\n def __str__(self):\r\n return self.get_full_name()\r\n\r\n @property\r\n def imageURL(self):\r\n try:\r\n url = self.foto.url\r\n except:\r\n url = ''\r\n return url\r\n\r\n class Meta:\r\n verbose_name = 'Médico'\r\n verbose_name_plural = 'Médicos'\r\n\r\n\r\nclass Especialidades(models.Model):\r\n tipos = [('225105 - Acupuntura','Médico Acumputurista'),\r\n ('225110 - Alergia e Imunologia','Médico Alergista e Imunologista'),\r\n ('225151 - Anestesiologia','Médico anestesiologista'),\r\n ('225115 - Angiologia','Médico angiologista'),\r\n ('225120 - Cardiologia','Médico Cardiologista'),\r\n ('225124A - Cardiologia Pediátrica','Médico Cardiologista'),\r\n ('225210 - Cirurgia Cardiovascular','Médico Cirurgião Cardiovascular'),\r\n ('225215 - Cirurgia de Cabeça e Pescoço','Médico cirurgião de cabeça e pescoço'),\r\n ('225295 - Cirurgia de Mão','Médico cirurgião da mão'),\r\n ('225225 - Cirurgia Geral ','Médico cirurgião geral '),\r\n ('225230 - Cirurgia Pediátrica','Médico cirurgião pediátrico'),\r\n ('225235 - Cirurgia Plástica','Médico cirurgião plástico '),\r\n ('225305 - Citopatologia','Médico citopatologista'),\r\n ('225125 - Clínica Médica','Médico clínico'),\r\n ('225280 - Coloproctologia','Médico proctologista'),\r\n ('225135 - Dermatologia','Médico dermatologista'),\r\n ('225155 - Endocrinologia e Metabologia','Médico endocrinologista e metabologista'),\r\n \r\n ('225310A - Endoscopia digestiva','Médico em endoscopia'),\r\n ('225310B - Endoscopia respiratoria','Médico em endoscopia'),\r\n ('225160 - Fisiatria','Médico fisiatra'),\r\n ('223605 - Fisioterapia','Fisioterapeuta geral'),\r\n ('223810 - Fonoaudiologia','Fonoaudiólogo'),\r\n ('225165 - Gastroenterologia','Médico gastroenterologista'),\r\n ('225175 - Genetica Medica','Médico geneticista'),\r\n ('225180 - Geriatria','Médico geriatra'),\r\n ('225250 - Ginecologia e obstetricia','Médico ginecologista e obstetra'),\r\n ('225185 - Hematologia e hemoterapia','Médico Hematologista'),\r\n ('225210A - Hemodinamica e Cardiologia Intervencionista','Hemodinamica e Cardiologia Intervencionista'),\r\n ('225165A - Hepatologia','Hepatologia'),\r\n ('225195 - Homeopatia','Médico Homeopata'),\r\n ('225103 - Infectologia','Médico infectologista'),\r\n ('225255 - Mastologia','Médico Mastologista'),\r\n ('225315 - Medicina nuclear','Médico em medicina nuclear'),\r\n ('225170 - Medico Clinico Geral','Médico Generalista'),\r\n ('225109 - Nefrologia','Médico Nefrologista'),\r\n ('225124H - Neonatologia','Neonatologia'),\r\n ('225124I - Neurologia pediatrica','Médico neurologista'),\r\n ('225260 - Neurocirurgia ','Médico neurocirurgião'),\r\n ('225112 - Neurologia','Médico neurologista'),\r\n\r\n ('225118 - Nutrologia','Médico nutrologista'),\r\n ('225265 - Oftalmologia','Médico oftalmologista'),\r\n ('225121 - Oncologia','Médico oncologista clínico'),\r\n ('225270 - Ortopedia e traumatologia','Médico ortopedista e traumatologista'),\r\n ('225275 - Otorrinolaringologia','Médico otorrinolaringologista'),\r\n ('225335 - Patologia clínica/Medicina laboratorial','Médico patologista clínico /medicina laboratorial'),\r\n ('225124 - Pediatria','Médico pediatra'),\r\n ('225127 - Pneumologia','Médico pneumologista'),\r\n ('251510 - Psicologia','Psicólogo clínico'),\r\n ('225133 - Psiquiatria','Médico psiquiatra'),\r\n ('225320 - Radiologia e diagnóstico por imagem','Médico em radiologia e diagnóstico por imagem'),\r\n ('225330 - Radioterapia','Médico radioterapeuta'),\r\n ('225136 - Reumatologia','Médico reumatologista'),\r\n ('223905 - Terapia ocupacional','Terapeuta ocupacional'),\r\n ('225285 - Urologia','Médico Médico urologista'),\r\n ('223268 - Cirurgia e traumatologia buco-maxilo-facial','Cirurgião dentista - traumatologista bucomaxilofacial'),\r\n ('223208 - Dentista clinico geral','Cirurgião dentista - clínico geral'),\r\n ('223212 - Endodontia','Cirurgião dentista - endodontista'),\r\n ('223220 - Estomatologia','Cirurgião dentista - estomatologista'),\r\n ('223224 - Implantodontia','Cirurgião dentista - implantodontista'),\r\n ('223236 - Odontopediatria','Cirurgião dentista - odontopediatra'),\r\n ('223240 - Ortodontia','Cirurgião dentista - ortopedista e ortodontista'),\r\n\r\n ('223248 - Periodontia','Cirurgião dentista - periodontista'),\r\n ('223256 - Protese dentaria','Cirurgião dentista - protesista'),\r\n ('223260 - Imaginologia odontologica','Imaginologia odontologica'),\r\n ('225220 - Cirurgia do aparelho digestivo','Médico cirurgião do aparelho digestivo'),\r\n ('225240 - Cirurgia toracica','Médico cirurgião torácico'),\r\n ('225124B - Endocrinologia pediatrica','Médico endocrinologista e metabologista'),\r\n ('223845 - Foniatria','Fonoaudiólogo'),\r\n ('225124C - Gastroenterologia pediatrica','Médico gastroenterologista'),\r\n ('225124D - Hematologia e hemoterapia pediatrica','Médico Hematologista'),\r\n ('225124E - Medicina do adolescente','Medicina do adolescente'),\r\n ('225150 - Medicina intensiva','Médico em medicina intensiva'),\r\n ('225124F - Medicina intensiva pediatrica','Médico em medicina intensiva'),\r\n ('225124G - Nefrologia pediatrica','Médico Nefrologista'),\r\n ('223710 - Nutricionista','Nutricionista'),\r\n ('225290 - Oncologia cirurgica','Médico oncologista clínico'),\r\n ('225122 - Oncologia pediatrica','Médico oncologista clínico'),\r\n ('225124K - Pneumologia pediatrica','Médico pneumologista'),\r\n ('225133A - Psiquiatria da infancia eda adolescencia','Psicopedagogo'),\r\n ('225124L - Reumatologia pediatrica','Médico reumatologista'),\r\n ('223280 - Dentistica','Dentistica'),\r\n ('223284 - Disfuncao temporomandibular e dor orafacial.','Cirurgião dentista - disfunção temporomandibular e dor orofacial'),\r\n ('223228 - Odontogeriatria','Cirurgião dentista - odontogeriatra'),\r\n \r\n ('223288 - Odontologia para pacientes com necessidades especiais','Cirurgião dentista - odontologia para pacientes com necessidades especiais'),\r\n ('223284A - Ortopedia funcional dos maxilares','Ortopedia funcional dos maxilares'),\r\n ('999999 - Medicamentos Hospitalares','Medicamentos Hospitalares'),\r\n ('999999A - Opme','Opme'),\r\n ('225151A - Dor','Dor'),\r\n ('225112A - Medicina do Sono','Medicina do Sono'),\r\n ('225203 - Cirurgia Vascular','Médico em cirurgia vascular'),\r\n ('225310 - Endoscopia','Médico em endoscopia'),\r\n ('225160A - Medicina Fisica e Reabilitação','Medicina Fisica e Reabilitação'),\r\n ('225325 - patologia','Médico patologista'),\r\n ('251605 - Assistente social ','Assistente social '),\r\n ('223505 - Enfermagem','Técnico de enfermagem'),\r\n ('999999B - Não Informado','CBO desconhecido ou não informado pelo solicitante'),\r\n\r\n ]\r\n especialidade = models.CharField(max_length=100, choices=tipos)\r\n \r\n\r\n def __str__(self):\r\n return self.especialidade\r\n \r\n class Meta:\r\n verbose_name = 'Especialidade'\r\n verbose_name_plural = 'Especialidades'\r\n \r\n\r\nclass Medicos_especialidade(models.Model):\r\n id_medico = models.ForeignKey(Medicos, on_delete=models.SET_NULL, null=True)\r\n id_especialidade = models.ForeignKey(Especialidades, on_delete=models.SET_NULL, null=True)\r\n preco = models.DecimalField(max_digits=7, decimal_places=2)\r\n certificado_especialidade = models.ImageField(null=True, blank=True)\r\n\r\n def __str__(self):\r\n return str(self.id)\r\n\r\n class Meta:\r\n verbose_name = 'Médico Por Especialidade'\r\n verbose_name_plural = 'Médicos Por Especialidade'\r\n\r\nclass Localidades(models.Model):\r\n user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)\r\n cep = models.CharField(max_length=11, null=True)\r\n rua = models.CharField(max_length=50, null=True)\r\n bairro = models.CharField(max_length=50, null=True)\r\n cidade = models.CharField(max_length=100, null=True)\r\n estado = models.CharField(max_length=2, null=True)\r\n complemento = models.CharField(max_length=30, null=True)\r\n\r\n\r\n def __str__(self):\r\n return str(self.id)\r\n\r\n class Meta:\r\n verbose_name = 'Localidade'\r\n verbose_name_plural = 'Localidades'\r\n\r\nclass Agendas(models.Model):\r\n id_medico = models.ForeignKey(Medicos, on_delete=models.SET_NULL, null=True)\r\n id_especialidade = models.ForeignKey(Especialidades, on_delete=models.SET_NULL, null=True)\r\n tipos = [('Presencial', 'Presencial'), ('Digital', 'Digital')]\r\n tipos_consulta = models.CharField(max_length=50, choices=tipos)\r\n data = models.DateField()\r\n hora = models.TimeField()\r\n\r\n def __str__(self):\r\n return str(self.id)\r\n\r\n class Meta:\r\n verbose_name = 'Agenda'\r\n verbose_name_plural = 'Agendas'\r\n\r\nclass Compras(models.Model):\r\n id_paciente = models.ForeignKey(Pacientes, on_delete=models.SET_NULL, null=True)\r\n data_emissao = models.DateTimeField(auto_now_add=True)\r\n complete = models.BooleanField(default=False, null=True, blank=True)\r\n transaction_id = models.CharField(max_length=200, null=True)\r\n\r\n\r\n def __str__(self):\r\n return str(self.id)\r\n \r\n\r\n def get_cart_total(self):\r\n comprasitems = self.compras_consulta_set.all()\r\n total = sum([item.get_total for item in comprasitems])\r\n return total\r\n\r\n @property\r\n def get_cart_items(self):\r\n comprasitems = self.compras_consulta_set.all()\r\n total = sum([item.quantity for item in comprasitems])\r\n return total\r\n\r\n class Meta:\r\n verbose_name = 'Compra'\r\n verbose_name_plural = 'Compras'\r\n\r\n\r\nclass Compras_consulta(models.Model):\r\n id_compra = models.ForeignKey(Compras, on_delete=models.SET_NULL, null=True)\r\n id_medicos_especialidade = models.ForeignKey(Medicos_especialidade, on_delete=models.SET_NULL, null=True)\r\n quantity = models.IntegerField(default=0, null=True, blank=True)\r\n\r\n\r\n def __str__(self):\r\n return str(self.id)\r\n\r\n\r\n @property\r\n def get_total(self):\r\n total = self.id_medicos_especialidade.preco * self.quantity\r\n return total\r\n\r\n class Meta:\r\n verbose_name = 'Consulta Por Compra'\r\n verbose_name_plural = 'Consultas Por Compra'\r\n\r\n\r\nclass Contato_paciente(models.Model):\r\n id_paciente = models.ForeignKey(Pacientes, on_delete=models.SET_NULL, blank=True, null=True)\r\n id_compra = models.ForeignKey(Compras, on_delete=models.SET_NULL, blank=True, null=True)\r\n nome_completo = models.CharField(max_length=200, null=True)\r\n email = models.EmailField(max_length=200, null=True)\r\n cep = models.CharField(max_length=200, null=True)\r\n rua = models.CharField(max_length=200, null=True)\r\n bairro = models.CharField(max_length=200, null=True)\r\n cidade = models.CharField(max_length=200, null=True)\r\n estado = models.CharField(max_length=200, null=True)\r\n items_pedido = models.CharField(max_length=200, null=True)\r\n total = models.CharField(max_length=200, null=True)\r\n data_compra = models.DateTimeField(auto_now_add=True)\r\n\r\n def __str__(self):\r\n return str(self.id)", "sub_path": "medline/consulta/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 12953, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "consulta.models_login.User", "line_number": 6, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 7, "usage_type": "call"}, {"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.CharField", "line_number": 9, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 9, "usage_type": "name"}, {"api_name": "consulta.models_login.User", "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": "django.db.models.DateField", "line_number": 21, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 21, "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.db.models.CharField", "line_number": 23, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 23, "usage_type": "name"}, {"api_name": "django.db.models.ImageField", "line_number": 24, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 24, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 42, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 42, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 145, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 145, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 156, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 156, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 157, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 157, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 157, "usage_type": "attribute"}, {"api_name": "django.db.models.ForeignKey", "line_number": 158, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 158, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 158, "usage_type": "attribute"}, {"api_name": "django.db.models.DecimalField", "line_number": 159, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 159, "usage_type": "name"}, {"api_name": "django.db.models.ImageField", "line_number": 160, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 160, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 169, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 169, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 170, "usage_type": "call"}, {"api_name": "consulta.models_login.User", "line_number": 170, "usage_type": "argument"}, {"api_name": "django.db.models", "line_number": 170, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 170, "usage_type": "attribute"}, {"api_name": "django.db.models.CharField", "line_number": 171, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 171, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 172, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 172, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 173, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 173, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 174, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 174, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 175, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 175, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 176, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 176, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 186, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 186, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 187, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 187, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 187, "usage_type": "attribute"}, {"api_name": "django.db.models.ForeignKey", "line_number": 188, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 188, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 188, "usage_type": "attribute"}, {"api_name": "django.db.models.CharField", "line_number": 190, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 190, "usage_type": "name"}, {"api_name": "django.db.models.DateField", "line_number": 191, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 191, "usage_type": "name"}, {"api_name": "django.db.models.TimeField", "line_number": 192, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 192, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 201, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 201, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 202, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 202, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 202, "usage_type": "attribute"}, {"api_name": "django.db.models.DateTimeField", "line_number": 203, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 203, "usage_type": "name"}, {"api_name": "django.db.models.BooleanField", "line_number": 204, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 204, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 205, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 205, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 228, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 228, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 229, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 229, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 229, "usage_type": "attribute"}, {"api_name": "django.db.models.ForeignKey", "line_number": 230, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 230, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 230, "usage_type": "attribute"}, {"api_name": "django.db.models.IntegerField", "line_number": 231, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 231, "usage_type": "name"}, {"api_name": "django.db.models.Model", "line_number": 248, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 248, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 249, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 249, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 249, "usage_type": "attribute"}, {"api_name": "django.db.models.ForeignKey", "line_number": 250, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 250, "usage_type": "name"}, {"api_name": "django.db.models.SET_NULL", "line_number": 250, "usage_type": "attribute"}, {"api_name": "django.db.models.CharField", "line_number": 251, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 251, "usage_type": "name"}, {"api_name": "django.db.models.EmailField", "line_number": 252, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 252, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 253, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 253, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 254, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 254, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 255, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 255, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 256, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 256, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 257, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 257, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 258, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 258, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 259, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 259, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 260, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 260, "usage_type": "name"}]}
+{"seq_id": "489583457", "text": "import re\nimport logging\n\nLOGGER = logging.getLogger()\n\n\nIMAGE_FILE_RE = re.compile( \n \"(?P\\\\d{8})/\" +\n \"CS(?P\\\\d{1})/\" +\n \"(?P.+)/\" +\n \"p(?P\\\\d{1,2}|XX)/\" +\n \"ch(?P\\\\d{1}|XX)/\" +\n \"z(?P\\\\d{1,2}|XX)\"+\n \"(?P.*)\" +\n \"\\.\" + \n \"(?P.+)\"\n )\n\nclass LSMImageFilename:\n @classmethod\n def parse(cls, image_filename_str):\n match = IMAGE_FILE_RE.match(image_filename_str)\n if not match:\n raise Exception(\"invalid image filename: %s\" % image_filename_str)\n return cls(\n date=match[\"date\"],\n position=match[\"position\"],\n group=match[\"group\"],\n f=(None if match[\"f\"] == \"XXX\" else int(match[\"f\"])),\n z=(None if match[\"z\"] == \"XX\" else int(match[\"z\"])),\n c=(None if match[\"c\"] == \"XX\" else int(match[\"c\"])),\n suffix=match[\"suffix\"],\n extension=match[\"extension\"],\n )\n\n def __init__(self, date, position, group, f, z, c, suffix, extension):\n self.date = date\n self.position = position\n self.group = group\n self.f = f\n self.z = z\n self.c = c\n self.suffix = suffix\n self.extension = extension\n\n def __str__(self):\n return \"%s/CS%s/%s/p%s/ch%s/z%s%s.%s\" % (\n self.date,\n self.position,\n self.group,\n self.f_str,\n self.c_str,\n self.z_str,\n self.suffix,\n self.extension\n )\n\n def __copy__(self):\n return LSMImageFilename(\n date=self.date,\n position=self.position,\n group=self.group,\n f=self.f,\n z=self.z,\n c=self.c,\n suffix=self.suffix,\n extension=self.extension\n )\n\n @property\n def f_str(self):\n return \"XXX\" if not self.f else (\"%i\" % self.f)\n\n @property\n def z_str(self):\n return \"XX\" if not self.z else (\"%i\" % self.z)\n\n @property\n def c_str(self):\n return \"XX\" if not self.c else (\"%i\" % self.c)\n", "sub_path": "models/image_name_dictionaries/image_filename_LSM.py", "file_name": "image_filename_LSM.py", "file_ext": "py", "file_size_in_byte": 1861, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "logging.getLogger", "line_number": 4, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 7, "usage_type": "call"}]}
+{"seq_id": "23854682", "text": "from tkinter import *\r\nfrom tkinter import messagebox\r\nimport pymysql\r\nimport sqlite3\r\n\r\n\r\ndef ingresodenotas():\r\n\r\n conn=sqlite3.connect(\"notas\")\r\n \r\n\r\n cur=conn.cursor()\r\n cur.execute(\"INSERT INTO calificaciones1 VALUES (null,'\" + AF1.get() +\r\n \"','\" + so1.get() +\r\n \"','\" + PA1.get() +\r\n \"','\" + Comu1.get() + \"')\")\r\n\r\n conn.commit()\r\n \r\n \r\n messagebox.showinfo(\"DB\",\"Registro ingresado con exito\")\r\ndef leer():\r\n\r\n conn=sqlite3.connect(\"notas\")\r\n \r\n\r\n cur=conn.cursor()\r\n cur.execute(\"SELECT * FROM calificaciones1 WHERE ID=\" + ID1.get())\r\n\r\n elUsuario=cur.fetchall()\r\n\r\n for usuario in elUsuario:\r\n\r\n ID1.set(usuario[0])\r\n AF1.set(usuario[1])\r\n so1.set(usuario[2])\r\n PA1.set(usuario[3])\r\n Comu1.set(usuario[4])\r\n conn.commit()\r\ndef Limpiar ():\r\n\tID1.set(\" \")\r\n\tAF1.set(\" \")\r\n\tso1.set(\" \")\r\n\tPA1.set(\" \")\r\n\tComu1.set(\" \")\r\ndef salir():\r\n\tvalor=messagebox.askquestion(\"salir\",\"deseas salir de la aplicacion\")\r\n\tif valor==\"yes\":\r\n\t\ttk.destroy()\r\n\r\n\r\ndef actualizar():\r\n conn=sqlite3.connect(\"notas\")\r\n cur=conn.cursor()\r\n cur.execute(\"UPDATE calificaciones1 SET Algoritmos='\" + AF1.get() +\r\n \"', SistemasOp='\" + so1.get() +\r\n \"', Programacion='\" + PA1.get() +\r\n \"', Comunicaciones='\" + Comu1.get() +\r\n \"' WHERE ID=\" + ID1.get())\r\n \r\n conn.commit()\r\n messagebox.showinfo(\"DB\",\"Registro Actualizado con exito\")\r\ndef eliminar():\r\n\r\n conn=sqlite3.connect(\"notas\")\r\n cur=conn.cursor()\r\n cur.execute(\"DELETE FROM calificaciones1 WHERE ID=\" + ID1.get())\r\n conn.commit()\r\n messagebox.showinfo(\"BD\",\"Registro borrado con exito\")\r\n\r\ntk=Tk()\r\ntk.title(\"Ingreso de datos\")\r\nventana=Frame (height=400,width=700)\r\nventana.pack(padx=5,pady=5)\r\nventana.configure(background=\"MediumPurple2\")\r\ntema=Label(ventana,font=('Times New Roman',12,'bold'),text=\"Registro de notas\",padx=80,pady=3,bd=5,background=\"gray77\").place(x=170,y=0)\r\n#nota1\r\nnum_ced=Label(ventana,font=('Times New Roman',12,'bold'),text=\"Ingrese la ID del alumno que desea averiguar\",background=\"#91F467\").place(x=195,y=37)\r\nID1=StringVar()\r\ntxt=Entry(ventana,font=('Times New Roman',15,'bold'),textvariable=ID1,width=10,bg=\"cyan\",bd=5).place(x=400,y=70)\r\n#nota2\r\nAF=Label(ventana,font=('Times New Roman',12,'bold'),text=\"Algoritmos funtamentales\",background=\"#91F467\").place(x=0,y=80)\r\nAF1=StringVar()\r\ntxt1=Entry(ventana,font=('Times New Roman',15,'bold'),textvariable=AF1,width=10,bg=\"powder blue\",bd=5).place(x=210,y=80)\r\n#notas3\r\nso=Label(ventana,font=('Times New Roman',12,'bold'),text=\"Sistemas Operativos \",background=\"#91F467\").place(x=0,y=123)\r\nso1=StringVar()\r\ntxt2=Entry(ventana,font=('Times New Roman',15,'bold'),textvariable=so1,width=10,bg=\"powder blue\",bd=5).place(x=210,y=123)\r\n#notas4\r\nPA=Label(ventana,font=('Times New Roman',12,'bold'),text=\"Programacion avanzada \",background=\"#91F467\").place(x=0,y=166)\r\nPA1=StringVar()\r\ntxt3=Entry(ventana,font=('Times New Roman',15,'bold'),textvariable=PA1,width=10,bg=\"powder blue\",bd=5).place(x=210,y=166)\r\n#notas5\r\nComu=Label(ventana,font=('Times New Roman',12,'bold'),text=\"Comunicaciones\",background=\"#91F467\").place(x=0,y=209)\r\nComu1=StringVar()\r\ntxt4=Entry(ventana,font=('Times New Roman',15,'bold'),textvariable=Comu1,width=10,bg=\"powder blue\",bd=5).place(x=210,y=209)\r\n\r\n#botones\r\n\r\n#conectar=Button(ventana,font=('Times New Roman',12,'bold'),bd=15,command=conectar,text=\"conectar\",padx=20,pady=5,background=\"#91F467\").place(x=20,y=340)\r\ningresar=Button(ventana,font=('Times New Roman',12,'bold'),bd=15,command=ingresodenotas,text=\"Ingresar\",padx=20,pady=5,background=\"#91F467\").place(x=0,y=300)\r\nlimpiar=Button(ventana,font=('Times New Roman',12,'bold'),bd=15,command=Limpiar,text=\"Limpiar\",padx=20,pady=5,background=\"#FF60F3\").place(x=130,y=300)\r\nsalir=Button(ventana,font=('Times New Roman',12,'bold'),bd=15,command=salir,text=\"salir\",padx=20,pady=5,background=\"#FF60F3\").place(x=268,y=300)\r\nactualizar=Button(ventana,font=('Times New Roman',12,'bold'),bd=15,command=actualizar,text=\"Actualizar\",padx=20,pady=5,background=\"#91F467\").place(x=400,y=300)\r\nLeer=Button(ventana,font=('Times New Roman',12,'bold'),bd=15,command=leer,text=\"Leer\",padx=20,pady=5,background=\"#91F467\").place(x=580,y=300)\r\neliminar=Button(ventana,font=('Times New Roman',12,'bold'),bd=15,command=eliminar,text=\"borrar\",padx=20,pady=5,background=\"#91F467\").place(x=580,y=220)\r\ncanvas = Canvas(tk,width=300, height=300)\r\ncanvas.pack()\r\n\r\nesfera = PhotoImage(file='buo.png')\r\ncanvas.create_image(0, 0, anchor=NW, image=esfera)\r\n\r\ntk.mainloop()", "sub_path": "Juego_Retro_P_A-master/programacion avanzada base de datos/notas_saew.py", "file_name": "notas_saew.py", "file_ext": "py", "file_size_in_byte": 4591, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "sqlite3.connect", "line_number": 9, "usage_type": "call"}, {"api_name": "tkinter.messagebox.showinfo", "line_number": 21, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 21, "usage_type": "name"}, {"api_name": "sqlite3.connect", "line_number": 24, "usage_type": "call"}, {"api_name": "tkinter.messagebox.askquestion", "line_number": 47, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 47, "usage_type": "name"}, {"api_name": "sqlite3.connect", "line_number": 53, "usage_type": "call"}, {"api_name": "tkinter.messagebox.showinfo", "line_number": 62, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 62, "usage_type": "name"}, {"api_name": "sqlite3.connect", "line_number": 65, "usage_type": "call"}, {"api_name": "tkinter.messagebox.showinfo", "line_number": 69, "usage_type": "call"}, {"api_name": "tkinter.messagebox", "line_number": 69, "usage_type": "name"}]}
+{"seq_id": "116729729", "text": "\"\"\"empty message\n\nRevision ID: 43c36ca0314d\nRevises: ab3b53b230a\nCreate Date: 2015-12-16 21:23:57.583027\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '43c36ca0314d'\ndown_revision = 'ab3b53b230a'\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('feedback',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('value', sa.Boolean(), nullable=True),\n sa.Column('timestamp', sa.DateTime(), nullable=True),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.Column('answer_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['answer_id'], ['answer.id'], ),\n sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.drop_column(u'answer', 'feedback')\n op.drop_column(u'user', 'credit')\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.add_column(u'user', sa.Column('credit', sa.INTEGER(), autoincrement=False, nullable=True))\n op.add_column(u'answer', sa.Column('feedback', sa.VARCHAR(), autoincrement=False, nullable=True))\n op.drop_table('feedback')\n ### end Alembic commands ###\n", "sub_path": "migrations/versions/43c36ca0314d_.py", "file_name": "43c36ca0314d_.py", "file_ext": "py", "file_size_in_byte": 1260, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "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.Boolean", "line_number": 21, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 22, "usage_type": "call"}, {"api_name": "sqlalchemy.DateTime", "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.Integer", "line_number": 24, "usage_type": "call"}, {"api_name": "sqlalchemy.ForeignKeyConstraint", "line_number": 25, "usage_type": "call"}, {"api_name": "sqlalchemy.ForeignKeyConstraint", "line_number": 26, "usage_type": "call"}, {"api_name": "sqlalchemy.PrimaryKeyConstraint", "line_number": 27, "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.add_column", "line_number": 36, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 36, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 36, "usage_type": "call"}, {"api_name": "sqlalchemy.INTEGER", "line_number": 36, "usage_type": "call"}, {"api_name": "alembic.op.add_column", "line_number": 37, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 37, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 37, "usage_type": "call"}, {"api_name": "sqlalchemy.VARCHAR", "line_number": 37, "usage_type": "call"}, {"api_name": "alembic.op.drop_table", "line_number": 38, "usage_type": "call"}, {"api_name": "alembic.op", "line_number": 38, "usage_type": "name"}]}
+{"seq_id": "399828948", "text": "import cv2\nimport sys\nfrom moviepy.editor import VideoFileClip\n\n(major_ver, minor_ver, subminor_ver) = (cv2.cv2.__version__).split('.')\n\nfileToProcess = \"test.mp4\"\nfileToSave = \"out.mp4\"\nsecondsToSkip = 0\n\nif __name__ == '__main__' :\n # first we cut the seconds off of the video\n if secondsToSkip > 0:\n clip = VideoFileClip(fileToProcess).subclip(secondsToSkip)\n clip.write_videofile(fileToSave, codec=\"mpeg4\")\n fileToProcess=fileToSave\n\n # the trackers included in OpenCV version 4.5.1\n tracker_types = ['MIL','KCF', 'GOTURN', 'CSRT']\n tracker_type = tracker_types[3]\n if int(minor_ver) < 3:\n tracker = cv2.cv2.Tracker_create(tracker_type)\n else:\n if tracker_type == 'MIL':\n tracker = cv2.cv2.TrackerMIL_create()\n if tracker_type == 'KCF':\n tracker = cv2.cv2.TrackerKCF_create()\n if tracker_type == 'GOTURN':\n # not working try to remove opencv-contrib-python\n tracker = cv2.cv2.TrackerGOTURN_create()\n if tracker_type == \"CSRT\":\n tracker = cv2.cv2.TrackerCSRT_create()\n\n # Read video\n video = cv2.cv2.VideoCapture(fileToProcess)\n\n # Exit if video not opened.\n if not video.isOpened():\n print(\"Could not open video\")\n sys.exit()\n\n # Read first frame.\n ok, frame = video.read()\n if not ok:\n print('Cannot read video file')\n sys.exit()\n \n video.release()\n\n # Define an initial bounding box if you know it\n# bbox = (488*2, 266*2, 629*2, 730*2)\n\n # Uncomment the line below to select a different bounding box\n bbox = cv2.cv2.selectROI('Select Area', frame, False)\n cv2.cv2.destroyAllWindows()\n\n # Initialize tracker with first frame and bounding box\n ok = tracker.init(frame, bbox)\n\n def blur(image):\n frame = image.copy()\n try:\n ok, bbox = tracker.update(frame)\n if ok:\n blured = cv2.cv2.blur(frame,(int(frame.shape[0]*.05),int(frame.shape[0]*.05)))\n bluredroi = blured[int(bbox[1]):int(bbox[1]+bbox[3]), int(bbox[0]):int(bbox[0]+bbox[2])] \n frame[int(bbox[1]):int(bbox[1]+bbox[3]), int(bbox[0]):int(bbox[0]+bbox[2])] = bluredroi\n # in case you want a rectangle around the object\n # p1 = (int(bbox[0]), int(bbox[1]))\n # p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))\n # cv2.cv2.rectangle(frame, p1, p2, (255,0,0), 2, 1)\n else:\n return frame\n # print(\"Error\")\n # sys.exit()\n finally:\n return frame\n \n\n clip = VideoFileClip(fileToProcess)\n clip_blurred = clip.fl_image(blur)\n clip_blurred.write_videofile(fileToSave)", "sub_path": "mosaic.py", "file_name": "mosaic.py", "file_ext": "py", "file_size_in_byte": 2774, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "cv2.cv2.__version__.split", "line_number": 5, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 5, "usage_type": "attribute"}, {"api_name": "moviepy.editor.VideoFileClip", "line_number": 14, "usage_type": "call"}, {"api_name": "cv2.cv2.Tracker_create", "line_number": 22, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 22, "usage_type": "attribute"}, {"api_name": "cv2.cv2.TrackerMIL_create", "line_number": 25, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 25, "usage_type": "attribute"}, {"api_name": "cv2.cv2.TrackerKCF_create", "line_number": 27, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 27, "usage_type": "attribute"}, {"api_name": "cv2.cv2.TrackerGOTURN_create", "line_number": 30, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 30, "usage_type": "attribute"}, {"api_name": "cv2.cv2.TrackerCSRT_create", "line_number": 32, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 32, "usage_type": "attribute"}, {"api_name": "cv2.cv2.VideoCapture", "line_number": 35, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 35, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 40, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 46, "usage_type": "call"}, {"api_name": "cv2.cv2.selectROI", "line_number": 54, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 54, "usage_type": "attribute"}, {"api_name": "cv2.cv2.destroyAllWindows", "line_number": 55, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 55, "usage_type": "attribute"}, {"api_name": "cv2.cv2.blur", "line_number": 65, "usage_type": "call"}, {"api_name": "cv2.cv2", "line_number": 65, "usage_type": "attribute"}, {"api_name": "moviepy.editor.VideoFileClip", "line_number": 80, "usage_type": "call"}]}
+{"seq_id": "557094202", "text": "import logging\n\nimport pytest\nimport tensorflow as tf\n\nfrom ludwig.combiners.combiners import (\n ConcatCombiner,\n SequenceConcatCombiner,\n SequenceCombiner,\n TabNetCombiner,\n ComparatorCombiner,\n TransformerCombiner,\n TabTransformerCombiner,\n sequence_encoder_registry,\n)\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\nlogging.getLogger(\"ludwig\").setLevel(logging.INFO)\n\nBATCH_SIZE = 16\nSEQ_SIZE = 12\nHIDDEN_SIZE = 128\nOTHER_HIDDEN_SIZE = 32\nFC_SIZE = 64\nBASE_FC_SIZE = 256\n\n\n# set up simulated encoder outputs\n@pytest.fixture\ndef encoder_outputs():\n # generates simulated encoder outputs dictionary:\n # feature_1: shape [b, h1] tensor\n # feature_2: shape [b, h2] tensor\n # feature_3: shape [b, s, h1] tensor\n # feature_4: shape [b, sh, h2] tensor\n\n encoder_outputs = {}\n shapes_list = [\n [BATCH_SIZE, HIDDEN_SIZE],\n [BATCH_SIZE, OTHER_HIDDEN_SIZE],\n [BATCH_SIZE, SEQ_SIZE, HIDDEN_SIZE],\n [BATCH_SIZE, SEQ_SIZE, OTHER_HIDDEN_SIZE],\n ]\n feature_names = [\"feature_\" + str(i + 1) for i in range(len(shapes_list))]\n\n for feature_name, batch_shape in zip(feature_names, shapes_list):\n encoder_outputs[feature_name] = {\n \"encoder_output\": tf.random.normal(batch_shape, dtype=tf.float32)\n }\n if len(batch_shape) > 2:\n encoder_outputs[feature_name][\n \"encoder_output_state\"] = tf.random.normal(\n [batch_shape[0], batch_shape[2]], dtype=tf.float32\n )\n\n return encoder_outputs\n\n\n# setup encoder outputs for ComparatorCombiner\n@pytest.fixture\ndef encoder_comparator_outputs():\n # generates simulated encoder outputs dictionary:\n # feature_1: shape [b, h1] tensor\n # feature_2: shape [b, h2] tensor\n # feature_3: shape [b, s, h1] tensor\n # feature_4: shape [b, sh, h2] tensor\n\n encoder_outputs = {}\n shapes_list = [\n [BATCH_SIZE, HIDDEN_SIZE],\n [BATCH_SIZE, OTHER_HIDDEN_SIZE],\n [BATCH_SIZE, SEQ_SIZE, HIDDEN_SIZE],\n [BATCH_SIZE, SEQ_SIZE, OTHER_HIDDEN_SIZE],\n ]\n text_feature_names = [\"text_feature_\" + str(i + 1) for i in\n range(len(shapes_list))]\n image_feature_names = [\n \"image_feature_\" + str(i + 1) for i in range(len(shapes_list))\n ]\n for i, (feature_name, batch_shape) in enumerate(\n zip(text_feature_names, shapes_list)\n ):\n # is there a better way to do this?\n if i == 0 or i == 3:\n dot_product_shape = [batch_shape[0], BASE_FC_SIZE]\n encoder_outputs[feature_name] = {\n \"encoder_output\": tf.random.normal(dot_product_shape,\n dtype=tf.float32)\n }\n else:\n encoder_outputs[feature_name] = {\n \"encoder_output\": tf.random.normal(batch_shape,\n dtype=tf.float32)\n }\n\n for i, (feature_name, batch_shape) in enumerate(\n zip(image_feature_names, shapes_list)\n ):\n if i == 0 or i == 3:\n dot_product_shape = [batch_shape[0], BASE_FC_SIZE]\n encoder_outputs[feature_name] = {\n \"encoder_output\": tf.random.normal(dot_product_shape,\n dtype=tf.float32)\n }\n else:\n encoder_outputs[feature_name] = {\n \"encoder_output\": tf.random.normal(batch_shape,\n dtype=tf.float32)\n }\n\n return encoder_outputs\n\n\n# test for simple concatenation combiner\n@pytest.mark.parametrize(\"fc_layer\",\n [None, [{\"fc_size\": 64}, {\"fc_size\": 64}]])\ndef test_concat_combiner(encoder_outputs, fc_layer):\n # clean out unneeded encoder outputs\n del encoder_outputs[\"feature_3\"]\n del encoder_outputs[\"feature_4\"]\n\n # setup combiner to test\n combiner = ConcatCombiner(fc_layers=fc_layer)\n\n # concatenate encoder outputs\n results = combiner(encoder_outputs)\n\n # required key present\n assert \"combiner_output\" in results\n\n # confirm correct output shapes\n if fc_layer:\n assert results[\"combiner_output\"].shape.as_list() == [BATCH_SIZE,\n FC_SIZE]\n else:\n # calculate expected hidden size for concatenated tensors\n hidden_size = 0\n for k in encoder_outputs:\n hidden_size += encoder_outputs[k][\"encoder_output\"].shape[1]\n\n assert results[\"combiner_output\"].shape.as_list() == [BATCH_SIZE,\n hidden_size]\n\n\n# test for sequence concatenation combiner\n@pytest.mark.parametrize(\"reduce_output\", [None, \"sum\"])\n@pytest.mark.parametrize(\"main_sequence_feature\", [None, \"feature_3\"])\ndef test_sequence_concat_combiner(\n encoder_outputs, main_sequence_feature, reduce_output\n):\n combiner = SequenceConcatCombiner(\n main_sequence_feature=main_sequence_feature,\n reduce_output=reduce_output\n )\n\n # calculate expected hidden size for concatenated tensors\n hidden_size = 0\n for k in encoder_outputs:\n hidden_size += encoder_outputs[k][\"encoder_output\"].shape[-1]\n\n # concatenate encoder outputs\n results = combiner(encoder_outputs)\n\n # required key present\n assert \"combiner_output\" in results\n\n # confirm correct shape\n if reduce_output is None:\n assert results[\"combiner_output\"].shape.as_list() == [\n BATCH_SIZE,\n SEQ_SIZE,\n hidden_size,\n ]\n else:\n assert results[\"combiner_output\"].shape.as_list() == [BATCH_SIZE,\n hidden_size]\n\n\n# test for sequence combiner\n@pytest.mark.parametrize(\"reduce_output\", [None, \"sum\"])\n@pytest.mark.parametrize(\"encoder\", sequence_encoder_registry)\n@pytest.mark.parametrize(\"main_sequence_feature\", [None, \"feature_3\"])\ndef test_sequence_combiner(\n encoder_outputs, main_sequence_feature, encoder, reduce_output\n):\n combiner = SequenceCombiner(\n main_sequence_feature=main_sequence_feature,\n encoder=encoder,\n reduce_output=reduce_output,\n )\n\n # calculate expected hidden size for concatenated tensors\n hidden_size = 0\n for k in encoder_outputs:\n hidden_size += encoder_outputs[k][\"encoder_output\"].shape[-1]\n\n # concatenate encoder outputs\n results = combiner(encoder_outputs)\n\n # required key present\n assert \"combiner_output\" in results\n\n combiner_shape = results[\"combiner_output\"].shape\n # test for correct dimension\n if reduce_output:\n assert len(combiner_shape) == 2\n else:\n assert len(combiner_shape) == 3\n\n # Shape test assumes on Ludwig sequence encoder defaults\n # parallel encoders: # layers = 4, fc_size=256\n # non-parallel encoders: fc_size=256\n # if defaults change, then this test has to be updated\n default_layer = 4\n default_fc_size = 256\n\n if \"parallel\" in encoder:\n combiner_shape[-1] == default_layer * default_fc_size\n else:\n combiner_shape[-1] == default_fc_size\n\n\ndef tabnet_encoder_outputs():\n # Need to do this in a function, otherwise TF will try to initialize\n # too early\n return {\n 'batch_128': {\n 'feature_1': {\n 'encoder_output': tf.random.normal(\n [128, 1],\n dtype=tf.float32\n )\n },\n 'feature_2': {\n 'encoder_output': tf.random.normal(\n [128, 1],\n dtype=tf.float32\n )\n },\n },\n 'inputs': {\n 'feature_1': {\n 'encoder_output': tf.keras.Input(\n (),\n dtype=tf.float32,\n name='feature_1',\n )\n },\n 'feature_2': {\n 'encoder_output': tf.keras.Input(\n (),\n dtype=tf.float32,\n name='feature_2',\n )\n },\n }\n }\n\n\n@pytest.mark.parametrize(\"encoder_outputs_key\", ['batch_128', 'inputs'])\ndef test_tabnet_combiner(encoder_outputs_key):\n encoder_outputs = tabnet_encoder_outputs()[encoder_outputs_key]\n\n # setup combiner to test\n combiner = TabNetCombiner(\n size=2,\n output_size=2,\n num_steps=3,\n num_total_blocks=4,\n num_shared_blocks=2,\n dropout=0.1\n )\n\n # concatenate encoder outputs\n results = combiner(encoder_outputs)\n\n # required key present\n assert 'combiner_output' in results\n assert 'attention_masks' in results\n\n\n@pytest.mark.parametrize(\"fc_layer\",\n [None, [{\"fc_size\": 64}, {\"fc_size\": 64}]])\n@pytest.mark.parametrize(\"entity_1\", [[\"text_feature_1\", \"text_feature_2\"]])\n@pytest.mark.parametrize(\"entity_2\", [[\"image_feature_1\", \"image_feature_2\"]])\ndef test_comparator_combiner(encoder_comparator_outputs, fc_layer, entity_1,\n entity_2):\n # clean out unneeded encoder outputs since we only have 2 layers\n del encoder_comparator_outputs[\"text_feature_3\"]\n del encoder_comparator_outputs[\"image_feature_3\"]\n del encoder_comparator_outputs[\"text_feature_4\"]\n del encoder_comparator_outputs[\"image_feature_4\"]\n\n # setup combiner to test set to 256 for case when none as it's the default size\n fc_size = fc_layer[0][\"fc_size\"] if fc_layer else 256\n combiner = ComparatorCombiner(\n entity_1, entity_2, fc_layers=fc_layer, fc_size=fc_size\n )\n\n # concatenate encoder outputs\n results = combiner(encoder_comparator_outputs)\n\n # required key present\n assert \"combiner_output\" in results\n\n # confirm correct output shapes\n # concat on axis=1\n # because of dot products, 2 of the shapes added will be the fc_size\n # other 2 will be of shape BATCH_SIZE\n # this assumes dimensionality = 2\n size = BATCH_SIZE * 2 + fc_size * 2\n assert results[\"combiner_output\"].shape.as_list() == [BATCH_SIZE, size]\n\n\ndef test_transformer_combiner(encoder_outputs):\n # clean out unneeded encoder outputs\n encoder_outputs = {}\n encoder_outputs['feature_1'] = {\n 'encoder_output': tf.random.normal(\n [128, 1],\n dtype=tf.float32\n )\n }\n encoder_outputs['feature_2'] = {\n 'encoder_output': tf.random.normal(\n [128, 1],\n dtype=tf.float32\n )\n }\n\n input_features_def = [\n {'name': 'feature_1', 'type': 'numerical'},\n {'name': 'feature_2', 'type': 'numerical'}\n ]\n\n # setup combiner to test\n combiner = TransformerCombiner(\n input_features=input_features_def\n )\n\n # concatenate encoder outputs\n results = combiner(encoder_outputs)\n\n # required key present\n assert 'combiner_output' in results\n\n\ndef test_tabtransformer_combiner(encoder_outputs):\n # clean out unneeded encoder outputs\n encoder_outputs = {}\n encoder_outputs['feature_1'] = {\n 'encoder_output': tf.random.normal(\n [128, 1],\n dtype=tf.float32\n )\n }\n encoder_outputs['feature_2'] = {\n 'encoder_output': tf.random.normal(\n [128, 16],\n dtype=tf.float32\n )\n }\n\n input_features_def = [\n {'name': 'feature_1', 'type': 'numerical'},\n {'name': 'feature_2', 'type': 'category'}\n ]\n\n # setup combiner to test\n combiner = TabTransformerCombiner(\n input_features=input_features_def\n )\n\n # concatenate encoder outputs\n results = combiner(encoder_outputs)\n\n # required key present\n assert 'combiner_output' in results\n\n # setup combiner to test\n combiner = TabTransformerCombiner(\n input_features=input_features_def,\n embed_input_feature_name=56\n )\n\n # concatenate encoder outputs\n results = combiner(encoder_outputs)\n\n # required key present\n assert 'combiner_output' in results\n\n # setup combiner to test\n combiner = TabTransformerCombiner(\n input_features=input_features_def,\n embed_input_feature_name='add'\n )\n\n # concatenate encoder outputs\n results = combiner(encoder_outputs)\n\n # required key present\n assert 'combiner_output' in results\n", "sub_path": "tests/integration_tests/test_combiners.py", "file_name": "test_combiners.py", "file_ext": "py", "file_size_in_byte": 12397, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "logging.getLogger", "line_number": 17, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 18, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 19, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 19, "usage_type": "attribute"}, {"api_name": "tensorflow.random.normal", "line_number": 49, "usage_type": "call"}, {"api_name": "tensorflow.random", "line_number": 49, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 49, "usage_type": "attribute"}, {"api_name": "tensorflow.random.normal", "line_number": 53, "usage_type": "call"}, {"api_name": "tensorflow.random", "line_number": 53, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 54, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 30, "usage_type": "attribute"}, {"api_name": "tensorflow.random.normal", "line_number": 88, "usage_type": "call"}, {"api_name": "tensorflow.random", "line_number": 88, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 89, "usage_type": "attribute"}, {"api_name": "tensorflow.random.normal", "line_number": 93, "usage_type": "call"}, {"api_name": "tensorflow.random", "line_number": 93, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 94, "usage_type": "attribute"}, {"api_name": "tensorflow.random.normal", "line_number": 103, "usage_type": "call"}, {"api_name": "tensorflow.random", "line_number": 103, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 104, "usage_type": "attribute"}, {"api_name": "tensorflow.random.normal", "line_number": 108, "usage_type": "call"}, {"api_name": "tensorflow.random", "line_number": 108, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 109, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 61, "usage_type": "attribute"}, {"api_name": "ludwig.combiners.combiners.ConcatCombiner", "line_number": 124, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 116, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 116, "usage_type": "attribute"}, {"api_name": "ludwig.combiners.combiners.SequenceConcatCombiner", "line_number": 152, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 147, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 147, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 148, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 148, "usage_type": "attribute"}, {"api_name": "ludwig.combiners.combiners.SequenceCombiner", "line_number": 187, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 181, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 181, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 182, "usage_type": "call"}, {"api_name": "ludwig.combiners.combiners.sequence_encoder_registry", "line_number": 182, "usage_type": "argument"}, {"api_name": "pytest.mark", "line_number": 182, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 183, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 183, "usage_type": "attribute"}, {"api_name": "tensorflow.random.normal", "line_number": 230, "usage_type": "call"}, {"api_name": "tensorflow.random", "line_number": 230, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 232, "usage_type": "attribute"}, {"api_name": "tensorflow.random.normal", "line_number": 236, "usage_type": "call"}, {"api_name": "tensorflow.random", "line_number": 236, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 238, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.Input", "line_number": 244, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 244, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 246, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.Input", "line_number": 251, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 251, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 253, "usage_type": "attribute"}, {"api_name": "ludwig.combiners.combiners.TabNetCombiner", "line_number": 266, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 261, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 261, "usage_type": "attribute"}, {"api_name": "ludwig.combiners.combiners.ComparatorCombiner", "line_number": 297, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 283, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 283, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 285, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 285, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 286, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 286, "usage_type": "attribute"}, {"api_name": "tensorflow.random.normal", "line_number": 320, "usage_type": "call"}, {"api_name": "tensorflow.random", "line_number": 320, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 322, "usage_type": "attribute"}, {"api_name": "tensorflow.random.normal", "line_number": 326, "usage_type": "call"}, {"api_name": "tensorflow.random", "line_number": 326, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 328, "usage_type": "attribute"}, {"api_name": "ludwig.combiners.combiners.TransformerCombiner", "line_number": 338, "usage_type": "call"}, {"api_name": "tensorflow.random.normal", "line_number": 353, "usage_type": "call"}, {"api_name": "tensorflow.random", "line_number": 353, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 355, "usage_type": "attribute"}, {"api_name": "tensorflow.random.normal", "line_number": 359, "usage_type": "call"}, {"api_name": "tensorflow.random", "line_number": 359, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 361, "usage_type": "attribute"}, {"api_name": "ludwig.combiners.combiners.TabTransformerCombiner", "line_number": 371, "usage_type": "call"}, {"api_name": "ludwig.combiners.combiners.TabTransformerCombiner", "line_number": 382, "usage_type": "call"}, {"api_name": "ludwig.combiners.combiners.TabTransformerCombiner", "line_number": 394, "usage_type": "call"}]}
+{"seq_id": "123126141", "text": "from django.conf.urls import include, url\nfrom django.contrib import admin\n\n\nurlpatterns = [\n # uvodne kecy, kontakt, demo, faq,...\n url(r'^', include('about.urls', namespace=\"about\")),\n # zadania, riesenia uloh; sady\n url(r'^tasks/', include('tasks.urls', namespace=\"tasks\")),\n # submity, statistiky\n url(r'^submits/', include('submit.urls', namespace=\"submit\")),\n # django admin\n url(r'^admin/', include(admin.site.urls)),\n # login\n url(r'^account/', include('ksp_login.urls')),\n]\n", "sub_path": "page/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 513, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "django.conf.urls.url", "line_number": 7, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 7, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 9, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 9, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 11, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 11, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 13, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 13, "usage_type": "call"}, {"api_name": "django.contrib.admin.site", "line_number": 13, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 13, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 15, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 15, "usage_type": "call"}]}
+{"seq_id": "180261169", "text": "import sys\nfrom collections import defaultdict\n\n\nclass MockRandomName:\n def __init__(self):\n self.generator = defaultdict(lambda: {}, {\n 'a': {\n 'get': lambda: 'codeA',\n 'filename': 'a.a',\n 'language_name': 'A'\n },\n 'b': {\n 'get': lambda: 'codeB',\n 'filename': 'b.b',\n 'language_name': 'B'\n }\n })\n\n\nsys.modules['app.helpers.code_generator'] = MockRandomName()\n", "sub_path": "tests/mocks/mock_code_generator.py", "file_name": "mock_code_generator.py", "file_ext": "py", "file_size_in_byte": 511, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "collections.defaultdict", "line_number": 7, "usage_type": "call"}, {"api_name": "sys.modules", "line_number": 21, "usage_type": "attribute"}]}
+{"seq_id": "300497462", "text": "#Code Used From:\n#https://www.101computing.net/creating-sprites-using-pygame/\n\nimport pygame\nfrom pygame.math import Vector2\nimport math\n\nWHITE = (255, 255, 255)\nYELLOW = (255, 255, 63)\n\nclass Boat(pygame.sprite.Sprite):\n #This class represents a car. It derives from the \"Sprite\" class in Pygame.\n\n def __init__(self, pos):\n # Call the parent class (Sprite) constructor\n super().__init__()\n\n # Pass in the color of the car, and its x and y position, width and height.\n # Set the background color and set it to be transparent\n\n self.image = pygame.Surface((80,202), pygame.SRCALPHA)\n # self.image.fill(WHITE)\n # self.image.set_colorkey(WHITE)\n\n picture = pygame.image.load(\"images/yellow_boat.png\")\n boat_image = pygame.transform.scale(picture, (80, 200))\n self.image = boat_image\n self.rotated_image = self.image\n\n self.rect = self.image.get_rect(center=(pos))\n self.pos = Vector2(pos)\n self.offset = Vector2(0, 0)\n self.angle = 0\n\n #pygame.draw.rect(picture, WHITE, 0, width = 0)\n\n\n def rotate(self):\n self.image = pygame.transform.rotozoom(self.rotated_image, -self.angle, 1)\n offset_rotated = self.offset.rotate(self.angle)\n self.rect = self.image.get_rect(center=self.pos+offset_rotated)\n\n def rotate_right(self):\n self.angle += 1\n self.rotate()\n\n def rotate_left(self):\n self.angle -= 1\n self.rotate()\n\n def moveRight(self, pixels):\n self.rect.x += pixels\n self.pos.x += pixels\n\n def moveLeft(self, pixels):\n self.rect.x -= pixels\n self.pos.x -= pixels\n\n def moveUp(self, pixels):\n #self.rect.y -= pixels\n self.pos.y -= math.cos(math.radians(self.angle))*pixels\n self.pos.x += math.sin(math.radians(self.angle))*pixels\n \n print(self.pos.x, self.pos.y)\n self.rect.y -= math.cos(math.radians(self.angle))*pixels\n self.rect.x += math.sin(math.radians(self.angle))*pixels\n self.rect = self.image.get_rect(center=self.pos)\n \n def moveDown(self, pixels):\n self.rect.y += pixels\n self.pos.y += pixels\n #def distance(self):\n ", "sub_path": "Final_Blind_Sailing/Previous_Work/boat1.py", "file_name": "boat1.py", "file_ext": "py", "file_size_in_byte": 2226, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "pygame.sprite", "line_number": 11, "usage_type": "attribute"}, {"api_name": "pygame.Surface", "line_number": 21, "usage_type": "call"}, {"api_name": "pygame.SRCALPHA", "line_number": 21, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 25, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 25, "usage_type": "attribute"}, {"api_name": "pygame.transform.scale", "line_number": 26, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 26, "usage_type": "attribute"}, {"api_name": "pygame.math.Vector2", "line_number": 31, "usage_type": "call"}, {"api_name": "pygame.math.Vector2", "line_number": 32, "usage_type": "call"}, {"api_name": "pygame.transform.rotozoom", "line_number": 39, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 39, "usage_type": "attribute"}, {"api_name": "math.cos", "line_number": 61, "usage_type": "call"}, {"api_name": "math.radians", "line_number": 61, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 62, "usage_type": "call"}, {"api_name": "math.radians", "line_number": 62, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 65, "usage_type": "call"}, {"api_name": "math.radians", "line_number": 65, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 66, "usage_type": "call"}, {"api_name": "math.radians", "line_number": 66, "usage_type": "call"}]}
+{"seq_id": "272244445", "text": "import sqlite3\n\nimport click\nfrom flask import g\nfrom flask import current_app\nfrom flask.cli import with_appcontext\n\ndef get_db():\n if \"db\" not in g:\n g.db = sqlite3.connect(current_app.config['DATABASE'])\n\n return g.db\n\ndef close_db(_):\n db = g.get(\"pop\", None)\n if db:\n db.close()\n\ndef init_db():\n db = get_db()\n with current_app.open_resource(\"schema.sql\") as f:\n db.executescript(f.read().decode(\"utf8\"))\n\nclass Poll(object):\n @classmethod\n def get_poll_by_id(cls, id):\n db = get_db()\n raw_poll = get_db().execute(\"SELECT id, name, date FROM polls WHERE id = ?\", [id]).fetchone()\n\n if raw_poll:\n return cls(\n id=raw_poll[0],\n name=raw_poll[1],\n date=raw_poll[2],\n )\n\n return None\n\n @classmethod\n def get_polls(cls):\n db = get_db()\n raw_polls = get_db().execute(\"SELECT id, name, date FROM polls ORDER BY id ASC\").fetchall()\n polls = []\n for raw_poll in raw_polls:\n polls.append(cls(\n id=raw_poll[0],\n name=raw_poll[1],\n date=raw_poll[2]\n ))\n\n return polls\n\n def __init__(self, id, name, date):\n self.id = id\n self.name = name\n self.date = date\n\n def save(self):\n db = get_db()\n if self.id == None:\n db.execute(\"INSERT INTO polls VALUES (null, ?, ?)\", [self.name, self.date])\n self.id = db.execute(\"SELECT last_insert_rowid()\").fetchone()[0]\n else:\n db.execute(\"UPDATE polls SET name = ?, date = ? WHERE id = ?\", [self.name, self.date, self.id])\n\n db.commit()\n\n def number_of_votes(self):\n return get_db().execute(\"SELECT count(*) FROM vote_casts WHERE poll_id = ?\", [self.id]).fetchone()[0]\n\n def __str__(self):\n return self.name\n\n def __repr__(self):\n return \" {name}\".format(id=self.id, name=self.name)\n\n\nclass Choice(object):\n @classmethod\n def get_choices_for_poll(cls, poll):\n db = get_db()\n raw_choices = get_db().execute(\"SELECT id, choice FROM choices WHERE poll_id = ?\", [poll.id]).fetchall()\n\n choices = []\n for raw_choice in raw_choices:\n choices.append(cls(\n id=raw_choice[0],\n choice=raw_choice[1],\n poll=poll,\n ))\n\n return choices\n\n @classmethod\n def get_by_id_for_poll(cls, poll, choice_id):\n db = get_db()\n raw_poll = get_db().execute(\"SELECT id, choice FROM choices WHERE id = ? and poll_id= ? \", [choice_id, poll.id]).fetchone()\n\n if raw_poll:\n return cls(\n id=raw_poll[0],\n choice=raw_poll[1],\n poll=poll,\n )\n\n return None\n\n def __init__(self, id, choice, poll):\n self.id = id\n self.choice = choice\n self.poll = poll\n\n def save(self):\n db = get_db()\n if self.id == None:\n db.execute(\"INSERT INTO choices VALUES (null, ?, ?)\", [self.choice, self.poll.id])\n self.id = db.execute(\"SELECT last_insert_rowid()\").fetchone()[0]\n else:\n db.execute(\"UPDATE choices SET choice = ? WHERE id = ?\", [self.choice, self.id])\n\n db.commit()\n\n def cast_vote(self):\n db = get_db()\n db.execute(\"INSERT INTO vote_casts VALUES (null, ?, ?)\", [self.poll.id, self.id])\n db.commit()\n\n def number_of_votes(self):\n return get_db().execute(\"SELECT count(*) FROM vote_casts WHERE choice_id = ?\", [self.id]).fetchone()[0]\n\n def __str__(self):\n return self.choice\n\n def __repr__(self):\n return \" {choice}\".format(id=self.id, choice=self.choice)\n\n\n\n@click.command(\"init-db\")\n@with_appcontext\ndef init_db_command():\n init_db()\n click.echo(\"Initialized the database.\")\n\n\ndef init_app(app):\n app.teardown_appcontext(close_db)\n app.cli.add_command(init_db_command)\n", "sub_path": "cours/03-sept-18/exemples/station-de-vote/poll/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 4000, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "flask.g", "line_number": 9, "usage_type": "name"}, {"api_name": "flask.g.db", "line_number": 10, "usage_type": "attribute"}, {"api_name": "flask.g", "line_number": 10, "usage_type": "name"}, {"api_name": "sqlite3.connect", "line_number": 10, "usage_type": "call"}, {"api_name": "flask.current_app.config", "line_number": 10, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 10, "usage_type": "name"}, {"api_name": "flask.g.db", "line_number": 12, "usage_type": "attribute"}, {"api_name": "flask.g", "line_number": 12, "usage_type": "name"}, {"api_name": "flask.g.get", "line_number": 15, "usage_type": "call"}, {"api_name": "flask.g", "line_number": 15, "usage_type": "name"}, {"api_name": "flask.current_app.open_resource", "line_number": 21, "usage_type": "call"}, {"api_name": "flask.current_app", "line_number": 21, "usage_type": "name"}, {"api_name": "click.echo", "line_number": 143, "usage_type": "call"}, {"api_name": "click.command", "line_number": 139, "usage_type": "call"}, {"api_name": "flask.cli.with_appcontext", "line_number": 140, "usage_type": "name"}]}
+{"seq_id": "99750552", "text": "#!/usr/bin/env python\n\nfrom ase.io import read\nfrom ase import Atom\n\nslabO = read('POSCAR')\n# get index of first O atom\nindex_O = next(a.index for a in slabO if a.symbol == 'O')\nO = slabO[index_O]\npos_H = O.position + (0, 0, 0.987)\nH = Atom('H', pos_H)\nslabOH = slabO + H\nslabOH.write('POSCAR', format='vasp', vasp5=True, sort=True, direct=True)\n\n", "sub_path": "bin/add_H_on_O.py", "file_name": "add_H_on_O.py", "file_ext": "py", "file_size_in_byte": 347, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "ase.io.read", "line_number": 6, "usage_type": "call"}, {"api_name": "ase.Atom", "line_number": 11, "usage_type": "call"}]}
+{"seq_id": "483109238", "text": "from django.http import HttpResponseRedirect\nfrom django.utils.deprecation import MiddlewareMixin\nfrom users.models import UserModel\n\n\nclass AuthMiddleware(MiddlewareMixin):\n def process_request(self, request):\n ticket = request.COOKIES.get('ticket')\n if request.path == '/users/cart/':\n ticket = request.COOKIES.get('ticket')\n if not ticket:\n return HttpResponseRedirect('/users/login/')\n users = UserModel.objects.filter(t_ticket=ticket)\n if users:\n request.user = users[0]\n else:\n return HttpResponseRedirect('/users/login/')\n else:\n if not ticket:\n return None\n users = UserModel.objects.filter(t_ticket=ticket)\n if users:\n request.user = users[0]", "sub_path": "aixianfeng3.0/utils/UserAuthMiddleware.py", "file_name": "UserAuthMiddleware.py", "file_ext": "py", "file_size_in_byte": 838, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "django.utils.deprecation.MiddlewareMixin", "line_number": 6, "usage_type": "name"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 12, "usage_type": "call"}, {"api_name": "users.models", "line_number": 13, "usage_type": "name"}, {"api_name": "users.models.UserModel.objects.filter", "line_number": 13, "usage_type": "call"}, {"api_name": "users.models.UserModel.objects", "line_number": 13, "usage_type": "attribute"}, {"api_name": "users.models.UserModel", "line_number": 13, "usage_type": "name"}, {"api_name": "users.models", "line_number": 14, "usage_type": "name"}, {"api_name": "users.models", "line_number": 15, "usage_type": "name"}, {"api_name": "django.http.HttpResponseRedirect", "line_number": 17, "usage_type": "call"}, {"api_name": "users.models", "line_number": 21, "usage_type": "name"}, {"api_name": "users.models.UserModel.objects.filter", "line_number": 21, "usage_type": "call"}, {"api_name": "users.models.UserModel.objects", "line_number": 21, "usage_type": "attribute"}, {"api_name": "users.models.UserModel", "line_number": 21, "usage_type": "name"}, {"api_name": "users.models", "line_number": 22, "usage_type": "name"}, {"api_name": "users.models", "line_number": 23, "usage_type": "name"}]}
+{"seq_id": "120021978", "text": "# Copyright 2017 Google LLC All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport collections\nimport unittest\n\nimport mock\n\n\nclass TestDocumentReference(unittest.TestCase):\n @staticmethod\n def _get_target_class():\n from google.cloud.firestore_v1.document import DocumentReference\n\n return DocumentReference\n\n def _make_one(self, *args, **kwargs):\n klass = self._get_target_class()\n return klass(*args, **kwargs)\n\n def test_constructor(self):\n collection_id1 = \"users\"\n document_id1 = \"alovelace\"\n collection_id2 = \"platform\"\n document_id2 = \"*nix\"\n client = mock.MagicMock()\n client.__hash__.return_value = 1234\n\n document = self._make_one(\n collection_id1, document_id1, collection_id2, document_id2, client=client\n )\n self.assertIs(document._client, client)\n expected_path = \"/\".join(\n (collection_id1, document_id1, collection_id2, document_id2)\n )\n self.assertEqual(document.path, expected_path)\n\n def test_constructor_invalid_path(self):\n with self.assertRaises(ValueError):\n self._make_one()\n with self.assertRaises(ValueError):\n self._make_one(None, \"before\", \"bad-collection-id\", \"fifteen\")\n with self.assertRaises(ValueError):\n self._make_one(\"bad-document-ID\", None)\n with self.assertRaises(ValueError):\n self._make_one(\"Just\", \"A-Collection\", \"Sub\")\n\n def test_constructor_invalid_kwarg(self):\n with self.assertRaises(TypeError):\n self._make_one(\"Coh-lek-shun\", \"Dahk-yu-mehnt\", burger=18.75)\n\n def test___copy__(self):\n client = _make_client(\"rain\")\n document = self._make_one(\"a\", \"b\", client=client)\n # Access the document path so it is copied.\n doc_path = document._document_path\n self.assertEqual(doc_path, document._document_path_internal)\n\n new_document = document.__copy__()\n self.assertIsNot(new_document, document)\n self.assertIs(new_document._client, document._client)\n self.assertEqual(new_document._path, document._path)\n self.assertEqual(\n new_document._document_path_internal, document._document_path_internal\n )\n\n def test___deepcopy__calls_copy(self):\n client = mock.sentinel.client\n document = self._make_one(\"a\", \"b\", client=client)\n document.__copy__ = mock.Mock(return_value=mock.sentinel.new_doc, spec=[])\n\n unused_memo = {}\n new_document = document.__deepcopy__(unused_memo)\n self.assertIs(new_document, mock.sentinel.new_doc)\n document.__copy__.assert_called_once_with()\n\n def test__eq__same_type(self):\n document1 = self._make_one(\"X\", \"YY\", client=mock.sentinel.client)\n document2 = self._make_one(\"X\", \"ZZ\", client=mock.sentinel.client)\n document3 = self._make_one(\"X\", \"YY\", client=mock.sentinel.client2)\n document4 = self._make_one(\"X\", \"YY\", client=mock.sentinel.client)\n\n pairs = ((document1, document2), (document1, document3), (document2, document3))\n for candidate1, candidate2 in pairs:\n # We use == explicitly since assertNotEqual would use !=.\n equality_val = candidate1 == candidate2\n self.assertFalse(equality_val)\n\n # Check the only equal one.\n self.assertEqual(document1, document4)\n self.assertIsNot(document1, document4)\n\n def test__eq__other_type(self):\n document = self._make_one(\"X\", \"YY\", client=mock.sentinel.client)\n other = object()\n equality_val = document == other\n self.assertFalse(equality_val)\n self.assertIs(document.__eq__(other), NotImplemented)\n\n def test___hash__(self):\n client = mock.MagicMock()\n client.__hash__.return_value = 234566789\n document = self._make_one(\"X\", \"YY\", client=client)\n self.assertEqual(hash(document), hash((\"X\", \"YY\")) + hash(client))\n\n def test__ne__same_type(self):\n document1 = self._make_one(\"X\", \"YY\", client=mock.sentinel.client)\n document2 = self._make_one(\"X\", \"ZZ\", client=mock.sentinel.client)\n document3 = self._make_one(\"X\", \"YY\", client=mock.sentinel.client2)\n document4 = self._make_one(\"X\", \"YY\", client=mock.sentinel.client)\n\n self.assertNotEqual(document1, document2)\n self.assertNotEqual(document1, document3)\n self.assertNotEqual(document2, document3)\n\n # We use != explicitly since assertEqual would use ==.\n inequality_val = document1 != document4\n self.assertFalse(inequality_val)\n self.assertIsNot(document1, document4)\n\n def test__ne__other_type(self):\n document = self._make_one(\"X\", \"YY\", client=mock.sentinel.client)\n other = object()\n self.assertNotEqual(document, other)\n self.assertIs(document.__ne__(other), NotImplemented)\n\n def test__document_path_property(self):\n project = \"hi-its-me-ok-bye\"\n client = _make_client(project=project)\n\n collection_id = \"then\"\n document_id = \"090909iii\"\n document = self._make_one(collection_id, document_id, client=client)\n doc_path = document._document_path\n expected = \"projects/{}/databases/{}/documents/{}/{}\".format(\n project, client._database, collection_id, document_id\n )\n self.assertEqual(doc_path, expected)\n self.assertIs(document._document_path_internal, doc_path)\n\n # Make sure value is cached.\n document._document_path_internal = mock.sentinel.cached\n self.assertIs(document._document_path, mock.sentinel.cached)\n\n def test__document_path_property_no_client(self):\n document = self._make_one(\"hi\", \"bye\")\n self.assertIsNone(document._client)\n with self.assertRaises(ValueError):\n getattr(document, \"_document_path\")\n\n self.assertIsNone(document._document_path_internal)\n\n def test_id_property(self):\n document_id = \"867-5309\"\n document = self._make_one(\"Co-lek-shun\", document_id)\n self.assertEqual(document.id, document_id)\n\n def test_parent_property(self):\n from google.cloud.firestore_v1.collection import CollectionReference\n\n collection_id = \"grocery-store\"\n document_id = \"market\"\n client = _make_client()\n document = self._make_one(collection_id, document_id, client=client)\n\n parent = document.parent\n self.assertIsInstance(parent, CollectionReference)\n self.assertIs(parent._client, client)\n self.assertEqual(parent._path, (collection_id,))\n\n def test_collection_factory(self):\n from google.cloud.firestore_v1.collection import CollectionReference\n\n collection_id = \"grocery-store\"\n document_id = \"market\"\n new_collection = \"fruits\"\n client = _make_client()\n document = self._make_one(collection_id, document_id, client=client)\n\n child = document.collection(new_collection)\n self.assertIsInstance(child, CollectionReference)\n self.assertIs(child._client, client)\n self.assertEqual(child._path, (collection_id, document_id, new_collection))\n\n @staticmethod\n def _write_pb_for_create(document_path, document_data):\n from google.cloud.firestore_v1.proto import common_pb2\n from google.cloud.firestore_v1.proto import document_pb2\n from google.cloud.firestore_v1.proto import write_pb2\n from google.cloud.firestore_v1 import _helpers\n\n return write_pb2.Write(\n update=document_pb2.Document(\n name=document_path, fields=_helpers.encode_dict(document_data)\n ),\n current_document=common_pb2.Precondition(exists=False),\n )\n\n @staticmethod\n def _make_commit_repsonse(write_results=None):\n from google.cloud.firestore_v1.proto import firestore_pb2\n\n response = mock.create_autospec(firestore_pb2.CommitResponse)\n response.write_results = write_results or [mock.sentinel.write_result]\n response.commit_time = mock.sentinel.commit_time\n return response\n\n def test_create(self):\n # Create a minimal fake GAPIC with a dummy response.\n firestore_api = mock.Mock(spec=[\"commit\"])\n firestore_api.commit.return_value = self._make_commit_repsonse()\n\n # Attach the fake GAPIC to a real client.\n client = _make_client(\"dignity\")\n client._firestore_api_internal = firestore_api\n\n # Actually make a document and call create().\n document = self._make_one(\"foo\", \"twelve\", client=client)\n document_data = {\"hello\": \"goodbye\", \"count\": 99}\n write_result = document.create(document_data)\n\n # Verify the response and the mocks.\n self.assertIs(write_result, mock.sentinel.write_result)\n write_pb = self._write_pb_for_create(document._document_path, document_data)\n firestore_api.commit.assert_called_once_with(\n client._database_string,\n [write_pb],\n transaction=None,\n metadata=client._rpc_metadata,\n )\n\n def test_create_empty(self):\n # Create a minimal fake GAPIC with a dummy response.\n from google.cloud.firestore_v1.document import DocumentReference\n from google.cloud.firestore_v1.document import DocumentSnapshot\n\n firestore_api = mock.Mock(spec=[\"commit\"])\n document_reference = mock.create_autospec(DocumentReference)\n snapshot = mock.create_autospec(DocumentSnapshot)\n snapshot.exists = True\n document_reference.get.return_value = snapshot\n firestore_api.commit.return_value = self._make_commit_repsonse(\n write_results=[document_reference]\n )\n\n # Attach the fake GAPIC to a real client.\n client = _make_client(\"dignity\")\n client._firestore_api_internal = firestore_api\n client.get_all = mock.MagicMock()\n client.get_all.exists.return_value = True\n\n # Actually make a document and call create().\n document = self._make_one(\"foo\", \"twelve\", client=client)\n document_data = {}\n write_result = document.create(document_data)\n self.assertTrue(write_result.get().exists)\n\n @staticmethod\n def _write_pb_for_set(document_path, document_data, merge):\n from google.cloud.firestore_v1.proto import common_pb2\n from google.cloud.firestore_v1.proto import document_pb2\n from google.cloud.firestore_v1.proto import write_pb2\n from google.cloud.firestore_v1 import _helpers\n\n write_pbs = write_pb2.Write(\n update=document_pb2.Document(\n name=document_path, fields=_helpers.encode_dict(document_data)\n )\n )\n if merge:\n field_paths = [\n field_path\n for field_path, value in _helpers.extract_fields(\n document_data, _helpers.FieldPath()\n )\n ]\n field_paths = [\n field_path.to_api_repr() for field_path in sorted(field_paths)\n ]\n mask = common_pb2.DocumentMask(field_paths=sorted(field_paths))\n write_pbs.update_mask.CopyFrom(mask)\n return write_pbs\n\n def _set_helper(self, merge=False, **option_kwargs):\n # Create a minimal fake GAPIC with a dummy response.\n firestore_api = mock.Mock(spec=[\"commit\"])\n firestore_api.commit.return_value = self._make_commit_repsonse()\n\n # Attach the fake GAPIC to a real client.\n client = _make_client(\"db-dee-bee\")\n client._firestore_api_internal = firestore_api\n\n # Actually make a document and call create().\n document = self._make_one(\"User\", \"Interface\", client=client)\n document_data = {\"And\": 500, \"Now\": b\"\\xba\\xaa\\xaa \\xba\\xaa\\xaa\"}\n write_result = document.set(document_data, merge)\n\n # Verify the response and the mocks.\n self.assertIs(write_result, mock.sentinel.write_result)\n write_pb = self._write_pb_for_set(document._document_path, document_data, merge)\n\n firestore_api.commit.assert_called_once_with(\n client._database_string,\n [write_pb],\n transaction=None,\n metadata=client._rpc_metadata,\n )\n\n def test_set(self):\n self._set_helper()\n\n def test_set_merge(self):\n self._set_helper(merge=True)\n\n @staticmethod\n def _write_pb_for_update(document_path, update_values, field_paths):\n from google.cloud.firestore_v1.proto import common_pb2\n from google.cloud.firestore_v1.proto import document_pb2\n from google.cloud.firestore_v1.proto import write_pb2\n from google.cloud.firestore_v1 import _helpers\n\n return write_pb2.Write(\n update=document_pb2.Document(\n name=document_path, fields=_helpers.encode_dict(update_values)\n ),\n update_mask=common_pb2.DocumentMask(field_paths=field_paths),\n current_document=common_pb2.Precondition(exists=True),\n )\n\n def _update_helper(self, **option_kwargs):\n from google.cloud.firestore_v1.transforms import DELETE_FIELD\n\n # Create a minimal fake GAPIC with a dummy response.\n firestore_api = mock.Mock(spec=[\"commit\"])\n firestore_api.commit.return_value = self._make_commit_repsonse()\n\n # Attach the fake GAPIC to a real client.\n client = _make_client(\"potato-chip\")\n client._firestore_api_internal = firestore_api\n\n # Actually make a document and call create().\n document = self._make_one(\"baked\", \"Alaska\", client=client)\n # \"Cheat\" and use OrderedDict-s so that iteritems() is deterministic.\n field_updates = collections.OrderedDict(\n ((\"hello\", 1), (\"then.do\", False), (\"goodbye\", DELETE_FIELD))\n )\n if option_kwargs:\n option = client.write_option(**option_kwargs)\n write_result = document.update(field_updates, option=option)\n else:\n option = None\n write_result = document.update(field_updates)\n\n # Verify the response and the mocks.\n self.assertIs(write_result, mock.sentinel.write_result)\n update_values = {\n \"hello\": field_updates[\"hello\"],\n \"then\": {\"do\": field_updates[\"then.do\"]},\n }\n field_paths = list(field_updates.keys())\n write_pb = self._write_pb_for_update(\n document._document_path, update_values, sorted(field_paths)\n )\n if option is not None:\n option.modify_write(write_pb)\n firestore_api.commit.assert_called_once_with(\n client._database_string,\n [write_pb],\n transaction=None,\n metadata=client._rpc_metadata,\n )\n\n def test_update_with_exists(self):\n with self.assertRaises(ValueError):\n self._update_helper(exists=True)\n\n def test_update(self):\n self._update_helper()\n\n def test_update_with_precondition(self):\n from google.protobuf import timestamp_pb2\n\n timestamp = timestamp_pb2.Timestamp(seconds=1058655101, nanos=100022244)\n self._update_helper(last_update_time=timestamp)\n\n def test_empty_update(self):\n # Create a minimal fake GAPIC with a dummy response.\n firestore_api = mock.Mock(spec=[\"commit\"])\n firestore_api.commit.return_value = self._make_commit_repsonse()\n\n # Attach the fake GAPIC to a real client.\n client = _make_client(\"potato-chip\")\n client._firestore_api_internal = firestore_api\n\n # Actually make a document and call create().\n document = self._make_one(\"baked\", \"Alaska\", client=client)\n # \"Cheat\" and use OrderedDict-s so that iteritems() is deterministic.\n field_updates = {}\n with self.assertRaises(ValueError):\n document.update(field_updates)\n\n def _delete_helper(self, **option_kwargs):\n from google.cloud.firestore_v1.proto import write_pb2\n\n # Create a minimal fake GAPIC with a dummy response.\n firestore_api = mock.Mock(spec=[\"commit\"])\n firestore_api.commit.return_value = self._make_commit_repsonse()\n\n # Attach the fake GAPIC to a real client.\n client = _make_client(\"donut-base\")\n client._firestore_api_internal = firestore_api\n\n # Actually make a document and call delete().\n document = self._make_one(\"where\", \"we-are\", client=client)\n if option_kwargs:\n option = client.write_option(**option_kwargs)\n delete_time = document.delete(option=option)\n else:\n option = None\n delete_time = document.delete()\n\n # Verify the response and the mocks.\n self.assertIs(delete_time, mock.sentinel.commit_time)\n write_pb = write_pb2.Write(delete=document._document_path)\n if option is not None:\n option.modify_write(write_pb)\n firestore_api.commit.assert_called_once_with(\n client._database_string,\n [write_pb],\n transaction=None,\n metadata=client._rpc_metadata,\n )\n\n def test_delete(self):\n self._delete_helper()\n\n def test_delete_with_option(self):\n from google.protobuf import timestamp_pb2\n\n timestamp_pb = timestamp_pb2.Timestamp(seconds=1058655101, nanos=100022244)\n self._delete_helper(last_update_time=timestamp_pb)\n\n def _get_helper(self, field_paths=None, use_transaction=False, not_found=False):\n from google.api_core.exceptions import NotFound\n from google.cloud.firestore_v1.proto import common_pb2\n from google.cloud.firestore_v1.proto import document_pb2\n from google.cloud.firestore_v1.transaction import Transaction\n\n # Create a minimal fake GAPIC with a dummy response.\n create_time = 123\n update_time = 234\n firestore_api = mock.Mock(spec=[\"get_document\"])\n response = mock.create_autospec(document_pb2.Document)\n response.fields = {}\n response.create_time = create_time\n response.update_time = update_time\n\n if not_found:\n firestore_api.get_document.side_effect = NotFound(\"testing\")\n else:\n firestore_api.get_document.return_value = response\n\n client = _make_client(\"donut-base\")\n client._firestore_api_internal = firestore_api\n\n document = self._make_one(\"where\", \"we-are\", client=client)\n\n if use_transaction:\n transaction = Transaction(client)\n transaction_id = transaction._id = b\"asking-me-2\"\n else:\n transaction = None\n\n snapshot = document.get(field_paths=field_paths, transaction=transaction)\n\n self.assertIs(snapshot.reference, document)\n if not_found:\n self.assertIsNone(snapshot._data)\n self.assertFalse(snapshot.exists)\n self.assertIsNone(snapshot.read_time)\n self.assertIsNone(snapshot.create_time)\n self.assertIsNone(snapshot.update_time)\n else:\n self.assertEqual(snapshot.to_dict(), {})\n self.assertTrue(snapshot.exists)\n self.assertIsNone(snapshot.read_time)\n self.assertIs(snapshot.create_time, create_time)\n self.assertIs(snapshot.update_time, update_time)\n\n # Verify the request made to the API\n if field_paths is not None:\n mask = common_pb2.DocumentMask(field_paths=sorted(field_paths))\n else:\n mask = None\n\n if use_transaction:\n expected_transaction_id = transaction_id\n else:\n expected_transaction_id = None\n\n firestore_api.get_document.assert_called_once_with(\n document._document_path,\n mask=mask,\n transaction=expected_transaction_id,\n metadata=client._rpc_metadata,\n )\n\n def test_get_not_found(self):\n self._get_helper(not_found=True)\n\n def test_get_default(self):\n self._get_helper()\n\n def test_get_w_string_field_path(self):\n with self.assertRaises(ValueError):\n self._get_helper(field_paths=\"foo\")\n\n def test_get_with_field_path(self):\n self._get_helper(field_paths=[\"foo\"])\n\n def test_get_with_multiple_field_paths(self):\n self._get_helper(field_paths=[\"foo\", \"bar.baz\"])\n\n def test_get_with_transaction(self):\n self._get_helper(use_transaction=True)\n\n def _collections_helper(self, page_size=None):\n from google.api_core.page_iterator import Iterator\n from google.api_core.page_iterator import Page\n from google.cloud.firestore_v1.collection import CollectionReference\n from google.cloud.firestore_v1.gapic.firestore_client import FirestoreClient\n\n class _Iterator(Iterator):\n def __init__(self, pages):\n super(_Iterator, self).__init__(client=None)\n self._pages = pages\n\n def _next_page(self):\n if self._pages:\n page, self._pages = self._pages[0], self._pages[1:]\n return Page(self, page, self.item_to_value)\n\n collection_ids = [\"coll-1\", \"coll-2\"]\n iterator = _Iterator(pages=[collection_ids])\n api_client = mock.create_autospec(FirestoreClient)\n api_client.list_collection_ids.return_value = iterator\n\n client = _make_client()\n client._firestore_api_internal = api_client\n\n # Actually make a document and call delete().\n document = self._make_one(\"where\", \"we-are\", client=client)\n if page_size is not None:\n collections = list(document.collections(page_size=page_size))\n else:\n collections = list(document.collections())\n\n # Verify the response and the mocks.\n self.assertEqual(len(collections), len(collection_ids))\n for collection, collection_id in zip(collections, collection_ids):\n self.assertIsInstance(collection, CollectionReference)\n self.assertEqual(collection.parent, document)\n self.assertEqual(collection.id, collection_id)\n\n api_client.list_collection_ids.assert_called_once_with(\n document._document_path, page_size=page_size, metadata=client._rpc_metadata\n )\n\n def test_collections_wo_page_size(self):\n self._collections_helper()\n\n def test_collections_w_page_size(self):\n self._collections_helper(page_size=10)\n\n @mock.patch(\"google.cloud.firestore_v1.document.Watch\", autospec=True)\n def test_on_snapshot(self, watch):\n client = mock.Mock(_database_string=\"sprinklez\", spec=[\"_database_string\"])\n document = self._make_one(\"yellow\", \"mellow\", client=client)\n document.on_snapshot(None)\n watch.for_document.assert_called_once()\n\n\nclass TestDocumentSnapshot(unittest.TestCase):\n @staticmethod\n def _get_target_class():\n from google.cloud.firestore_v1.document import DocumentSnapshot\n\n return DocumentSnapshot\n\n def _make_one(self, *args, **kwargs):\n klass = self._get_target_class()\n return klass(*args, **kwargs)\n\n def _make_reference(self, *args, **kwargs):\n from google.cloud.firestore_v1.document import DocumentReference\n\n return DocumentReference(*args, **kwargs)\n\n def _make_w_ref(self, ref_path=(\"a\", \"b\"), data={}, exists=True):\n client = mock.sentinel.client\n reference = self._make_reference(*ref_path, client=client)\n return self._make_one(\n reference,\n data,\n exists,\n mock.sentinel.read_time,\n mock.sentinel.create_time,\n mock.sentinel.update_time,\n )\n\n def test_constructor(self):\n client = mock.sentinel.client\n reference = self._make_reference(\"hi\", \"bye\", client=client)\n data = {\"zoop\": 83}\n snapshot = self._make_one(\n reference,\n data,\n True,\n mock.sentinel.read_time,\n mock.sentinel.create_time,\n mock.sentinel.update_time,\n )\n self.assertIs(snapshot._reference, reference)\n self.assertEqual(snapshot._data, data)\n self.assertIsNot(snapshot._data, data) # Make sure copied.\n self.assertTrue(snapshot._exists)\n self.assertIs(snapshot.read_time, mock.sentinel.read_time)\n self.assertIs(snapshot.create_time, mock.sentinel.create_time)\n self.assertIs(snapshot.update_time, mock.sentinel.update_time)\n\n def test___eq___other_type(self):\n snapshot = self._make_w_ref()\n other = object()\n self.assertFalse(snapshot == other)\n\n def test___eq___different_reference_same_data(self):\n snapshot = self._make_w_ref((\"a\", \"b\"))\n other = self._make_w_ref((\"c\", \"d\"))\n self.assertFalse(snapshot == other)\n\n def test___eq___same_reference_different_data(self):\n snapshot = self._make_w_ref((\"a\", \"b\"))\n other = self._make_w_ref((\"a\", \"b\"), {\"foo\": \"bar\"})\n self.assertFalse(snapshot == other)\n\n def test___eq___same_reference_same_data(self):\n snapshot = self._make_w_ref((\"a\", \"b\"), {\"foo\": \"bar\"})\n other = self._make_w_ref((\"a\", \"b\"), {\"foo\": \"bar\"})\n self.assertTrue(snapshot == other)\n\n def test___hash__(self):\n from google.protobuf import timestamp_pb2\n\n client = mock.MagicMock()\n client.__hash__.return_value = 234566789\n reference = self._make_reference(\"hi\", \"bye\", client=client)\n data = {\"zoop\": 83}\n update_time = timestamp_pb2.Timestamp(seconds=123456, nanos=123456789)\n snapshot = self._make_one(\n reference, data, True, None, mock.sentinel.create_time, update_time\n )\n self.assertEqual(\n hash(snapshot), hash(reference) + hash(123456) + hash(123456789)\n )\n\n def test__client_property(self):\n reference = self._make_reference(\n \"ok\", \"fine\", \"now\", \"fore\", client=mock.sentinel.client\n )\n snapshot = self._make_one(reference, {}, False, None, None, None)\n self.assertIs(snapshot._client, mock.sentinel.client)\n\n def test_exists_property(self):\n reference = mock.sentinel.reference\n\n snapshot1 = self._make_one(reference, {}, False, None, None, None)\n self.assertFalse(snapshot1.exists)\n snapshot2 = self._make_one(reference, {}, True, None, None, None)\n self.assertTrue(snapshot2.exists)\n\n def test_id_property(self):\n document_id = \"around\"\n reference = self._make_reference(\n \"look\", document_id, client=mock.sentinel.client\n )\n snapshot = self._make_one(reference, {}, True, None, None, None)\n self.assertEqual(snapshot.id, document_id)\n self.assertEqual(reference.id, document_id)\n\n def test_reference_property(self):\n snapshot = self._make_one(mock.sentinel.reference, {}, True, None, None, None)\n self.assertIs(snapshot.reference, mock.sentinel.reference)\n\n def test_get(self):\n data = {\"one\": {\"bold\": \"move\"}}\n snapshot = self._make_one(None, data, True, None, None, None)\n\n first_read = snapshot.get(\"one\")\n second_read = snapshot.get(\"one\")\n self.assertEqual(first_read, data.get(\"one\"))\n self.assertIsNot(first_read, data.get(\"one\"))\n self.assertEqual(first_read, second_read)\n self.assertIsNot(first_read, second_read)\n\n with self.assertRaises(KeyError):\n snapshot.get(\"two\")\n\n def test_nonexistent_snapshot(self):\n snapshot = self._make_one(None, None, False, None, None, None)\n self.assertIsNone(snapshot.get(\"one\"))\n\n def test_to_dict(self):\n data = {\"a\": 10, \"b\": [\"definitely\", \"mutable\"], \"c\": {\"45\": 50}}\n snapshot = self._make_one(None, data, True, None, None, None)\n as_dict = snapshot.to_dict()\n self.assertEqual(as_dict, data)\n self.assertIsNot(as_dict, data)\n # Check that the data remains unchanged.\n as_dict[\"b\"].append(\"hi\")\n self.assertEqual(data, snapshot.to_dict())\n self.assertNotEqual(data, as_dict)\n\n def test_non_existent(self):\n snapshot = self._make_one(None, None, False, None, None, None)\n as_dict = snapshot.to_dict()\n self.assertIsNone(as_dict)\n\n\nclass Test__get_document_path(unittest.TestCase):\n @staticmethod\n def _call_fut(client, path):\n from google.cloud.firestore_v1.document import _get_document_path\n\n return _get_document_path(client, path)\n\n def test_it(self):\n project = \"prah-jekt\"\n client = _make_client(project=project)\n path = (\"Some\", \"Document\", \"Child\", \"Shockument\")\n document_path = self._call_fut(client, path)\n\n expected = \"projects/{}/databases/{}/documents/{}\".format(\n project, client._database, \"/\".join(path)\n )\n self.assertEqual(document_path, expected)\n\n\nclass Test__consume_single_get(unittest.TestCase):\n @staticmethod\n def _call_fut(response_iterator):\n from google.cloud.firestore_v1.document import _consume_single_get\n\n return _consume_single_get(response_iterator)\n\n def test_success(self):\n response_iterator = iter([mock.sentinel.result])\n result = self._call_fut(response_iterator)\n self.assertIs(result, mock.sentinel.result)\n\n def test_failure_not_enough(self):\n response_iterator = iter([])\n with self.assertRaises(ValueError):\n self._call_fut(response_iterator)\n\n def test_failure_too_many(self):\n response_iterator = iter([None, None])\n with self.assertRaises(ValueError):\n self._call_fut(response_iterator)\n\n\nclass Test__first_write_result(unittest.TestCase):\n @staticmethod\n def _call_fut(write_results):\n from google.cloud.firestore_v1.document import _first_write_result\n\n return _first_write_result(write_results)\n\n def test_success(self):\n from google.protobuf import timestamp_pb2\n from google.cloud.firestore_v1.proto import write_pb2\n\n single_result = write_pb2.WriteResult(\n update_time=timestamp_pb2.Timestamp(seconds=1368767504, nanos=458000123)\n )\n write_results = [single_result]\n result = self._call_fut(write_results)\n self.assertIs(result, single_result)\n\n def test_failure_not_enough(self):\n write_results = []\n with self.assertRaises(ValueError):\n self._call_fut(write_results)\n\n def test_more_than_one(self):\n from google.cloud.firestore_v1.proto import write_pb2\n\n result1 = write_pb2.WriteResult()\n result2 = write_pb2.WriteResult()\n write_results = [result1, result2]\n result = self._call_fut(write_results)\n self.assertIs(result, result1)\n\n\ndef _make_credentials():\n import google.auth.credentials\n\n return mock.Mock(spec=google.auth.credentials.Credentials)\n\n\ndef _make_client(project=\"project-project\"):\n from google.cloud.firestore_v1.client import Client\n\n credentials = _make_credentials()\n return Client(project=project, credentials=credentials)\n", "sub_path": "firestore/tests/unit/v1/test_document.py", "file_name": "test_document.py", "file_ext": "py", "file_size_in_byte": 31704, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "unittest.TestCase", "line_number": 21, "usage_type": "attribute"}, {"api_name": "google.cloud.firestore_v1.document.DocumentReference", "line_number": 26, "usage_type": "name"}, {"api_name": "mock.MagicMock", "line_number": 37, "usage_type": "call"}, {"api_name": "mock.sentinel", "line_number": 79, "usage_type": "attribute"}, {"api_name": "mock.Mock", "line_number": 81, "usage_type": "call"}, {"api_name": "mock.sentinel", "line_number": 81, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 85, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 89, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 90, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 91, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 92, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 105, "usage_type": "attribute"}, {"api_name": "mock.MagicMock", "line_number": 112, "usage_type": "call"}, {"api_name": "mock.sentinel", "line_number": 118, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 119, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 120, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 121, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 133, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 153, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 154, "usage_type": "attribute"}, {"api_name": "google.cloud.firestore_v1.collection.CollectionReference", "line_number": 178, "usage_type": "name"}, {"api_name": "google.cloud.firestore_v1.collection.CollectionReference", "line_number": 192, "usage_type": "name"}, {"api_name": "google.cloud.firestore_v1.proto.write_pb2.Write", "line_number": 203, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.proto.write_pb2", "line_number": 203, "usage_type": "name"}, {"api_name": "google.cloud.firestore_v1.proto.document_pb2.Document", "line_number": 204, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.proto.document_pb2", "line_number": 204, "usage_type": "name"}, {"api_name": "google.cloud.firestore_v1._helpers.encode_dict", "line_number": 205, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1._helpers", "line_number": 205, "usage_type": "name"}, {"api_name": "google.cloud.firestore_v1.proto.common_pb2.Precondition", "line_number": 207, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.proto.common_pb2", "line_number": 207, "usage_type": "name"}, {"api_name": "mock.create_autospec", "line_number": 214, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.proto.firestore_pb2.CommitResponse", "line_number": 214, "usage_type": "attribute"}, {"api_name": "google.cloud.firestore_v1.proto.firestore_pb2", "line_number": 214, "usage_type": "name"}, {"api_name": "mock.sentinel", "line_number": 215, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 216, "usage_type": "attribute"}, {"api_name": "mock.Mock", "line_number": 221, "usage_type": "call"}, {"api_name": "mock.sentinel", "line_number": 234, "usage_type": "attribute"}, {"api_name": "mock.Mock", "line_number": 248, "usage_type": "call"}, {"api_name": "mock.create_autospec", "line_number": 249, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.document.DocumentReference", "line_number": 249, "usage_type": "name"}, {"api_name": "mock.create_autospec", "line_number": 250, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.document.DocumentSnapshot", "line_number": 250, "usage_type": "name"}, {"api_name": "mock.MagicMock", "line_number": 260, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.proto.write_pb2.Write", "line_number": 276, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.proto.write_pb2", "line_number": 276, "usage_type": "name"}, {"api_name": "google.cloud.firestore_v1.proto.document_pb2.Document", "line_number": 277, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.proto.document_pb2", "line_number": 277, "usage_type": "name"}, {"api_name": "google.cloud.firestore_v1._helpers.encode_dict", "line_number": 278, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1._helpers", "line_number": 278, "usage_type": "name"}, {"api_name": "google.cloud.firestore_v1._helpers.extract_fields", "line_number": 284, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1._helpers", "line_number": 284, "usage_type": "name"}, {"api_name": "google.cloud.firestore_v1._helpers.FieldPath", "line_number": 285, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1._helpers", "line_number": 285, "usage_type": "name"}, {"api_name": "google.cloud.firestore_v1.proto.common_pb2.DocumentMask", "line_number": 291, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.proto.common_pb2", "line_number": 291, "usage_type": "name"}, {"api_name": "mock.Mock", "line_number": 297, "usage_type": "call"}, {"api_name": "mock.sentinel", "line_number": 310, "usage_type": "attribute"}, {"api_name": "google.cloud.firestore_v1.proto.write_pb2.Write", "line_number": 333, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.proto.write_pb2", "line_number": 333, "usage_type": "name"}, {"api_name": "google.cloud.firestore_v1.proto.document_pb2.Document", "line_number": 334, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.proto.document_pb2", "line_number": 334, "usage_type": "name"}, {"api_name": "google.cloud.firestore_v1._helpers.encode_dict", "line_number": 335, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1._helpers", "line_number": 335, "usage_type": "name"}, {"api_name": "google.cloud.firestore_v1.proto.common_pb2.DocumentMask", "line_number": 337, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.proto.common_pb2", "line_number": 337, "usage_type": "name"}, {"api_name": "google.cloud.firestore_v1.proto.common_pb2.Precondition", "line_number": 338, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.proto.common_pb2", "line_number": 338, "usage_type": "name"}, {"api_name": "mock.Mock", "line_number": 345, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 355, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.transforms.DELETE_FIELD", "line_number": 356, "usage_type": "name"}, {"api_name": "mock.sentinel", "line_number": 366, "usage_type": "attribute"}, {"api_name": "google.protobuf.timestamp_pb2.Timestamp", "line_number": 394, "usage_type": "call"}, {"api_name": "google.protobuf.timestamp_pb2", "line_number": 394, "usage_type": "name"}, {"api_name": "mock.Mock", "line_number": 399, "usage_type": "call"}, {"api_name": "mock.Mock", "line_number": 417, "usage_type": "call"}, {"api_name": "mock.sentinel", "line_number": 434, "usage_type": "attribute"}, {"api_name": "google.cloud.firestore_v1.proto.write_pb2.Write", "line_number": 435, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.proto.write_pb2", "line_number": 435, "usage_type": "name"}, {"api_name": "google.protobuf.timestamp_pb2.Timestamp", "line_number": 451, "usage_type": "call"}, {"api_name": "google.protobuf.timestamp_pb2", "line_number": 451, "usage_type": "name"}, {"api_name": "mock.Mock", "line_number": 463, "usage_type": "call"}, {"api_name": "mock.create_autospec", "line_number": 464, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.proto.document_pb2.Document", "line_number": 464, "usage_type": "attribute"}, {"api_name": "google.cloud.firestore_v1.proto.document_pb2", "line_number": 464, "usage_type": "name"}, {"api_name": "google.api_core.exceptions.NotFound", "line_number": 470, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.transaction.Transaction", "line_number": 480, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.proto.common_pb2.DocumentMask", "line_number": 503, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.proto.common_pb2", "line_number": 503, "usage_type": "name"}, {"api_name": "mock.create_autospec", "line_number": 556, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.gapic.firestore_client.FirestoreClient", "line_number": 556, "usage_type": "name"}, {"api_name": "google.cloud.firestore_v1.collection.CollectionReference", "line_number": 572, "usage_type": "name"}, {"api_name": "mock.Mock", "line_number": 588, "usage_type": "call"}, {"api_name": "mock.patch", "line_number": 586, "usage_type": "call"}, {"api_name": "unittest.TestCase", "line_number": 594, "usage_type": "attribute"}, {"api_name": "google.cloud.firestore_v1.document.DocumentSnapshot", "line_number": 599, "usage_type": "name"}, {"api_name": "google.cloud.firestore_v1.document.DocumentReference", "line_number": 608, "usage_type": "call"}, {"api_name": "mock.sentinel", "line_number": 611, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 617, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 618, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 619, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 623, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 630, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 631, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 632, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 638, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 639, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 640, "usage_type": "attribute"}, {"api_name": "mock.MagicMock", "line_number": 665, "usage_type": "call"}, {"api_name": "google.protobuf.timestamp_pb2.Timestamp", "line_number": 669, "usage_type": "call"}, {"api_name": "google.protobuf.timestamp_pb2", "line_number": 669, "usage_type": "name"}, {"api_name": "mock.sentinel", "line_number": 671, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 679, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 682, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 685, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 695, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 702, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 703, "usage_type": "attribute"}, {"api_name": "unittest.TestCase", "line_number": 740, "usage_type": "attribute"}, {"api_name": "google.cloud.firestore_v1.document._get_document_path", "line_number": 745, "usage_type": "call"}, {"api_name": "unittest.TestCase", "line_number": 759, "usage_type": "attribute"}, {"api_name": "google.cloud.firestore_v1.document._consume_single_get", "line_number": 764, "usage_type": "call"}, {"api_name": "mock.sentinel", "line_number": 767, "usage_type": "attribute"}, {"api_name": "mock.sentinel", "line_number": 769, "usage_type": "attribute"}, {"api_name": "unittest.TestCase", "line_number": 782, "usage_type": "attribute"}, {"api_name": "google.cloud.firestore_v1.document._first_write_result", "line_number": 787, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.proto.write_pb2.WriteResult", "line_number": 793, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.proto.write_pb2", "line_number": 793, "usage_type": "name"}, {"api_name": "google.protobuf.timestamp_pb2.Timestamp", "line_number": 794, "usage_type": "call"}, {"api_name": "google.protobuf.timestamp_pb2", "line_number": 794, "usage_type": "name"}, {"api_name": "google.cloud.firestore_v1.proto.write_pb2.WriteResult", "line_number": 808, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.proto.write_pb2", "line_number": 808, "usage_type": "name"}, {"api_name": "google.cloud.firestore_v1.proto.write_pb2.WriteResult", "line_number": 809, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.proto.write_pb2", "line_number": 809, "usage_type": "name"}, {"api_name": "mock.Mock", "line_number": 818, "usage_type": "call"}, {"api_name": "google.cloud.firestore_v1.document.auth", "line_number": 818, "usage_type": "attribute"}, {"api_name": "google.cloud.firestore_v1.document", "line_number": 818, "usage_type": "name"}, {"api_name": "google.cloud.firestore_v1.client.Client", "line_number": 825, "usage_type": "call"}]}
+{"seq_id": "398947161", "text": "'''\nThis file is the starting point of this flash server.\n\nApenx:\n @@ means todo\n\n'''\n\nfrom flask import Flask, request, jsonify, after_this_request, render_template\nimport tldextract # to extract the domain name from url\nimport whois\nimport geocoder\nimport pycountry\nfrom geopy.geocoders import Nominatim\nimport requests\nimport json\nimport time\nfrom datetime import datetime\n\nimport controller.alexa as alexa\nimport controller.blazeGraph as blazegraph\nimport controller.dbpedia as dbpedia\nimport controller.privacyMetrics as privacyMetrics\n\n# from OpenSSL import SSL\n# context = SSL.Context(SSL.PROTOCOL_TLSv1_2)\n# context.use_privatekey_file('server.key')\n# context.use_certificate_file('server.crt')\n\napp = Flask(__name__)\n#app.run('127.0.0.1', debug=True, port=5000, ssl_context=context)\n\n@app.route('/')\ndef index():\n blazegraph.baseRules()\n return \"privary matters :) \\n The basic rules are set in your RDF Triple store.\"\n\n@app.route('/privacyMetric', methods=['GET', 'POST'])\ndef privacyMetric():\n \n @after_this_request\n def add_header(response):\n response.headers.add('Access-Control-Allow-Origin', '*')\n return response\n\n # variable initialise\n userInfo = {}\n\n # get domain name from url ======= \n url = request.form.get(\"url\")\n protocol = url.split(':')[0]\n urlInfo = tldextract.extract(url)\n domain = urlInfo.domain +'.' + urlInfo.suffix\n\n if protocol == \"chrome-extension\":\n return jsonify({'privacyScore': 0, 'reasonForPrivacyScore': \"This webpage is completely safe.\", \"websiteType\":\"privacyProtection\"})\n\n print(\"protocol: \", protocol)\n\n # get data from request\n userInfo['domainVisitCount'] = int(request.form.get(\"domainVisitCount\"))\n\n # get user profile\n userProfile = request.form.get(\"userProfile\")\n userInfo['userProfile'] = json.loads(userProfile)\n print(\"UserProfile: \", request.form.get(\"userProfile\"))\n\n # initialising privacyScore Variable\n privacyScore = 0\n\n # flags\n calledWhois = False\n\n if domain not in ['localhost.']:\n # get user location from userLocation ======\n userLocationLat = request.form.get(\"userLocationLat\")\n userLocationLong = request.form.get(\"userLocationLong\")\n print(userLocationLat)\n print(userLocationLong)\n\n g = geocoder.osm([userLocationLat, userLocationLong], method='reverse')\n geocoderTriedNum = 0\n while g is None or geocoderTriedNum < 5:\n time.sleep(2)\n g = geocoder.osm([userLocationLat, userLocationLong], method='reverse')\n geocoderTriedNum += 1\n print(g.json['country'])\n userInfo['websitevisitedcountry'] = g.json['country']\n # check user's country is present in the dbpedia\n if dbpedia.IsInfoInDBPedia(userInfo['websitevisitedcountry']):\n userInfo['websitevisitedcountry'] = userInfo['websitevisitedcountry']\n\n print(domain)\n\n # check domain is present in the our graph\n objectIsPresent = blazegraph.checkForSubject(domain)\n comp_info_score = []\n\n # if not present, add info to that graph\n isPresentInDBPedia = False\n # get domain information using alexa api\n if objectIsPresent == False:\n comp_info = alexa.alexa(domain)\n \n comp_info = list(comp_info)\n # check if the website creation date is present\n if comp_info[7] == 'NaN':\n # get expiration date using whois\n websiteInfoFromWhoIs = whois.whois(domain)\n print(\"websiteInfoFromWhoIs:@: \",websiteInfoFromWhoIs)\n calledWhois = True\n if isinstance(websiteInfoFromWhoIs.creation_date, list):\n print(\"websiteDate1:\")\n comp_info[7] = datetime.strftime(websiteInfoFromWhoIs.creation_date[1], \"%Y-%m-%d %H:%M:%S\")\n else:\n print(\"websiteDate2:\")\n comp_info[7] = datetime.strftime(websiteInfoFromWhoIs.creation_date, \"%Y-%m-%d %H:%M:%S\")\n \n # to add create info into rdf.\n blazegraph.add_companyInfo(comp_info)\n\n # delete if NaN is present\n blazegraph.deleteNaN()\n \n # get complete URL and connect with DBPedia\n # check info is present in DBPedia\n comp_info[1] = comp_info[1].replace('/', '')\n comp_info[1] = comp_info[1].replace(' ', '_')\n isPresentInDBPedia = dbpedia.IsInfoInDBPedia(comp_info[1]) \n print(\"isPresentInDBPedia:\", isPresentInDBPedia)\n \n if isPresentInDBPedia:\n print(\"same\")\n # get company name \n #companyTitle = blazegraph.getCompanyName(domain)\n blazegraph.sameAs(domain, comp_info[1])\n\n # get company location information from dbpedia\n companyLoc = dbpedia.getCompanyLocation(comp_info[1])\n \n if companyLoc != None:\n # convert company location into country\n geoLocator = Nominatim(user_agent=\"privacyProtection\")\n companyLocForGeoCoder = companyLoc.split('/')[-1]\n location = geoLocator.geocode(companyLocForGeoCoder)\n geocoderTriedNum2 = 0\n while location is None or geocoderTriedNum2 < 5:\n time.sleep(2)\n location = geoLocator.geocode(companyLocForGeoCoder)\n geocoderTriedNum2 += 1\n companyLoc = location.raw['display_name'].split(\" \")[-1]\n print(\"location country 222\", companyLoc)\n \n if isPresentInDBPedia == False or companyLoc == None:\n # get website domain reg. location using whois\n if calledWhois == False:\n # get expiration location using whois\n websiteInfoFromWhoIs = whois.whois(domain)\n \n # websiteDomainCity = websiteInfoFromWhoIs.city\n # if websiteDomainCity != None: \n # print(\"Company location in app @1@: \", websiteInfoFromWhoIs)\n # companyLoc = websiteDomainCity.replace(\" \", \"_\")\n # else:\n websiteDomainCountry = websiteInfoFromWhoIs.country\n companyLoc = pycountry.countries.get(alpha_2=websiteDomainCountry)\n if companyLoc == None:\n companyLoc = \"NaN\"\n else:\n companyLoc = companyLoc.name\n companyLoc = companyLoc.replace(\" \", \"_\")\n\n # get company information from dbpedia\n print(\"Company location in app @@: \", companyLoc)\n comp_info.append(companyLoc)\n blazegraph.addCompanyLocation(domain, comp_info[8])\n print(\"companyLoc: \", comp_info[8])\n\n # add website protocol info to calculate privacy score\n comp_info.append(protocol)\n comp_info_score = comp_info \n # --------\n else:\n # get company information from our triple store\n comp_info = blazegraph.getCompanyInfoInFormat(subject_m=domain)\n print(\"Company's information: \",comp_info)\n comp_info.append(protocol)\n comp_info_score = comp_info\n\n # get privacy score based on company Info @@to-do send this data to the client\n privacyScore, reasonForPrivacyScore = privacyMetrics.calculatePrivacyScore(comp_info, userInfo)\n print(\"comp_info[4]\", comp_info[4])\n if comp_info[4] is not None and comp_info[4] is not \"NaN\":\n websiteType = comp_info[4].split('/')[0]\n else:\n websiteType = \"others\"\n\n print(\"privacyRiskScore :\", privacyScore)\n print(\"reasonForPrivacyScore :\", reasonForPrivacyScore)\n print(\"websiteType :\", websiteType)\n\n return jsonify({'privacyRiskScore': privacyScore, 'reasonForPrivacyScore': reasonForPrivacyScore, \"websiteType\":websiteType })\n\n################################################################################################\n@app.route('/getRDF', methods=['GET','POST'])\ndef getRDF():\n print(\"RDF\")\n @after_this_request\n def add_header(response):\n response.headers.add('Access-Control-Allow-Origin', '*')\n return response\n\n res = blazegraph.select_all()\n return jsonify(res)\n\n\n################################################################################################\n@app.route('/userProfile', methods=['GET','POST'])\ndef getUserProfile():\n @after_this_request\n def add_header(response):\n response.headers.add('Access-Control-Allow-Origin', '*')\n return response\n \n LinkedInAUTHCode = request.args.get('code')\n\n print(LinkedInAUTHCode)\n\n res = requests.post(\"https://www.linkedin.com/oauth/v2/accessToken?grant_type=authorization_code&code=\"+ LinkedInAUTHCode + \"&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2FuserProfile&client_id=77mpeeyrvnkjaa&client_secret=loIraKqPvMjE9fOe\",\n headers = {\n \"content-type\": \"x-www-form-urlencoded\"\n })\n \n\n if res.ok:\n print('Access_token', res.json())\n linkedInAccessToken = res.json()['access_token']\n linkedInAccessTokenExpiresIn = res.json()['expires_in'] # @@todo time + expiresIn\n else:\n print(res.json())\n\n res1 = requests.get(\"https://api.linkedin.com/v2/me\",\n headers = {\n \"Authorization\": \"Bearer \" + linkedInAccessToken,\n \"connection\" : \"Keep-Alive\"\n })\n\n if res1.ok:\n print('Access_token', res1.json())\n else:\n print(res1.json())\n\n #return render_template('userProfile.html')\n return 'OK'\n\nif __name__ == \"__main__\": \n app.run(debug=True)", "sub_path": "backend/app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 9891, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "flask.Flask", "line_number": 30, "usage_type": "call"}, {"api_name": "controller.blazeGraph.baseRules", "line_number": 35, "usage_type": "call"}, {"api_name": "controller.blazeGraph", "line_number": 35, "usage_type": "name"}, {"api_name": "flask.after_this_request", "line_number": 41, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 50, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 50, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 50, "usage_type": "name"}, {"api_name": "tldextract.extract", "line_number": 52, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 56, "usage_type": "call"}, {"api_name": "flask.request.form.get", "line_number": 61, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 61, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 61, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 64, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 64, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 64, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 65, "usage_type": "call"}, {"api_name": "flask.request.form.get", "line_number": 66, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 66, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 66, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 76, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 76, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 76, "usage_type": "name"}, {"api_name": "flask.request.form.get", "line_number": 77, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 77, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 77, "usage_type": "name"}, {"api_name": "geocoder.osm", "line_number": 81, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 84, "usage_type": "call"}, {"api_name": "geocoder.osm", "line_number": 85, "usage_type": "call"}, {"api_name": "controller.dbpedia.IsInfoInDBPedia", "line_number": 90, "usage_type": "call"}, {"api_name": "controller.dbpedia", "line_number": 90, "usage_type": "name"}, {"api_name": "controller.blazeGraph.checkForSubject", "line_number": 96, "usage_type": "call"}, {"api_name": "controller.blazeGraph", "line_number": 96, "usage_type": "name"}, {"api_name": "controller.alexa.alexa", "line_number": 103, "usage_type": "call"}, {"api_name": "controller.alexa", "line_number": 103, "usage_type": "name"}, {"api_name": "whois.whois", "line_number": 109, "usage_type": "call"}, {"api_name": "datetime.datetime.strftime", "line_number": 114, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 114, "usage_type": "name"}, {"api_name": "datetime.datetime.strftime", "line_number": 117, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 117, "usage_type": "name"}, {"api_name": "controller.blazeGraph.add_companyInfo", "line_number": 120, "usage_type": "call"}, {"api_name": "controller.blazeGraph", "line_number": 120, "usage_type": "name"}, {"api_name": "controller.blazeGraph.deleteNaN", "line_number": 123, "usage_type": "call"}, {"api_name": "controller.blazeGraph", "line_number": 123, "usage_type": "name"}, {"api_name": "controller.dbpedia.IsInfoInDBPedia", "line_number": 129, "usage_type": "call"}, {"api_name": "controller.dbpedia", "line_number": 129, "usage_type": "name"}, {"api_name": "controller.blazeGraph.sameAs", "line_number": 136, "usage_type": "call"}, {"api_name": "controller.blazeGraph", "line_number": 136, "usage_type": "name"}, {"api_name": "controller.dbpedia.getCompanyLocation", "line_number": 139, "usage_type": "call"}, {"api_name": "controller.dbpedia", "line_number": 139, "usage_type": "name"}, {"api_name": "geopy.geocoders.Nominatim", "line_number": 143, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 148, "usage_type": "call"}, {"api_name": "whois.whois", "line_number": 158, "usage_type": "call"}, {"api_name": "pycountry.countries.get", "line_number": 166, "usage_type": "call"}, {"api_name": "pycountry.countries", "line_number": 166, "usage_type": "attribute"}, {"api_name": "controller.blazeGraph.addCompanyLocation", "line_number": 176, "usage_type": "call"}, {"api_name": "controller.blazeGraph", "line_number": 176, "usage_type": "name"}, {"api_name": "controller.blazeGraph.getCompanyInfoInFormat", "line_number": 185, "usage_type": "call"}, {"api_name": "controller.blazeGraph", "line_number": 185, "usage_type": "name"}, {"api_name": "controller.privacyMetrics.calculatePrivacyScore", "line_number": 191, "usage_type": "call"}, {"api_name": "controller.privacyMetrics", "line_number": 191, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 202, "usage_type": "call"}, {"api_name": "flask.after_this_request", "line_number": 208, "usage_type": "name"}, {"api_name": "controller.blazeGraph.select_all", "line_number": 213, "usage_type": "call"}, {"api_name": "controller.blazeGraph", "line_number": 213, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 214, "usage_type": "call"}, {"api_name": "flask.after_this_request", "line_number": 220, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 225, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 225, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 225, "usage_type": "name"}, {"api_name": "requests.post", "line_number": 229, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 242, "usage_type": "call"}]}
+{"seq_id": "281391442", "text": "import io\nimport copy\nimport _pickle as cPickle\nimport logging\nfrom pathlib import Path\nfrom typing import List, Dict, Set, Optional, Iterator, Union, TextIO\nfrom collections import OrderedDict\n\nfrom pyknp import BList, Bunsetsu, Tag, Morpheme, Rel\nimport jaconv\n\nfrom kyoto_reader.pas import Pas, Predicate, BaseArgument, Argument, SpecialArgument\nfrom kyoto_reader.coreference import Mention, Entity\nfrom kyoto_reader.ne import NamedEntity\nfrom kyoto_reader.constants import ALL_CASES, CORE_CASES, ALL_EXOPHORS, ALL_COREFS, CORE_COREFS, NE_CATEGORIES\nfrom kyoto_reader.base_phrase import BasePhrase\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.WARNING)\n\n\nclass KyotoReader:\n \"\"\" KWDLC(または Kyoto Corpus)の文書集合を扱うクラス\n\n Args:\n source (Union[Path, str]): 入力ソース.Path オブジェクトを指定するとその場所のファイルを読む\n target_cases (Optional[List[str]]): 抽出の対象とする格\n target_corefs (Optional[List[str]]): 抽出の対象とする共参照関係(=など)\n relax_cases (bool): ガ≒格などをガ格として扱うか\n extract_nes (bool): 固有表現をコーパスから抽出するかどうか\n knp_ext (str): KWDLC または KC ファイルの拡張子\n pickle_ext (str): Document を pickle 形式で読む場合の拡張子\n use_pas_tag (bool): タグからではなく、<述語項構造:>タグから PAS を読むかどうか\n \"\"\"\n def __init__(self,\n source: Union[Path, str],\n target_cases: Optional[List[str]],\n target_corefs: Optional[List[str]],\n relax_cases: bool = False,\n extract_nes: bool = True,\n use_pas_tag: bool = False,\n knp_ext: str = '.knp',\n pickle_ext: str = '.pkl',\n ) -> None:\n if not (isinstance(source, Path) or isinstance(source, str)):\n raise TypeError(f'source must be Path or str type, but got {type(source)}')\n if isinstance(source, Path):\n if source.is_dir():\n logger.info(f'got directory path, files in the directory is treated as source files')\n file_paths: List[Path] = \\\n sorted(source.glob(f'**/*{knp_ext}')) + sorted(source.glob(f'**/*{pickle_ext}'))\n self.did2source: Dict[str, Union[Path, str]] = OrderedDict((path.stem, path) for path in file_paths)\n else:\n logger.info(f'got file path, this file is treated as a source knp file')\n self.did2source: Dict[str, Union[Path, str]] = {source.stem: source}\n else:\n logger.info(f'got string, this string is treated as a source knp string')\n self.did2source: Dict[str, Union[Path, str]] = {'doc': source}\n\n self.target_cases: List[str] = self._get_target(target_cases, ALL_CASES, CORE_CASES, 'case')\n self.target_corefs: List[str] = self._get_target(target_corefs, ALL_COREFS, CORE_COREFS, 'coref')\n self.relax_cases: bool = relax_cases\n self.extract_nes: bool = extract_nes\n self.use_pas_tag: bool = use_pas_tag\n self.knp_ext: str = knp_ext\n self.pickle_ext: str = pickle_ext\n\n @staticmethod\n def _get_target(input_: Optional[list],\n all_: list,\n default: list,\n type_: str,\n ) -> list:\n if input_ is None:\n return default\n target = []\n for item in input_:\n if item not in all_:\n logger.warning(f'unknown target {type_}: {item}')\n continue\n target.append(item)\n\n return target\n\n def get_doc_ids(self) -> List[str]:\n return list(self.did2source.keys())\n\n def process_document(self, doc_id: str) -> Optional['Document']:\n if doc_id not in self.did2source:\n logger.error(f'unknown document id: {doc_id}')\n return None\n if isinstance(self.did2source[doc_id], Path):\n if self.did2source[doc_id].suffix == self.pickle_ext:\n with self.did2source[doc_id].open(mode='rb') as f:\n return cPickle.load(f)\n elif self.did2source[doc_id].suffix == self.knp_ext:\n with self.did2source[doc_id].open() as f:\n input_string = f.read()\n else:\n return None\n else:\n input_string = self.did2source[doc_id]\n return Document(input_string,\n doc_id,\n self.target_cases,\n self.target_corefs,\n self.relax_cases,\n self.extract_nes,\n self.use_pas_tag)\n\n def process_documents(self, doc_ids: List[str]) -> Iterator[Optional['Document']]:\n for doc_id in doc_ids:\n yield self.process_document(doc_id)\n\n def process_all_documents(self) -> Iterator['Document']:\n for doc_id in self.did2source.keys():\n yield self.process_document(doc_id)\n\n\nclass Document:\n \"\"\" KWDLC(または Kyoto Corpus)の1文書を扱うクラス\n\n Args:\n knp_string (str): 文書ファイルの内容(knp形式)\n doc_id (str): 文書ID\n cases (List[str]): 抽出の対象とする格\n corefs (List[str]): 抽出の対象とする共参照関係(=など)\n relax_cases (bool): ガ≒格などをガ格として扱うか\n extract_nes (bool): 固有表現をコーパスから抽出するかどうか\n use_pas_tag (bool): タグからではなく、<述語項構造:>タグから PAS を読むかどうか\n\n Attributes:\n knp_string (str): 文書ファイルの内容(knp形式)\n doc_id (str): 文書ID(ファイル名から拡張子を除いたもの)\n cases (List[str]): 抽出の対象とする格\n corefs (List[str]): 抽出の対象とする共参照関係(=など)\n extract_nes (bool): 固有表現をコーパスから抽出するかどうか\n sid2sentence (dict): 文IDと文を紐付ける辞書\n bnst2dbid (dict): 文節IDと文書レベルの文節IDを紐付ける辞書\n tag2dtid (dict): 基本句IDと文書レベルの基本句IDを紐付ける辞書\n mrph2dmid (dict): 形態素IDと文書レベルの形態素IDを紐付ける辞書\n mentions (dict): dtid を key とする mention の辞書\n entities (dict): entity id を key として entity オブジェクトが格納されている\n named_entities (list): 抽出した固有表現\n \"\"\"\n def __init__(self,\n knp_string: str,\n doc_id: str,\n cases: List[str],\n corefs: List[str],\n relax_cases: bool,\n extract_nes: bool,\n use_pas_tag: bool,\n ) -> None:\n self.knp_string: str = knp_string\n self.doc_id: str = doc_id\n self.cases: List[str] = cases\n self.corefs: List[str] = corefs\n self.relax_cases: bool = relax_cases\n self.extract_nes: bool = extract_nes\n self.use_pas_tag: bool = use_pas_tag\n\n self.sid2sentence: Dict[str, BList] = OrderedDict()\n buff = []\n for line in knp_string.strip().split('\\n'):\n buff.append(line)\n if line.strip() == 'EOS':\n sentence = BList('\\n'.join(buff) + '\\n')\n if sentence.sid in self.sid2sentence:\n logger.warning(f'{sentence.sid:24}duplicated sid found')\n self.sid2sentence[sentence.sid] = sentence\n buff = []\n\n self.bnst2dbid = {}\n self.tag2dtid = {}\n self.mrph2dmid = {}\n self._assign_document_wide_id()\n\n self._pas: Dict[int, Pas] = OrderedDict()\n self.mentions: Dict[int, Mention] = OrderedDict()\n self.entities: Dict[int, Entity] = OrderedDict()\n if use_pas_tag:\n self._analyze_pas()\n else:\n self._analyze_rel()\n\n if extract_nes:\n self.named_entities: List[NamedEntity] = []\n self._extract_nes()\n\n def _assign_document_wide_id(self) -> None:\n \"\"\"文節・基本句・形態素に文書全体に渡る通し番号を振る\"\"\"\n dbid, dtid, dmid = 0, 0, 0\n for sentence in self.sentences:\n for bnst in sentence.bnst_list():\n for tag in bnst.tag_list():\n for mrph in tag.mrph_list():\n self.mrph2dmid[mrph] = dmid\n dmid += 1\n self.tag2dtid[tag] = dtid\n dtid += 1\n self.bnst2dbid[bnst] = dbid\n dbid += 1\n\n def _analyze_pas(self) -> None:\n \"\"\"extract predicate argument structure from <述語項構造:> tag in knp string\"\"\"\n sid2idx = {sid: idx for idx, sid in enumerate(self.sid2sentence.keys())}\n for tag in self.tag_list():\n if tag.pas is None:\n continue\n pas = Pas(BasePhrase(tag, self.tag2dtid[tag], tag.pas.sid, self.mrph2dmid), self.mrph2dmid)\n for case, arguments in tag.pas.arguments.items():\n if self.relax_cases:\n if case in ALL_CASES and case.endswith('≒'):\n case = case.rstrip('≒') # ガ≒ -> ガ\n for arg in arguments:\n arg.midasi = jaconv.h2z(arg.midasi, digit=True) # 不特定:人1 -> 不特定:人1\n # exophor\n if arg.flag == 'E':\n entity = self._create_entity(exophor=arg.midasi, eid=arg.eid)\n pas.add_special_argument(case, arg.midasi, entity.eid, '')\n else:\n sid = self.sentences[sid2idx[arg.sid] - arg.sdist].sid\n arg_bp = self._get_bp(sid, arg.tid)\n mention = self._create_mention(arg_bp)\n pas.add_argument(case, mention, '', self.mrph2dmid)\n if pas.arguments:\n self._pas[pas.dtid] = pas\n\n def _analyze_rel(self) -> None:\n \"\"\"extract predicate argument structure and coreference relation from tag in knp string\"\"\"\n tag2sid = {tag: sentence.sid for sentence in self.sentences for tag in sentence.tag_list()}\n for tag in self.tag_list():\n rels = []\n for rel in self._extract_rel_tags(tag):\n if self.relax_cases:\n if rel.atype in ALL_CASES and rel.atype.endswith('≒'):\n rel.atype = rel.atype.rstrip('≒') # ガ≒ -> ガ\n valid = True\n if rel.sid is not None and rel.sid not in self.sid2sentence:\n logger.warning(f'{tag2sid[tag]:24}sentence: {rel.sid} not found in {self.doc_id}')\n valid = False\n if rel.atype in (ALL_CASES + ALL_COREFS):\n if rel.atype not in (self.cases + self.corefs):\n logger.info(f'{tag2sid[tag]:24}relation type: {rel.atype} is ignored')\n valid = False\n else:\n logger.warning(f'{tag2sid[tag]:24}unknown relation: {rel.atype}')\n if valid:\n rels.append(rel)\n src_bp = BasePhrase(tag, self.tag2dtid[tag], tag2sid[tag], self.mrph2dmid)\n # extract PAS\n pas = Pas(src_bp, self.mrph2dmid)\n for rel in rels:\n if rel.atype in self.cases:\n if rel.sid is not None:\n assert rel.tid is not None\n arg_bp = self._get_bp(rel.sid, rel.tid)\n if arg_bp is None:\n continue\n # 項を発見したら同時に mention と entity を作成\n mention = self._create_mention(arg_bp)\n pas.add_argument(rel.atype, mention, rel.mode, self.mrph2dmid)\n # exophora\n else:\n if rel.target == 'なし':\n pas.set_arguments_optional(rel.atype)\n continue\n if rel.target not in ALL_EXOPHORS:\n logger.warning(f'{pas.sid:24}unknown exophor: {rel.target}')\n continue\n entity = self._create_entity(rel.target)\n pas.add_special_argument(rel.atype, rel.target, entity.eid, rel.mode)\n if pas.arguments:\n self._pas[pas.dtid] = pas\n\n # extract coreference\n for rel in rels:\n if rel.atype in self.corefs:\n if rel.mode in ('', 'AND'): # ignore \"OR\" and \"?\"\n self._add_corefs(src_bp, rel)\n\n # to extract rels with mode: '?', rewrite initializer of pyknp Futures class\n @staticmethod\n def _extract_rel_tags(tag: Tag) -> List[Rel]:\n \"\"\"parse tag.fstring to extract tags\"\"\"\n splitter = \"><\"\n rels = []\n spec = tag.fstring\n\n tag_start = 1\n tag_end = None\n while tag_end != -1:\n tag_end = spec.find(splitter, tag_start)\n if spec[tag_start:].startswith('rel '):\n rel = Rel(spec[tag_start:tag_end])\n if rel.target:\n rel.target = jaconv.h2z(rel.target, digit=True) # 不特定:人1 -> 不特定:人1\n if rel.atype is not None:\n rels.append(rel)\n\n tag_start = tag_end + len(splitter)\n return rels\n\n def _add_corefs(self,\n source_bp: BasePhrase,\n rel: Rel,\n ) -> None:\n if rel.sid is not None:\n target_bp = self._get_bp(rel.sid, rel.tid)\n if target_bp is None:\n return\n if target_bp.dtid == source_bp.dtid:\n logger.warning(f'{source_bp.sid:24}coreference with self found: {source_bp.midasi}')\n return\n else:\n target_bp = None\n if rel.target not in ALL_EXOPHORS:\n logger.warning(f'{source_bp.sid:24}unknown exophor: {rel.target}')\n return\n\n uncertain: bool = rel.atype.endswith('≒')\n source_mention = self._create_mention(source_bp)\n for eid in source_mention.all_eids:\n # _merge_entities によって source_mention の eid が削除されているかもしれない\n if eid not in self.entities:\n continue\n source_entity = self.entities[eid]\n if rel.sid is not None:\n target_mention = self._create_mention(target_bp)\n for target_eid in target_mention.all_eids:\n target_entity = self.entities[target_eid]\n self._merge_entities(source_mention, target_mention, source_entity, target_entity, uncertain)\n else:\n target_entity = self._create_entity(exophor=rel.target)\n self._merge_entities(source_mention, None, source_entity, target_entity, uncertain)\n\n def _create_mention(self, bp: BasePhrase) -> Mention:\n \"\"\"メンションを作成\n bp がまだ mention として登録されていなければ新しく entity と共に作成.\n 登録されていればその mention を返す.\n\n Args:\n bp (BasePhrase): 基本句\n\n Returns:\n Mention: メンション\n \"\"\"\n if bp.dtid not in self.mentions:\n # new coreference cluster is made\n mention = Mention(bp, self.mrph2dmid)\n self.mentions[bp.dtid] = mention\n entity = self._create_entity()\n entity.add_mention(mention, uncertain=False)\n else:\n mention = self.mentions[bp.dtid]\n return mention\n\n def _create_entity(self,\n exophor: Optional[str] = None,\n eid: Optional[int] = None,\n ) -> Entity:\n \"\"\"エンティティを作成\n\n exophor が singleton entity だった場合を除き、新しく Entity のインスタンスを作成して返す\n singleton entity とは、「著者」や「不特定:人1」などの必ず一つしか存在しないような entity\n 一方で、「不特定:人」や「不特定:物」は複数存在しうるので singleton entity ではない\n eid を指定しない場合、最後に作成した entity の次の eid を選択\n\n Args:\n exophor (Optional[str]): 外界照応詞(optional)\n eid (Optional[int]): エンティティID(省略推奨)\n\n Returns:\n Entity: エンティティ\n \"\"\"\n if exophor:\n if exophor not in ('不特定:人', '不特定:物', '不特定:状況'): # exophor が singleton entity だった時\n entities = [e for e in self.entities.values() if exophor == e.exophor]\n # すでに singleton entity が存在した場合、新しい entity は作らずにその entity を返す\n if entities:\n assert len(entities) == 1 # singleton entity が1つしかないことを保証\n return entities[0]\n eids: List[int] = [e.eid for e in self.entities.values()]\n if eid in eids:\n eid_ = eid\n eid: int = max(eids) + 1\n logger.warning(f'{self.doc_id:24}eid: {eid_} is already used. use eid: {eid} instead.')\n elif eid is None or eid < 0:\n eid: int = max(eids) + 1 if eids else 0\n entity = Entity(eid, exophor=exophor)\n self.entities[eid] = entity\n return entity\n\n def _merge_entities(self,\n source_mention: Mention,\n target_mention: Optional[Mention],\n se: Entity,\n te: Entity,\n uncertain: bool,\n ) -> None:\n \"\"\"2つのエンティティをマージする\n\n source_mention と se, target_mention と te の間には mention が張られているが、\n source と target 間には張られていないので、add_mention する\n se と te が同一のエンティティであり、exophor も同じか片方が None ならば te の方を削除する\n\n Args:\n source_mention (Mention): 参照元メンション\n target_mention (Mention?): 参照先メンション\n se (Entity): 参照元エンティティ\n te (Entity): 参照先エンティティ\n uncertain (bool): source_mention と target_mention のアノテーションが ≒ かどうか\n \"\"\"\n uncertain_tgt = (target_mention is not None) and target_mention.is_uncertain_to(te)\n uncertain_src = source_mention.is_uncertain_to(se)\n if se is te:\n if not uncertain:\n # se(te), source_mention, target_mention の三角形のうち2辺が certain ならもう1辺も certain\n if (not uncertain_src) and uncertain_tgt:\n se.add_mention(target_mention, uncertain=False)\n if uncertain_src and (not uncertain_tgt):\n se.add_mention(source_mention, uncertain=False)\n return\n if target_mention is not None:\n se.add_mention(target_mention, uncertain=(uncertain or uncertain_src))\n te.add_mention(source_mention, uncertain=(uncertain or uncertain_tgt))\n # se と te が同一でない可能性が拭えない場合、te は削除しない\n if uncertain_src or uncertain or uncertain_tgt:\n return\n # se と te が同一でも exophor が異なれば te は削除しない\n if se.exophor is not None and te.exophor is not None and se.exophor != te.exophor:\n return\n # 以下 te を削除する準備\n if se.exophor is None:\n se.exophor = te.exophor\n for tm in te.all_mentions:\n se.add_mention(tm, uncertain=tm.is_uncertain_to(te))\n # argument も eid を持っているので eid が変わった場合はこちらも更新\n for arg in [arg for pas in self._pas.values() for args in pas.arguments.values() for arg in args]:\n if isinstance(arg, SpecialArgument) and arg.eid == te.eid:\n arg.eid = se.eid\n self._delete_entity(te.eid, source_mention.sid) # delete target entity\n\n def _delete_entity(self,\n eid: int,\n sid: str\n ) -> None:\n \"\"\"entity を削除する\n\n 対象の entity を entities から削除すると共に、\n その entity を参照する全ての mention からも削除\n eid に欠番ができる\n\n Args:\n eid (int): 削除対象の entity の EID\n sid (int): 削除された時解析されていた文の文ID\n \"\"\"\n if eid not in self.entities:\n return\n entity = self.entities[eid]\n logger.info(f'{sid:24}delete entity: {eid} ({entity.midasi})')\n for mention in entity.all_mentions:\n entity.remove_mention(mention)\n self.entities.pop(eid)\n\n def _get_bp(self,\n sid: str,\n tid: int,\n ) -> Optional[BasePhrase]:\n \"\"\"文IDと基本句IDから基本句を得る\n\n Args:\n sid (str): 文ID\n tid (int): 基本句ID\n\n Returns:\n Optional[BasePhrase]: 対応する基本句\n \"\"\"\n tag_list = self.sid2sentence[sid].tag_list()\n if not (0 <= tid < len(tag_list)):\n logger.warning(f'{sid:24}tag id: {tid} out of range')\n return None\n tag = tag_list[tid]\n return BasePhrase(tag, self.tag2dtid[tag], sid, self.mrph2dmid)\n\n def _extract_nes(self) -> None:\n \"\"\"KNP の tag を参照して文書中から固有表現を抽出する\"\"\"\n for sentence in self.sentences:\n tag_list = sentence.tag_list()\n # tag.features = {'NE': 'LOCATION:ダーマ神殿'}\n for tag in tag_list:\n if 'NE' not in tag.features:\n continue\n category, midasi = tag.features['NE'].split(':', maxsplit=1)\n if category not in NE_CATEGORIES:\n logger.warning(f'{sentence.sid:24}unknown NE category: {category}')\n continue\n mrph_list = [m for t in tag_list[:tag.tag_id + 1] for m in t.mrph_list()]\n mrph_span = self._find_mrph_span(midasi, mrph_list, tag)\n if mrph_span is None:\n logger.warning(f'{sentence.sid:24}mrph span of \"{midasi}\" not found')\n continue\n ne = NamedEntity(category, midasi, sentence, mrph_span, self.mrph2dmid)\n self.named_entities.append(ne)\n\n @staticmethod\n def _find_mrph_span(midasi: str,\n mrph_list: List[Morpheme],\n tag: Tag\n ) -> Optional[range]:\n \"\"\"midasiにマッチする形態素の範囲を返す\"\"\"\n for i in range(len(tag.mrph_list())):\n end_mid = len(mrph_list) - i\n mrph_span = ''\n for mrph in reversed(mrph_list[:end_mid]):\n mrph_span = mrph.midasi + mrph_span\n if mrph_span == midasi:\n return range(mrph.mrph_id, end_mid)\n return None\n\n @property\n def sentences(self) -> List[BList]:\n \"\"\"文を構成する全文節列オブジェクト\n\n Returns:\n List[BList]\n \"\"\"\n return list(self.sid2sentence.values())\n\n def bnst_list(self) -> List[Bunsetsu]:\n return [bnst for sentence in self.sentences for bnst in sentence.bnst_list()]\n\n def tag_list(self) -> List[Tag]:\n return [tag for sentence in self.sentences for tag in sentence.tag_list()]\n\n def mrph_list(self) -> List[Morpheme]:\n return [mrph for sentence in self.sentences for mrph in sentence.mrph_list()]\n\n def get_entities(self, tag: Tag) -> List[Entity]:\n return [e for e in self.entities.values() if any(m.dtid == self.tag2dtid[tag] for m in e.mentions)]\n\n def pas_list(self) -> List[Pas]:\n return list(self._pas.values())\n\n def get_predicates(self) -> List[Predicate]:\n return [pas.predicate for pas in self._pas.values()]\n\n def get_arguments(self,\n predicate: Predicate,\n relax: bool = False,\n include_optional: bool = False,\n ) -> Dict[str, List[BaseArgument]]:\n \"\"\"述語 predicate が持つ全ての項を返す\n\n Args:\n predicate (Predicate): 述語\n relax (bool): coreference chain によってより多くの項を返すかどうか\n include_optional (bool): 「すぐに」などの修飾的な項も返すかどうか\n\n Returns:\n Dict[str, List[BaseArgument]]: 格を key とする述語の項の辞書\n \"\"\"\n if predicate.dtid not in self._pas:\n return {}\n pas = copy.copy(self._pas[predicate.dtid])\n pas.arguments = cPickle.loads(cPickle.dumps(pas.arguments, -1))\n if include_optional is False:\n for case in self.cases:\n pas.arguments[case] = list(filter(lambda a: a.optional is False, pas.arguments[case]))\n\n if relax is True:\n for case, args in self._pas[predicate.dtid].arguments.items():\n for arg in args:\n for eid in (arg.all_eids if isinstance(arg, Argument) else arg.eids):\n entity = self.entities[eid]\n if entity.is_special and entity.exophor != arg.midasi:\n pas.add_special_argument(case, entity.exophor, entity.eid, 'AND')\n for mention in entity.all_mentions:\n if isinstance(arg, Argument) and mention.dtid == arg.dtid:\n continue\n pas.add_argument(case, mention, 'AND', self.mrph2dmid)\n\n return pas.arguments\n\n def get_siblings(self, mention: Mention, relax: bool = False) -> Set[Mention]:\n \"\"\"mention と共参照関係にある他の全ての mention を返す\"\"\"\n mentions = set()\n for eid in mention.eids:\n entity = self.entities[eid]\n mentions.update(entity.mentions)\n if relax is True:\n for eid in mention.eids_unc:\n entity = self.entities[eid]\n mentions.update(entity.all_mentions)\n if mention in mentions:\n mentions.remove(mention)\n return mentions\n\n def draw_tree(self,\n sid: str,\n coreference: bool,\n fh: Optional[TextIO] = None,\n ) -> None:\n \"\"\"sid で指定された文の述語項構造・共参照関係をツリー形式で fh に書き出す\n\n Args:\n sid (str): 出力対象の文ID\n coreference (bool): 共参照関係も出力するかどうか\n fh (Optional[TextIO]): 出力ストリーム\n \"\"\"\n sentence: BList = self[sid]\n with io.StringIO() as string:\n sentence.draw_tag_tree(fh=string)\n tree_strings = string.getvalue().rstrip('\\n').split('\\n')\n assert len(tree_strings) == len(sentence.tag_list())\n all_midasis = [m.midasi for m in self.mentions.values()]\n for predicate in filter(lambda p: p.sid == sid, self.get_predicates()):\n idx = predicate.tid\n tree_strings[idx] += ' '\n arguments = self.get_arguments(predicate)\n for case in self.cases:\n args = arguments[case]\n targets = set()\n for arg in args:\n target = arg.midasi\n if all_midasis.count(arg.midasi) > 1 and isinstance(arg, Argument):\n target += str(arg.dtid)\n targets.add(target)\n tree_strings[idx] += f'{\",\".join(targets)}:{case} '\n if coreference:\n for src_mention in filter(lambda m: m.sid == sid, self.mentions.values()):\n tgt_mentions = [tgt for tgt in self.get_siblings(src_mention) if tgt.dtid < src_mention.dtid]\n targets = set()\n for tgt_mention in tgt_mentions:\n target = tgt_mention.midasi\n if all_midasis.count(target) > 1:\n target += str(tgt_mention.dtid)\n targets.add(target)\n for eid in src_mention.eids:\n entity = self.entities[eid]\n if entity.is_special:\n targets.add(entity.exophor)\n if not targets:\n continue\n idx = src_mention.tid\n tree_strings[idx] += ' =:'\n tree_strings[idx] += ','.join(targets)\n\n print('\\n'.join(tree_strings), file=fh)\n\n def stat(self) -> dict:\n \"\"\"calculate document statistics\"\"\"\n ret = dict()\n ret['num_sents'] = len(self)\n ret['num_tags'] = len(self.tag_list())\n ret['num_mrphs'] = len(self.mrph_list())\n ret['num_taigen'] = sum(1 for tag in self.tag_list() if '体言' in tag.features)\n ret['num_yougen'] = sum(1 for tag in self.tag_list() if '用言' in tag.features)\n ret['num_entities'] = len(self.entities)\n ret['num_special_entities'] = sum(1 for ent in self.entities.values() if ent.is_special)\n\n num_mention = num_taigen = num_yougen = 0\n for src_mention in self.mentions.values():\n tgt_mentions: Set[Mention] = self.get_siblings(src_mention)\n if tgt_mentions:\n num_mention += 1\n for tgt_mention in tgt_mentions:\n if '体言' in tgt_mention.tag.features:\n num_taigen += 1\n if '用言' in tgt_mention.tag.features:\n num_yougen += 1\n ret['num_mentions'] = num_mention\n ret['num_taigen_mentions'] = num_taigen\n ret['num_yougen_mentions'] = num_yougen\n\n return ret\n\n def __len__(self):\n return len(self.sid2sentence)\n\n def __getitem__(self, sid: str):\n if sid in self.sid2sentence:\n return self.sid2sentence[sid]\n else:\n logger.error(f'sentence: {sid} is not in this document')\n return None\n\n def __iter__(self):\n return iter(self.sid2sentence.values())\n\n def __str__(self):\n return '\\n'.join(''.join(tag.midasi for tag in sent.tag_list()) for sent in self)\n", "sub_path": "src/kyoto_reader/reader.py", "file_name": "reader.py", "file_ext": "py", "file_size_in_byte": 31117, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "logging.getLogger", "line_number": 18, "usage_type": "call"}, {"api_name": "logging.WARNING", "line_number": 19, "usage_type": "attribute"}, {"api_name": "typing.Union", "line_number": 36, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 36, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 37, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 37, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 38, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 38, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 45, "usage_type": "argument"}, {"api_name": "pathlib.Path", "line_number": 47, "usage_type": "argument"}, {"api_name": "typing.List", "line_number": 50, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 50, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 52, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 52, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 52, "usage_type": "name"}, {"api_name": "collections.OrderedDict", "line_number": 52, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 55, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 55, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 55, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 58, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 58, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 58, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 60, "usage_type": "name"}, {"api_name": "kyoto_reader.constants.ALL_CASES", "line_number": 60, "usage_type": "argument"}, {"api_name": "kyoto_reader.constants.CORE_CASES", "line_number": 60, "usage_type": "argument"}, {"api_name": "typing.List", "line_number": 61, "usage_type": "name"}, {"api_name": "kyoto_reader.constants.ALL_COREFS", "line_number": 61, "usage_type": "argument"}, {"api_name": "kyoto_reader.constants.CORE_COREFS", "line_number": 61, "usage_type": "argument"}, {"api_name": "typing.Optional", "line_number": 69, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 85, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 92, "usage_type": "argument"}, {"api_name": "_pickle.load", "line_number": 95, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 88, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 111, "usage_type": "name"}, {"api_name": "typing.Iterator", "line_number": 111, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 111, "usage_type": "name"}, {"api_name": "typing.Iterator", "line_number": 115, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 149, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 150, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 157, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 158, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 163, "usage_type": "name"}, {"api_name": "pyknp.BList", "line_number": 163, "usage_type": "name"}, {"api_name": "collections.OrderedDict", "line_number": 163, "usage_type": "call"}, {"api_name": "pyknp.BList", "line_number": 168, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 179, "usage_type": "name"}, {"api_name": "kyoto_reader.pas.Pas", "line_number": 179, "usage_type": "name"}, {"api_name": "collections.OrderedDict", "line_number": 179, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 180, "usage_type": "name"}, {"api_name": "kyoto_reader.coreference.Mention", "line_number": 180, "usage_type": "name"}, {"api_name": "collections.OrderedDict", "line_number": 180, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 181, "usage_type": "name"}, {"api_name": "kyoto_reader.coreference.Entity", "line_number": 181, "usage_type": "name"}, {"api_name": "collections.OrderedDict", "line_number": 181, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 188, "usage_type": "name"}, {"api_name": "kyoto_reader.ne.NamedEntity", "line_number": 188, "usage_type": "name"}, {"api_name": "kyoto_reader.pas.Pas", "line_number": 211, "usage_type": "call"}, {"api_name": "kyoto_reader.base_phrase.BasePhrase", "line_number": 211, "usage_type": "call"}, {"api_name": "kyoto_reader.constants.ALL_CASES", "line_number": 214, "usage_type": "name"}, {"api_name": "jaconv.h2z", "line_number": 217, "usage_type": "call"}, {"api_name": "kyoto_reader.constants.ALL_CASES", "line_number": 237, "usage_type": "name"}, {"api_name": "kyoto_reader.constants.ALL_CASES", "line_number": 243, "usage_type": "name"}, {"api_name": "kyoto_reader.constants.ALL_COREFS", "line_number": 243, "usage_type": "name"}, {"api_name": "kyoto_reader.base_phrase.BasePhrase", "line_number": 251, "usage_type": "call"}, {"api_name": "kyoto_reader.pas.Pas", "line_number": 253, "usage_type": "call"}, {"api_name": "kyoto_reader.constants.ALL_EXOPHORS", "line_number": 269, "usage_type": "name"}, {"api_name": "pyknp.Tag", "line_number": 285, "usage_type": "name"}, {"api_name": "pyknp.Rel", "line_number": 296, "usage_type": "call"}, {"api_name": "jaconv.h2z", "line_number": 298, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 285, "usage_type": "name"}, {"api_name": "pyknp.Rel", "line_number": 285, "usage_type": "name"}, {"api_name": "kyoto_reader.base_phrase.BasePhrase", "line_number": 306, "usage_type": "name"}, {"api_name": "pyknp.Rel", "line_number": 307, "usage_type": "name"}, {"api_name": "kyoto_reader.constants.ALL_EXOPHORS", "line_number": 318, "usage_type": "name"}, {"api_name": "kyoto_reader.base_phrase.BasePhrase", "line_number": 338, "usage_type": "name"}, {"api_name": "kyoto_reader.coreference.Mention", "line_number": 351, "usage_type": "call"}, {"api_name": "kyoto_reader.coreference.Mention", "line_number": 338, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 360, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 361, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 384, "usage_type": "name"}, {"api_name": "kyoto_reader.coreference.Entity", "line_number": 391, "usage_type": "call"}, {"api_name": "kyoto_reader.coreference.Entity", "line_number": 362, "usage_type": "name"}, {"api_name": "kyoto_reader.coreference.Mention", "line_number": 396, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 397, "usage_type": "name"}, {"api_name": "kyoto_reader.coreference.Mention", "line_number": 397, "usage_type": "name"}, {"api_name": "kyoto_reader.coreference.Entity", "line_number": 398, "usage_type": "name"}, {"api_name": "kyoto_reader.coreference.Entity", "line_number": 399, "usage_type": "name"}, {"api_name": "kyoto_reader.pas.SpecialArgument", "line_number": 441, "usage_type": "argument"}, {"api_name": "kyoto_reader.base_phrase.BasePhrase", "line_number": 485, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 470, "usage_type": "name"}, {"api_name": "kyoto_reader.base_phrase.BasePhrase", "line_number": 470, "usage_type": "name"}, {"api_name": "kyoto_reader.constants.NE_CATEGORIES", "line_number": 496, "usage_type": "name"}, {"api_name": "kyoto_reader.ne.NamedEntity", "line_number": 504, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 509, "usage_type": "name"}, {"api_name": "pyknp.Morpheme", "line_number": 509, "usage_type": "name"}, {"api_name": "pyknp.Tag", "line_number": 510, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 511, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 523, "usage_type": "name"}, {"api_name": "pyknp.BList", "line_number": 523, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 531, "usage_type": "name"}, {"api_name": "pyknp.Bunsetsu", "line_number": 531, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 534, "usage_type": "name"}, {"api_name": "pyknp.Tag", "line_number": 534, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 537, "usage_type": "name"}, {"api_name": "pyknp.Morpheme", "line_number": 537, "usage_type": "name"}, {"api_name": "pyknp.Tag", "line_number": 540, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 540, "usage_type": "name"}, {"api_name": "kyoto_reader.coreference.Entity", "line_number": 540, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 543, "usage_type": "name"}, {"api_name": "kyoto_reader.pas.Pas", "line_number": 543, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 546, "usage_type": "name"}, {"api_name": "kyoto_reader.pas.Predicate", "line_number": 546, "usage_type": "name"}, {"api_name": "kyoto_reader.pas.Predicate", "line_number": 550, "usage_type": "name"}, {"api_name": "copy.copy", "line_number": 566, "usage_type": "call"}, {"api_name": "_pickle.loads", "line_number": 567, "usage_type": "call"}, {"api_name": "_pickle.dumps", "line_number": 567, "usage_type": "call"}, {"api_name": "kyoto_reader.pas.Argument", "line_number": 575, "usage_type": "argument"}, {"api_name": "kyoto_reader.pas.Argument", "line_number": 580, "usage_type": "argument"}, {"api_name": "typing.Dict", "line_number": 553, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 553, "usage_type": "name"}, {"api_name": "kyoto_reader.pas.BaseArgument", "line_number": 553, "usage_type": "name"}, {"api_name": "kyoto_reader.coreference.Mention", "line_number": 586, "usage_type": "name"}, {"api_name": "typing.Set", "line_number": 586, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 603, "usage_type": "name"}, {"api_name": "typing.TextIO", "line_number": 603, "usage_type": "name"}, {"api_name": "pyknp.BList", "line_number": 612, "usage_type": "name"}, {"api_name": "io.StringIO", "line_number": 613, "usage_type": "call"}, {"api_name": "kyoto_reader.pas.Argument", "line_number": 627, "usage_type": "argument"}, {"api_name": "typing.Set", "line_number": 665, "usage_type": "name"}, {"api_name": "kyoto_reader.coreference.Mention", "line_number": 665, "usage_type": "name"}]}
+{"seq_id": "260999875", "text": "import pytest\n\nfrom conftest import quoted_object, run_setup_sql\nfrom pgbedrock import ownerships as own\nfrom pgbedrock import attributes, privileges\nfrom pgbedrock.context import ObjectInfo\n\nQ_CREATE_SEQUENCE = 'SET ROLE {}; CREATE SEQUENCE {}.{}; RESET ROLE;'\nQ_SCHEMA_EXISTS = \"SELECT schema_name FROM information_schema.schemata WHERE schema_name='{}';\"\n\nROLES = tuple('role{}'.format(i) for i in range(2))\nSCHEMAS = tuple('schema{}'.format(i) for i in range(3))\nTABLES = tuple('table{}'.format(i) for i in range(4))\nSEQUENCES = tuple('seq{}'.format(i) for i in range(4))\nDUMMY = 'foo'\n\n\n@run_setup_sql([\n 'DROP SCHEMA public',\n 'CREATE SCHEMA {}'.format(SCHEMAS[0]),\n ])\ndef test_analyze_schemas_with_undocumented_items(capsys, cursor):\n spec = {'postgres': {'has_personal_schema': False}}\n\n with pytest.raises(SystemExit):\n own.analyze_schemas(spec, cursor, verbose=False)\n\n # Undocumented schemas will come back double-quoted\n missing_schemas = '\"information_schema\", \"pg_catalog\", \"schema0\"'\n assert capsys.readouterr()[0] == own.UNDOCUMENTED_SCHEMAS_MSG.format(missing_schemas) + \"\\n\"\n\n\n@run_setup_sql([\n 'DROP SCHEMA public',\n attributes.Q_CREATE_ROLE.format(ROLES[0]),\n attributes.Q_CREATE_ROLE.format(ROLES[1]),\n ])\ndef test_analyze_schemas_create_schemas(cursor):\n spec = {\n ROLES[0]: {\n 'has_personal_schema': True,\n 'owns': {\n 'schemas': [SCHEMAS[0]]\n },\n },\n ROLES[1]: {\n 'owns': {\n 'schemas': [SCHEMAS[1]],\n },\n },\n 'postgres': {\n 'owns': {\n 'schemas': [\n 'information_schema',\n 'pg_catalog',\n ]\n },\n },\n }\n actual = own.analyze_schemas(spec, cursor, verbose=False)\n\n expected = set([\n own.Q_CREATE_SCHEMA.format(ROLES[0], ROLES[0]),\n own.Q_CREATE_SCHEMA.format(SCHEMAS[0], ROLES[0]),\n own.Q_CREATE_SCHEMA.format(SCHEMAS[1], ROLES[1]),\n ])\n assert set(actual) == expected\n\n\ndef test_get_spec_schemas():\n spec = {\n ROLES[0]: {\n 'has_personal_schema': True,\n 'owns': {\n 'schemas': [SCHEMAS[0]]\n },\n },\n ROLES[1]: {\n 'owns': {\n 'schemas': [SCHEMAS[1]]\n },\n }\n }\n\n assert own.get_spec_schemas(spec) == set([ROLES[0], SCHEMAS[0], SCHEMAS[1]])\n\n\ndef test_init(mockdbcontext):\n mockdbcontext.get_schema_owner = lambda x: 'foo'\n mockdbcontext.get_schema_objects = lambda x: 'bar'\n schemaconf = own.SchemaAnalyzer(rolename=ROLES[0], schema=SCHEMAS[0], dbcontext=mockdbcontext)\n\n assert schemaconf.rolename == ROLES[0]\n assert schemaconf.schema == SCHEMAS[0]\n assert schemaconf.current_owner == 'foo'\n assert schemaconf.exists is True\n assert schemaconf.schema_objects == 'bar'\n\n\ndef test_analyze_create_schema(mockdbcontext):\n schemaconf = own.SchemaAnalyzer(ROLES[0], schema=SCHEMAS[0], dbcontext=mockdbcontext)\n actual = schemaconf.analyze()\n expected = [own.Q_CREATE_SCHEMA.format(SCHEMAS[0], ROLES[0])]\n assert actual == expected\n\n\ndef test_analyze_existing_schema_owner_change(mockdbcontext):\n mockdbcontext.get_schema_owner = lambda x: ROLES[1]\n schemaconf = own.SchemaAnalyzer(ROLES[0], schema=SCHEMAS[0], dbcontext=mockdbcontext)\n changes = schemaconf.analyze()\n assert changes == [own.Q_SET_SCHEMA_OWNER.format(SCHEMAS[0], ROLES[0], ROLES[1])]\n\n\ndef test_analyze_existing_schema_same_owner(mockdbcontext):\n mockdbcontext.get_schema_owner = lambda x: ROLES[0]\n schemaconf = own.SchemaAnalyzer(ROLES[0], schema=SCHEMAS[0], dbcontext=mockdbcontext)\n changes = schemaconf.analyze()\n assert changes == []\n\n\ndef test_analyze_existing_personal_schema_change_object_owners(mockdbcontext):\n mockdbcontext.get_schema_owner = lambda x: ROLES[0]\n mockdbcontext.get_schema_objects = lambda x: [\n ObjectInfo('tables', quoted_object(ROLES[0], TABLES[0]), ROLES[0], False),\n ObjectInfo('sequences', quoted_object(ROLES[0], SEQUENCES[0]), ROLES[0], False),\n ObjectInfo('tables', quoted_object(ROLES[0], TABLES[1]), ROLES[1], False),\n ObjectInfo('sequences', quoted_object(ROLES[0], SEQUENCES[1]), ROLES[1], False),\n ]\n schema = ROLES[0]\n\n schemaconf = own.SchemaAnalyzer(ROLES[0], schema=schema, dbcontext=mockdbcontext,\n is_personal_schema=True)\n actual = schemaconf.analyze()\n expected = [\n own.Q_SET_OBJECT_OWNER.format('TABLE', quoted_object(ROLES[0], TABLES[1]), ROLES[0], ROLES[1]),\n own.Q_SET_OBJECT_OWNER.format('SEQUENCE', quoted_object(ROLES[0], SEQUENCES[1]), ROLES[0], ROLES[1]),\n ]\n assert actual == expected\n\n\ndef test_create_schema(mockdbcontext):\n schemaconf = own.SchemaAnalyzer(ROLES[0], schema=SCHEMAS[0], dbcontext=mockdbcontext)\n schemaconf.create_schema()\n\n assert schemaconf.sql_to_run == [own.Q_CREATE_SCHEMA.format(SCHEMAS[0], ROLES[0])]\n\n\ndef test_set_owner(mockdbcontext):\n previous_owner = ROLES[1]\n mockdbcontext.get_schema_owner = lambda x: previous_owner\n\n schemaconf = own.SchemaAnalyzer(ROLES[0], schema=SCHEMAS[0], dbcontext=mockdbcontext)\n schemaconf.set_owner()\n\n expected = [own.Q_SET_SCHEMA_OWNER.format(SCHEMAS[0], ROLES[0], previous_owner)]\n assert schemaconf.sql_to_run == expected\n\n\ndef test_alter_object_owner(mockdbcontext):\n previous_owner = ROLES[1]\n owner = ROLES[0]\n schema = SCHEMAS[0]\n table_name = quoted_object(schema, TABLES[0])\n mockdbcontext.get_schema_owner = lambda x: owner\n\n schemaconf = own.SchemaAnalyzer(owner, schema=schema, dbcontext=mockdbcontext)\n schemaconf.alter_object_owner('tables', table_name, previous_owner)\n assert schemaconf.sql_to_run == [own.Q_SET_OBJECT_OWNER.format('TABLE', table_name, owner, previous_owner)]\n\n\ndef test_get_improperly_owned_objects(mockdbcontext):\n mockdbcontext.get_schema_owner = lambda x: ROLES[0]\n mockdbcontext.get_schema_objects = lambda x: [\n # Properly owned\n ObjectInfo('tables', quoted_object(ROLES[0], TABLES[0]), ROLES[0], False),\n ObjectInfo('sequences', quoted_object(ROLES[0], SEQUENCES[0]), ROLES[0], False),\n\n # Improperly owned\n ObjectInfo('tables', quoted_object(ROLES[0], TABLES[1]), ROLES[1], False),\n ObjectInfo('sequences', quoted_object(ROLES[0], SEQUENCES[1]), ROLES[1], False),\n\n # Improperly owned but dependent (i.e. should be skipped)\n ObjectInfo('sequences', quoted_object(ROLES[0], SEQUENCES[2]), ROLES[1], True),\n ]\n schema = ROLES[0]\n\n schemaconf = own.SchemaAnalyzer(rolename=ROLES[0], schema=schema, dbcontext=mockdbcontext,\n is_personal_schema=True)\n\n actual = schemaconf.get_improperly_owned_objects()\n expected = [('tables', quoted_object(schema, TABLES[1]), ROLES[1]),\n ('sequences', quoted_object(schema, SEQUENCES[1]), ROLES[1])]\n assert set(actual) == set(expected)\n", "sub_path": "tests/test_ownerships.py", "file_name": "test_ownerships.py", "file_ext": "py", "file_size_in_byte": 7080, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "pytest.raises", "line_number": 25, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships.analyze_schemas", "line_number": 26, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships", "line_number": 26, "usage_type": "name"}, {"api_name": "pgbedrock.ownerships.UNDOCUMENTED_SCHEMAS_MSG.format", "line_number": 30, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships.UNDOCUMENTED_SCHEMAS_MSG", "line_number": 30, "usage_type": "attribute"}, {"api_name": "pgbedrock.ownerships", "line_number": 30, "usage_type": "name"}, {"api_name": "conftest.run_setup_sql", "line_number": 18, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships.analyze_schemas", "line_number": 60, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships", "line_number": 60, "usage_type": "name"}, {"api_name": "pgbedrock.ownerships.Q_CREATE_SCHEMA.format", "line_number": 63, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships.Q_CREATE_SCHEMA", "line_number": 63, "usage_type": "attribute"}, {"api_name": "pgbedrock.ownerships", "line_number": 63, "usage_type": "name"}, {"api_name": "pgbedrock.ownerships.Q_CREATE_SCHEMA.format", "line_number": 64, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships.Q_CREATE_SCHEMA", "line_number": 64, "usage_type": "attribute"}, {"api_name": "pgbedrock.ownerships", "line_number": 64, "usage_type": "name"}, {"api_name": "pgbedrock.ownerships.Q_CREATE_SCHEMA.format", "line_number": 65, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships.Q_CREATE_SCHEMA", "line_number": 65, "usage_type": "attribute"}, {"api_name": "pgbedrock.ownerships", "line_number": 65, "usage_type": "name"}, {"api_name": "conftest.run_setup_sql", "line_number": 33, "usage_type": "call"}, {"api_name": "pgbedrock.attributes.Q_CREATE_ROLE.format", "line_number": 35, "usage_type": "call"}, {"api_name": "pgbedrock.attributes.Q_CREATE_ROLE", "line_number": 35, "usage_type": "attribute"}, {"api_name": "pgbedrock.attributes", "line_number": 35, "usage_type": "name"}, {"api_name": "pgbedrock.attributes.Q_CREATE_ROLE.format", "line_number": 36, "usage_type": "call"}, {"api_name": "pgbedrock.attributes.Q_CREATE_ROLE", "line_number": 36, "usage_type": "attribute"}, {"api_name": "pgbedrock.attributes", "line_number": 36, "usage_type": "name"}, {"api_name": "pgbedrock.ownerships.get_spec_schemas", "line_number": 85, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships", "line_number": 85, "usage_type": "name"}, {"api_name": "pgbedrock.ownerships.SchemaAnalyzer", "line_number": 91, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships", "line_number": 91, "usage_type": "name"}, {"api_name": "pgbedrock.ownerships.SchemaAnalyzer", "line_number": 101, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships", "line_number": 101, "usage_type": "name"}, {"api_name": "pgbedrock.ownerships.Q_CREATE_SCHEMA.format", "line_number": 103, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships.Q_CREATE_SCHEMA", "line_number": 103, "usage_type": "attribute"}, {"api_name": "pgbedrock.ownerships", "line_number": 103, "usage_type": "name"}, {"api_name": "pgbedrock.ownerships.SchemaAnalyzer", "line_number": 109, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships", "line_number": 109, "usage_type": "name"}, {"api_name": "pgbedrock.ownerships.Q_SET_SCHEMA_OWNER.format", "line_number": 111, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships.Q_SET_SCHEMA_OWNER", "line_number": 111, "usage_type": "attribute"}, {"api_name": "pgbedrock.ownerships", "line_number": 111, "usage_type": "name"}, {"api_name": "pgbedrock.ownerships.SchemaAnalyzer", "line_number": 116, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships", "line_number": 116, "usage_type": "name"}, {"api_name": "pgbedrock.context.ObjectInfo", "line_number": 124, "usage_type": "call"}, {"api_name": "conftest.quoted_object", "line_number": 124, "usage_type": "call"}, {"api_name": "pgbedrock.context.ObjectInfo", "line_number": 125, "usage_type": "call"}, {"api_name": "conftest.quoted_object", "line_number": 125, "usage_type": "call"}, {"api_name": "pgbedrock.context.ObjectInfo", "line_number": 126, "usage_type": "call"}, {"api_name": "conftest.quoted_object", "line_number": 126, "usage_type": "call"}, {"api_name": "pgbedrock.context.ObjectInfo", "line_number": 127, "usage_type": "call"}, {"api_name": "conftest.quoted_object", "line_number": 127, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships.SchemaAnalyzer", "line_number": 131, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships", "line_number": 131, "usage_type": "name"}, {"api_name": "pgbedrock.ownerships.Q_SET_OBJECT_OWNER.format", "line_number": 135, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships.Q_SET_OBJECT_OWNER", "line_number": 135, "usage_type": "attribute"}, {"api_name": "pgbedrock.ownerships", "line_number": 135, "usage_type": "name"}, {"api_name": "conftest.quoted_object", "line_number": 135, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships.Q_SET_OBJECT_OWNER.format", "line_number": 136, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships.Q_SET_OBJECT_OWNER", "line_number": 136, "usage_type": "attribute"}, {"api_name": "pgbedrock.ownerships", "line_number": 136, "usage_type": "name"}, {"api_name": "conftest.quoted_object", "line_number": 136, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships.SchemaAnalyzer", "line_number": 142, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships", "line_number": 142, "usage_type": "name"}, {"api_name": "pgbedrock.ownerships.Q_CREATE_SCHEMA.format", "line_number": 145, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships.Q_CREATE_SCHEMA", "line_number": 145, "usage_type": "attribute"}, {"api_name": "pgbedrock.ownerships", "line_number": 145, "usage_type": "name"}, {"api_name": "pgbedrock.ownerships.SchemaAnalyzer", "line_number": 152, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships", "line_number": 152, "usage_type": "name"}, {"api_name": "pgbedrock.ownerships.Q_SET_SCHEMA_OWNER.format", "line_number": 155, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships.Q_SET_SCHEMA_OWNER", "line_number": 155, "usage_type": "attribute"}, {"api_name": "pgbedrock.ownerships", "line_number": 155, "usage_type": "name"}, {"api_name": "conftest.quoted_object", "line_number": 163, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships.SchemaAnalyzer", "line_number": 166, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships", "line_number": 166, "usage_type": "name"}, {"api_name": "pgbedrock.ownerships.Q_SET_OBJECT_OWNER.format", "line_number": 168, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships.Q_SET_OBJECT_OWNER", "line_number": 168, "usage_type": "attribute"}, {"api_name": "pgbedrock.ownerships", "line_number": 168, "usage_type": "name"}, {"api_name": "pgbedrock.context.ObjectInfo", "line_number": 175, "usage_type": "call"}, {"api_name": "conftest.quoted_object", "line_number": 175, "usage_type": "call"}, {"api_name": "pgbedrock.context.ObjectInfo", "line_number": 176, "usage_type": "call"}, {"api_name": "conftest.quoted_object", "line_number": 176, "usage_type": "call"}, {"api_name": "pgbedrock.context.ObjectInfo", "line_number": 179, "usage_type": "call"}, {"api_name": "conftest.quoted_object", "line_number": 179, "usage_type": "call"}, {"api_name": "pgbedrock.context.ObjectInfo", "line_number": 180, "usage_type": "call"}, {"api_name": "conftest.quoted_object", "line_number": 180, "usage_type": "call"}, {"api_name": "pgbedrock.context.ObjectInfo", "line_number": 183, "usage_type": "call"}, {"api_name": "conftest.quoted_object", "line_number": 183, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships.SchemaAnalyzer", "line_number": 187, "usage_type": "call"}, {"api_name": "pgbedrock.ownerships", "line_number": 187, "usage_type": "name"}, {"api_name": "conftest.quoted_object", "line_number": 191, "usage_type": "call"}, {"api_name": "conftest.quoted_object", "line_number": 192, "usage_type": "call"}]}
+{"seq_id": "455395491", "text": "#!/usr/bin/python3\n\"\"\"\nAgents are the basis for (nearly) everything. An agent has a set of controls, some of which are in all agents, others can\nbe defined by classes inheriting from one of the agent classes. \n\nAgents can also have children which are themselves agents, allowing hierarchic structures to be built up. Once an agent is created\nall activities revolve around the controls which the agent has. Higher agents (all the way up to the end user via a web interface)\ncan request that particular controls are updated, and controls can themselves declare changed values which will be passed 'up' the\nhierarchy.\n\nThere are 3 primary types of agent:\n A synchronous agent is 'owned' by a higher agent, and runs in the same process as the higher agent. Most actions will be performed\n synchronously, although this will not necessarily be obvious to the higher agent.\n \n A subprocess agent can be the top of the tree, or a subordinate agent. It runs in a separate process = even in a separate machine.\n All communication is through a pipe or socket type connection. Subprocess agents will normally initiate connection to the 'higher'\n agent. The underlying implementation allows the connections to fail and be recovered automatically.\n \n A stub agent is a special type of synchronous agent that is used to manage the connection with subprocess agent. This allows the \n interface to an agent to appear identical irrespective of whether the agent is in process or out of process.\n \nNormally synchronous agents are instantiated by the agent that owns them, and subprocess agents are initiated independently, either from\nthe command line or run as a daemon.\n\nAgents can set up listeners that will respond to incoming connect requests by informing the agent \n- typically this will spawn a new stub agent.\n\nThe interface provided by an agent is defined by a few methods, which are primarily about the controls that represent the agent's state\nand action capabilities.\n\n setControls - provides a set of control names and the new values that are being requested by an owning agent to a subordinate agent\n \n notifyControls - informs an owning agent that 1 or more controls of a subordinate agent have changed\n \n\"\"\"\n\nimport procman\nimport controls\nimport camlib\nimport socket, time, logging, sys, traceback\n\nreadonlyflagset = {controls.ctrlFlags.readOnly}\n\nclass AgentBase():\n \"\"\"A base class for all agents\n \n Each Agent has a set of controls which define its externally visible state. Methods are provided\n to access and manipulate these controls.\n \n Every agent is expected to have at least these controls:\n aType - the type of the agent\n aLoglevel - the current logging level used for this agent\n and optionally:\n aInstance - the instance name of this agent - if not present (for single instance agents) then aType is used\n aDesc - description of this Agent\n \"\"\"\n def __init__(self, agentType, agentInstance = None, agentDesc=None, parentinfo = None, agentLogLevel = logging.DEBUG):\n \"\"\"creates the base for an agent of any type.\n \"\"\"\n tnow =time.time()\n self.controls = {\n 'aType': controls.genControl('aType', controls.strExtras(),'agent type', agentType, tnow, \"\", readonlyflagset, None)}\n if not agentInstance is None:\n self.controls['aInst'] = controls.genControl(\n 'aInst', controls.strExtras(),'agent instance', agentInstance, tnow, \"\", readonlyflagset, None)\n if not agentDesc is None:\n self.controls['aDesc'] = controls.genControl(\n 'aDesc', controls.strExtras(),'agent description', agentDesc, tnow, \"\", readonlyflagset, None)\n\n if agentLogLevel is None:\n self.lgr = self.parent.pcl\n self.controls['aLogLvl'] = controls.genControl('aLogLvl', controls.intExtras(None, None, None)\n , 'log level', 0, tnow, 0, {controls.ctrlFlags.unavailable}, None)\n else:\n self.lgr = logging.getLogger(\"%s%s\" % (agentType, '' if agentInstance is None else '(%s)' % agentInstance))\n self.controls['aLogLvl'] = controls.genControl('aLogLvl', controls.intExtras(None, None, None)\n , 'log level', agentLogLevel, tnow, agentLogLevel, {}, None)\n \n self.controls.update(self.makeControlset())\n self.pushpends = []\n self.pushtimer = None\n for cid, ctrl in self.controls.items():\n ctrl.setPushAgent(self.pushctrlchange)\n if parentinfo is None:\n self.master = None\n else:\n self.master = procman.ProcHostConnection(self, parentinfo, self.bghmessage,\"baseconn\")\n self.lgr.info(\"%s%s setup complete using AgentBase\" % (agentType, '' if agentInstance is None else '(%s)' % agentInstance))\n \n def makeControlset(self):\n \"\"\"override this method and return a dict of additional controls\"\"\"\n return {}\n self.lgr.warn(\"makeControlset: no additional controls defined\")\n\n def agentType(self):\n return self.controls['aType'].getValue()\n\n def agentName(self):\n return self.controls['aInst'].getValue() if 'aInst' in self.controls else self.controls['aType'].getValue()\n\n def setControls(self, upinf):\n \"\"\"uses a list of lists to update the local controls\"\"\"\n updateresponses = {'updresp':{}}\n allgood = True\n withfails = False\n for c in self.ctrlProcessOrder():\n if c in msg['upd']:\n uresp = self.controls[c].update(msg['upd'][c])\n self.lgr.debug(\"setControls: update %s result %s\" , c, repr(uresp) )\n allgood = allgood and uresp[2]\n if not uresp[0]:\n withfails=True\n updateresponses['updresp'][c] = uresp\n rmsg = \"all updates applied OK\" if allgood else \"some updates failed\" if withfails else \"adjustments to values made\"\n if not allgood:\n self.lgr.warn(\"setControls: %s\" % rmsg)\n return (allgood, withfails, rmsg, updateresponses)\n\n def ctrlProcessOrder(self):\n \"\"\"override this and return the order in which a set of controls should be processed\"\"\"\n self.lgr.warn(\"ctrlProcessOrder: no process control order defined - no updates will be made\")\n return list()\n\n def getControls(self):\n return self.controls\n\n def getControlsAsDicts(self):\n \"\"\"Standard function to get all the controls in handy dict format \"\"\"\n return controls.getControlsetInfo(self.controls)\n\n def addChildAgent(self,newchild):\n \"\"\"for now we'll assume that this isn't a dynamic thing, so no need to report changes up.\n Of course the new agent can be a stub or a local (synchronous) one.\n \"\"\"\n childid = newchild.agentName()\n print(\"XXXXXXXXXXXXXXXXXXXXX \" + str(type(newchild)))\n if not 'children' in self.controls:\n self.controls['children'] = controls.childControl('children', 'child agents', {childid: newchild}, time.time()\n , readonlyflagset)\n else:\n self.controls['children'].getValue()[childid] = newchild\n \n# def goneAgent(self,agentstub):\n# if agentstub.agenttype in self.agents:\n# del self.agents[agentstub.agenttype]\n# self.notify(\"lifecycle\", 'info', agentstub.agenttype\n# , \"agent %s disconnected from %s\" % (agentstub.agenttype, self.agentname))\n\n def childAgent(self,cname):\n if 'children' in self.controls and cname in self.controls['children'].getValue():\n return self.controls['children'].getValue()[cname]\n else:\n return None\n\n def bghmessage(self,msg):\n if 'ping' in msg:\n self.linktester.pingback(msg)\n return\n if msg['cmd'] == 'getControls':\n camlib.makeResponse(True, msg=self.agentname, cmd=msg, extras=self.getControlsAsDicts())\n self.master.sendOb(msg)\n return\n if msg['cmd'] == 'ctrlupdates':\n if '140' in msg['upd']:\n uresp = self.controlset['140'].update(msg['upd']['140'])\n camlib.makeResponse(True, msg = 'link test runnung', cmd=msg\n , extras={'updresp': {'140': uresp}})\n self.master.sendOb(msg)\n return\n else:\n if self.isGood():\n self.pcl.debug('updates: ' + msg.__repr__())\n if 'subagent' in msg:\n children = self.controlset\n else:\n updateresponses = {'updresp':{}}\n allgood = True\n withfails = False\n for c in self.ctrlProcessOrder():\n if c in msg['upd']:\n uresp = self.controlset[c].update(msg['upd'][c])\n self.pcl.debug(\"inmessage: update %s result %s\" , c, repr(uresp) )\n allgood = allgood and uresp[2]\n if not uresp[0]:\n withfails=True\n updateresponses['updresp'][c] = uresp\n rmsg = \"all updates applied OK\" if allgood else \"some updates failed\" if withfails else \"adjustments to values made\"\n updateresponses['state'] = self.getstate()\n camlib.makeResponse(not withfails, msg = rmsg, cmd=msg, extras=updateresponses)\n else:\n camlib.makeResponse(False, msg=\"device unavailable\", cmd=msg)\n self.master.sendOb(msg)\n return\n\n self.oncmd(msg)\n\n\n def pushctrlchange(self, acontrol):\n self.pcl.debug (\"pushy bit for %s to %s\" % (acontrol.id, acontrol.getValue()) )\n pushdelay = 0 if acontrol.flagIsSet(controls.ctrlFlags.autopushimm) \\\n else 0.1 if acontrol.flagIsSet(controls.ctrlFlags.autopushfast) \\\n else 1 if acontrol.flagIsSet(controls.ctrlFlags.autopushmed) \\\n else 10 if acontrol.flagIsSet(controls.ctrlFlags.autopushslow) \\\n else 100\n tnow = time.time()\n if acontrol in self.pushpends:\n self.pcl.debug(\"already in queue\")\n else:\n self.pushpends.append(acontrol)\n self.pcl.debug(\"added to queue\")\n if pushdelay == 0 or pushdelay > (tnow - acontrol.lastpush):\n self.pushbundle()\n else:\n if self.pushtimer is None or self.pushtimer.timeTillTick() > pushdelay:\n if not self.pushtimer is None:\n self.motor.owningclient.callmeback(self.pushtimer, False)\n self.pushtimer = procman.ProcCallback(time.time()+pushdelay, 1000, self.pushtick, None)\n self.callmeback(self.pushtimer, True)\n self.pcl.debug(\"new timer setup for %f\" % pushdelay)\n\n \nclass AgentSync(AgentBase):\n \"\"\"The base class for synchronous agents that are created within an AgentProc. The can be the direct descendant of either\n type of agent.\n \"\"\"\n\n def __init__(self, parent, agentType, agentInstance = None, agentDesc = None, agentLogLevel = logging.DEBUG):\n AgentBase.__init__(self, agentType, agentInstance, agentDesc, None, agentLogLevel)\n self.parent = parent\n self.lgr.info(\"AgentSync setup complete\") \n\nclass AgentProc(AgentBase, procman.ProcClient):\n \"\"\"A base class for subprocess agents. There must only be 1 of these in any subprocess and it is the\n top of the tree within the subprocess.\n \n It can support an outward connect to a higher agent (or any other socket based thing), and receive incoming\n connect requests from subordinate agents running in their own processes either in the same or in other machines.\n \n \"\"\"\n def __init__(self, agentType, agentInstance, agentDesc = None, parentInfo = None, agentLogLevel = logging.DEBUG, logfile=None):\n self.hostname = socket.gethostname()\n lfmt = logging.Formatter(fmt='%(asctime)s %(levelname)s %(name)s: %(message)s', datefmt='%I:%M:%S')\n agname = agentType if agentInstance is None else agentInstance\n if logfile:\n lhdlr = logging.FileHandler(logfile,'w')\n lhdlr.setFormatter(lfmt)\n lhdlr.setLevel(agentLogLevel)\n lgr = logging.getLogger('BasicAgent(%s)' % agname)\n lgr.addHandler(lhdlr)\n lgr.propagate = False\n else:\n lgr = logging.getLogger('ProcClient(%s)' % agname)\n lgr.setLevel(agentLogLevel)\n self.agentname = agname\n \n procman.ProcClient.__init__(self, '%s(%s):' % (agname,self.hostname),lgr)\n AgentBase.__init__(self, agentType, agentInstance, agentDesc, parentInfo, agentLogLevel)\n self.pushpends = []\n self.pushtimer = None\n\n def addListener(self, listenport):\n self.listener = procman.ProcAccepter(self,False\n ,listenport,self.agentConnects, self.agentname + \" listen\")\n\n def agentConnects(self,clientsock):\n AgentStub(self, clientsock)\n self.pcl.info(\"agentConnects\")\n\nclass linktester(controls.genControl):\n def __init__(self, cid, client, pstore):\n super().__init__(cid, controls.clickButtonExtras(), \"link test\", 0, time.time(), 25\n , controls.ctrlFlags.writeOnly, pstore)\n self.owningClient = client\n self.ticker = None\n\n def update(self,upvalue):\n logging.warn(\"XXXXXXXXXX-link test running.\")\n self.writeValue(time.time())\n self.ticker = procman.ProcCallback(time.time(),.15, self.tickme, None)\n self.owningClient.callmeback(self.ticker, True)\n self.ticksleft = 101\n self.ticklog=[]\n return (True, 1, False, \"link performance test\")\n \n def tickme(self, dummy):\n self.ticksleft -= 1\n if self.ticksleft <= 0:\n self.owningClient.callmeback(self.ticker, False)\n self.ticker = None\n for i in range(len(self.ticklog)):\n if i == 0:\n print('0.000, %f, %f' %(self.ticklog[i]['tb']-self.ticklog[i]['ts']\n , self.ticklog[i]['te']-self.ticklog[i]['ts']))\n else:\n print('%f, %f, %f' %(self.ticklog[i]['ts']-self.ticklog[i-1]['ts']\n , self.ticklog[i]['tb']-self.ticklog[i]['ts']\n , self.ticklog[i]['te']-self.ticklog[i]['ts']))\n\n print(self.ticklog)\n \n else:\n self.owningClient.master.sendOb({'ping': self.ticksleft, 'ts': time.time(), 'tb':0, 'te':0})\n \n def pingback(self, pmsg):\n pmsg['te'] = time.time()\n self.ticklog.append(pmsg)\n \n#class BasicAgent(procman.ProcClient):\n# \"\"\" basic agent framework - establishes connection back to base and provides basic separation\n# of messages arriving into:\n# cmd messages - for the main agent\n# log messages - to control the logging being done by the agent\n# stat messages - to control the status report levels that are returned to base\n# \"\"\"\n# def __init__(self, agname, maddress, mport, loglevel, statlevel, oncmd, logfile = None):\n# self.hostname = socket.gethostname()\n# self.agentname = agname\n# lfmt = logging.Formatter(fmt='%(asctime)s %(levelname)s %(name)s: %(message)s', datefmt='%I:%M:%S')\n# if logfile:\n# lhdlr = logging.FileHandler(logfile,'w')\n# lhdlr.setFormatter(lfmt)\n# lhdlr.setLevel(loglevel)\n# lgr = logging.getLogger('BasicAgeng(%s)' % agname)\n# lgr.addHandler(lhdlr)\n# lgr.propagate = False\n## root_logger = logging.getLogger()\n## root_logger.disabled = True\n# else:\n# lgr = logging.getLogger('ProcClient(%s)' % agname)\n# lgr.setLevel(loglevel)\n# super().__init__('%s(%s):' % (agname,self.hostname),lgr)\n# self.setLogLevels(loglevel, loglevel)\n# self.statlevel = statlevel\n# self.controlset = self.makeControlSet()\n# self.linktester = linktester('140', self, None)\n# self.controlset['140'] = self.linktester\n# self.oncmd = oncmd\n# self.agents={} # for any agents below this one in the hierarchy\n# if maddress is None:\n# self.master = None\n# else:\n# self.master = procman.ProcHostConnection(self, (maddress,mport), self.bghmessage,\"baseconn\")\n# self.pushpends = []\n# self.pushtimer = None\n \n# def addListener(self, listenport):\n# self.listener = procman.ProcAccepter(self,False\n# ,listenport,self.agentConnects, self.agentname + \" listen\")\n\n# def agentConnects(self,clientsock):\n# unknownagent(self, clientsock)\n# self.pcl.info(\"agentConnects\")\n \n# def addAgent(self,agentstub):\n# self.agents[agentstub.agenttype] = agentstub\n# self.notify(\"lifecycle\", 'info', agentstub.agenttype\n# , \"agent %s connected to %s\" % (agentstub.agenttype, self.agentname))\n\n# def goneAgent(self,agentstub):\n# if agentstub.agenttype in self.agents:\n# del self.agents[agentstub.agenttype]\n# self.notify(\"lifecycle\", 'info', agentstub.agenttype\n# , \"agent %s disconnected from %s\" % (agentstub.agenttype, self.agentname))\n\n# def addAgentControlsSub(self, agentstub, subid):\n# \"\"\"Adds this agent stub to the 'children' control using the key subid.\n# \n# The children control is created if it does not exist.\n# \n# The special control class xx is used for this control (defined below)\n# \n# The superior agent this procClient is conencted to is notified of the new child if there is\n# an existing connection.\n# \"\"\"\n# if not 'children' in self.controlset:\n# self.controlset['children'] = {agentstub.agenttype if subid is None else subid : agentstub}\n\n# def bghmessage(self,msg):\n# if 'ping' in msg:\n# self.linktester.pingback(msg)\n# return\n# if msg['cmd'] == 'getControls':\n# camlib.makeResponse(True, msg=self.agentname, cmd=msg, extras=self.getControlsAsDicts())\n# self.master.sendOb(msg)\n# return\n# if msg['cmd'] == 'ctrlupdates':\n# if '140' in msg['upd']:\n# uresp = self.controlset['140'].update(msg['upd']['140'])\n# camlib.makeResponse(True, msg = 'link test runnung', cmd=msg\n# , extras={'updresp': {'140': uresp}})\n# self.master.sendOb(msg)\n# return\n# else:\n# if self.isGood():\n# self.pcl.debug('updates: ' + msg.__repr__())\n# if 'subagent' in msg:\n# children = self.controlset\n# else:\n# updateresponses = {'updresp':{}}\n# allgood = True\n# withfails = False\n# for c in self.ctrlProcessOrder():\n# if c in msg['upd']:\n# uresp = self.controlset[c].update(msg['upd'][c])\n# self.pcl.debug(\"inmessage: update %s result %s\" , c, repr(uresp) )\n# allgood = allgood and uresp[2]\n# if not uresp[0]:\n # withfails=True\n # updateresponses['updresp'][c] = uresp\n # rmsg = \"all updates applied OK\" if allgood else \"some updates failed\" if withfails else \"adjustments to values made\"\n # updateresponses['state'] = self.getstate()\n# camlib.makeResponse(not withfails, msg = rmsg, cmd=msg, extras=updateresponses)\n# else:\n# camlib.makeResponse(False, msg=\"device unavailable\", cmd=msg)\n# self.master.sendOb(msg)\n# return\n\n# self.oncmd(msg)\n\n# def notify(self, mtype, mlevel, morigin, message):\n# \"\"\"incoming status from any lower level agents arrive here, and are by default forwarded up the chain.\n# override this to do any local actions based on the message, call super to forward them up as well.\n# \"\"\"\n# self.pcl.debug(\"status message %s (%s), (%s), (%s)\" ,message, mlevel, morigin, message)\n# self.master.sendOb({'statusmsg': {\n# 'mtype': mtype\n# , 'mlevel': mlevel\n# , 'morigin': self.agentname + '.' + morigin\n# ,'message': message}})\n\n# def enablepush(self, acontrol):\n# acontrol.setPushAgent(self.pushctrlchange)\n \n# def pushctrlchange(self, acontrol):\n# self.pcl.debug (\"pushy bit for %s to %s\" % (acontrol.id, acontrol.getValue()) )\n# pushdelay = 0 if acontrol.flagIsSet(controls.ctrlFlags.autopushimm) \\\n# else 0.1 if acontrol.flagIsSet(controls.ctrlFlags.autopushfast) \\\n# else 1 if acontrol.flagIsSet(controls.ctrlFlags.autopushmed) \\\n# else 10 if acontrol.flagIsSet(controls.ctrlFlags.autopushslow) \\\n# else 100\n# tnow = time.time()\n# if acontrol in self.pushpends:\n# self.pcl.debug(\"already in queue\")\n# else:\n# self.pushpends.append(acontrol)\n# self.pcl.debug(\"added to queue\")\n# if pushdelay == 0 or pushdelay > (tnow - acontrol.lastpush):\n# self.pushbundle()\n# else:\n# if self.pushtimer is None or self.pushtimer.timeTillTick() > pushdelay:\n# if not self.pushtimer is None:\n# self.motor.owningclient.callmeback(self.pushtimer, False)\n# self.pushtimer = procman.ProcCallback(time.time()+pushdelay, 1000, self.pushtick, None)\n# self.callmeback(self.pushtimer, True)\n# self.pcl.debug(\"new timer setup for %f\" % pushdelay)\n\n# def pushtick(self,dummy):\n# self.callmeback(self.pushtimer, False)\n# self.pushtimer = None\n# self.pushbundle()\n \n# def pushbundle(self):\n# if self.pushpends:\n# self.pcl.debug(\"pushing outstanding queue ---------\")\n# uset = {k.id: k.getUpdateValue() for k in self.pushpends}\n# self.pcl.debug(uset)\n# self.master.sendOb({'update': uset})\n# self.pushpends.clear()\n \n# def sendStatus(self, stype, level, sttext):\n# \"\"\"sends a standard status message 'up' the chain, originating from here\n# \"\"\"\n# self.master.sendOb({'statusmsg': {'mtype': stype, 'mlevel': level, 'morigin': self.agentname, 'message': sttext}})\n\n# def getControlsAsDicts(self):\n## resu = ({k: v.getControlInfo(None) for k, v in self.controlset.items()})\n## return resu\n# return controls.getControlsetInfo(self.controlset)\n \nclass AgentStub(procman.ProcServerConnection):\n \"\"\"A basic stub agent which manages the connection to the 'real' agent through a socket.\n \n It fires off a 'getControls' command initially and runs initially as a free-standing (unconnected) entity.\n When the response to the getControls arrives it identifies the agent type and calls it's\n owner's addChildAgent Method.\n \"\"\"\n def __init__(self, master, clientsock):\n \"\"\"sets up an initial agent stub\"\"\"\n super().__init__(master, clientsock, self.msgin, \"AgentStub\")\n self.controls = None\n self.sendOb({'cmd':'getControls'})\n self.changedcontrols=[]\n self.agenttype = ''\n self.onUpdateIn = None\n\n def agentName(self):\n return self.controls['aInst']['value'] if 'aInst' in self.controls else self.controls['aType']['value']\n\n def setOnUpdateIn(self, func):\n self.onUpdateIn = func\n\n def getControls(self):\n return self.controls\n \n def getChangedControls(self):\n self.lgr.info(\"getChangedControls....\")\n if self.changedcontrols:\n resp = ((k, self.controls[k]['mlist'][self.controls[k]['value']][1]\n if self.controls[k]['type'] == controls.ctrlTypes.cmenu.value else self.controls[k]['value'])\n for k in self.changedcontrols)\n self.changedcontrols = []\n return resp\n return None\n \n def msgin(self,msg):\n if 'ping' in msg:\n msg['tb'] = time.time()\n self.sendOb(msg)\n elif 'cmd' in msg and msg['cmd'] == 'getControls':\n self.controls = msg['response']['extras']\n self.agentType = self.controls['aInst']['value'] if 'aInst' in self.controls else self.controls['aType']['value']\n self.lgr.info(\"msgin agenttype is %s\" % self.agenttype)\n self.parent.addChildAgent(self)\n elif 'update' in msg:\n self.lgr.debug(\"msgin is update\")\n if not self.controls is None:\n for k,ctrlupd in msg['update'].items():\n actrl = self.controls[k]\n actrl['value'] = ctrlupd['v']\n actrl['valueat'] = ctrlupd['t']\n self.lgr.debug(\"ctrl %s set to %s\", actrl['name'], str(ctrlupd['v']))\n if not k in self.changedcontrols:\n self.changedcontrols.append(k)\n if not self.onUpdateIn is None:\n self.wrappedCall(self.onUpdateIn, msg)\n else:\n self.lgr.info(\"no controls available to update in %s\" % self.agenttype)\n# elif 'statusmsg' in msg:\n# nargs = msg['statusmsg']\n# self.parent.notify(morigin = self.agenttype, **nargs)\n else:\n self.lgr.info(\"WHAT? msgin %s\", msg)\n\n def controlUpdates(self,msg):\n msg['to'] = time.time()\n self.sendOb(msg)\n for ctrlid, newval in msg['upd'].items():\n self.controls[ctrlid]['value'] = newval\n\n def close(self):\n self.parent.goneAgent(self)\n super().close()\n\n def wrappedCall(self, fcall, param):\n try: # wrap the call so we can report errors, and then carry on\n \tfcall(param)\n except KeyboardInterrupt:\n \traise\n except:\n \texc_type, exc_value, exc_traceback = sys.exc_info()\n \tself.parent.pcl.warning(\"wrappedCall: exception in called code - \\n%s\\n%s\" % (\n \t\t\tstr(exc_value), ''.join(traceback.format_tb(exc_traceback))))\n ", "sub_path": "basicagent.py", "file_name": "basicagent.py", "file_ext": "py", "file_size_in_byte": 26639, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "controls.ctrlFlags", "line_number": 42, "usage_type": "attribute"}, {"api_name": "logging.DEBUG", "line_number": 57, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 60, "usage_type": "call"}, {"api_name": "controls.genControl", "line_number": 62, "usage_type": "call"}, {"api_name": "controls.strExtras", "line_number": 62, "usage_type": "call"}, {"api_name": "controls.genControl", "line_number": 64, "usage_type": "call"}, {"api_name": "controls.strExtras", "line_number": 65, "usage_type": "call"}, {"api_name": "controls.genControl", "line_number": 67, "usage_type": "call"}, {"api_name": "controls.strExtras", "line_number": 68, "usage_type": "call"}, {"api_name": "controls.genControl", "line_number": 72, "usage_type": "call"}, {"api_name": "controls.intExtras", "line_number": 72, "usage_type": "call"}, {"api_name": "controls.ctrlFlags", "line_number": 73, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 75, "usage_type": "call"}, {"api_name": "controls.genControl", "line_number": 76, "usage_type": "call"}, {"api_name": "controls.intExtras", "line_number": 76, "usage_type": "call"}, {"api_name": "procman.ProcHostConnection", "line_number": 87, "usage_type": "call"}, {"api_name": "controls.getControlsetInfo", "line_number": 129, "usage_type": "call"}, {"api_name": "controls.childControl", "line_number": 138, "usage_type": "call"}, {"api_name": "time.time", "line_number": 138, "usage_type": "call"}, {"api_name": "camlib.makeResponse", "line_number": 160, "usage_type": "call"}, {"api_name": "camlib.makeResponse", "line_number": 166, "usage_type": "call"}, {"api_name": "camlib.makeResponse", "line_number": 189, "usage_type": "call"}, {"api_name": "camlib.makeResponse", "line_number": 191, "usage_type": "call"}, {"api_name": "controls.ctrlFlags", "line_number": 200, "usage_type": "attribute"}, {"api_name": "controls.ctrlFlags", "line_number": 201, "usage_type": "attribute"}, {"api_name": "controls.ctrlFlags", "line_number": 202, "usage_type": "attribute"}, {"api_name": "controls.ctrlFlags", "line_number": 203, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 205, "usage_type": "call"}, {"api_name": "procman.ProcCallback", "line_number": 217, "usage_type": "call"}, {"api_name": "time.time", "line_number": 217, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 227, "usage_type": "attribute"}, {"api_name": "procman.ProcClient", "line_number": 232, "usage_type": "attribute"}, {"api_name": "logging.DEBUG", "line_number": 240, "usage_type": "attribute"}, {"api_name": "socket.gethostname", "line_number": 241, "usage_type": "call"}, {"api_name": "logging.Formatter", "line_number": 242, "usage_type": "call"}, {"api_name": "logging.FileHandler", "line_number": 245, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 248, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 252, "usage_type": "call"}, {"api_name": "procman.ProcClient.__init__", "line_number": 256, "usage_type": "call"}, {"api_name": "procman.ProcClient", "line_number": 256, "usage_type": "attribute"}, {"api_name": "procman.ProcAccepter", "line_number": 262, "usage_type": "call"}, {"api_name": "controls.genControl", "line_number": 269, "usage_type": "attribute"}, {"api_name": "controls.clickButtonExtras", "line_number": 271, "usage_type": "call"}, {"api_name": "time.time", "line_number": 271, "usage_type": "call"}, {"api_name": "controls.ctrlFlags", "line_number": 272, "usage_type": "attribute"}, {"api_name": "logging.warn", "line_number": 277, "usage_type": "call"}, {"api_name": "time.time", "line_number": 278, "usage_type": "call"}, {"api_name": "procman.ProcCallback", "line_number": 279, "usage_type": "call"}, {"api_name": "time.time", "line_number": 279, "usage_type": "call"}, {"api_name": "time.time", "line_number": 302, "usage_type": "call"}, {"api_name": "time.time", "line_number": 305, "usage_type": "call"}, {"api_name": "procman.ProcServerConnection", "line_number": 480, "usage_type": "attribute"}, {"api_name": "controls.ctrlTypes", "line_number": 509, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 517, "usage_type": "call"}, {"api_name": "time.time", "line_number": 545, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 560, "usage_type": "call"}, {"api_name": "traceback.format_tb", "line_number": 562, "usage_type": "call"}]}
+{"seq_id": "86960237", "text": "#!/usr/bin/python\nimport requests\nfrom bs4 import BeautifulSoup\nimport lxml.html\nimport pymysql\nimport time\n\ndef main():\n\n conn = pymysql.connect(host='localhost', user='scraper', password='tiger', db='scraping', charset='utf8')\n\n try:\n with conn.cursor() as curs:\n sql = \"\"\"insert into naver_article(title, url, dt, category, rank, pv) values (%s, %s, %s, %s, %s, %s)\"\"\"\n\n session = requests.session()\n response = session.get('http://cis.kbs.co.kr/cis/favorite_naver_mobile-3.html')\n root = lxml.html.fromstring(response.content)\n root.make_links_absolute(response.url)\n\n time.sleep(2)\n\n dt = root.cssselect('input')[0].get('value')\n\n time.sleep(2)\n \n for row in root.cssselect('#ntabs-1 tr'):\n for cell in row.cssselect('td:nth-child(3)'):\n if cell.text_content() == 'KBS':\n curs.execute(sql,(\n row.cssselect('td:nth-child(4)')[0].text_content(), #title\n row.cssselect('a')[1].get('href'), #url\n dt, #date\n row.cssselect('td:nth-child(2)')[0].text_content(), #category\n int(row.cssselect('td:nth-child(1)')[0].text_content()), #rank\n int(row.cssselect('td:nth-child(5)')[0].text_content().replace(',','')) #pv\n #row.cssselect('td:nth-child(5)')[0].text_content() #pv\n ))\n conn.commit()\n\n with conn.cursor() as curs:\n sql = \"select * from naver_article order by dt desc\"\n curs.execute(sql)\n rs = curs.fetchall()\n for row in rs:\n print(row)\n\n finally:\n conn.close()\n\nif __name__ == '__main__':\n main()\n", "sub_path": "naverScraping.py", "file_name": "naverScraping.py", "file_ext": "py", "file_size_in_byte": 2366, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "pymysql.connect", "line_number": 10, "usage_type": "call"}, {"api_name": "requests.session", "line_number": 16, "usage_type": "call"}, {"api_name": "lxml.html.html.fromstring", "line_number": 18, "usage_type": "call"}, {"api_name": "lxml.html.html", "line_number": 18, "usage_type": "attribute"}, {"api_name": "lxml.html", "line_number": 18, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 21, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 25, "usage_type": "call"}]}
+{"seq_id": "303817825", "text": "\nimport copy\nimport time \nimport logging\nimport collections\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Item(QtGui.QStandardItem):\n \"\"\"\n The Item class used for all filter tree steps. \n The item can take any of the following types:\n - Generic Item (unused)\n - Input Item\n - Filter Item\n - Group Item\n - Modifier Item\n\n All except the Generic Item type can be automatically created using the\n respective factory methods. \n\n All Item data is stored in the data structure of `QStandardItem` and\n can be accessed directly as attributes of the `Item` instance. \n \"\"\"\n\n #TYPE constants: use Item.type() to return item type\n FILTER_TYPE = QtGui.QStandardItem.UserType + 1\n MODIFIER_TYPE = QtGui.QStandardItem.UserType + 2\n GROUP_TYPE = QtGui.QStandardItem.UserType + 3\n INPUT_TYPE = QtGui.QStandardItem.UserType + 10\n\n #DATA ROLE constants: use with Item.setData(value, role) or Item.data(role)\n TYPE = QtCore.Qt.UserRole + 100\n NAME = QtCore.Qt.UserRole + 200\n IS_PROCESSED = QtCore.Qt.UserRole + 500\n HAS_PROCESSING_ERROR = QtCore.Qt.UserRole + 501\n STATUS_MESSAGE = QtCore.Qt.UserRole + 502\n OUTPUT = QtCore.Qt.UserRole + 600\n FN = QtCore.Qt.UserRole + 700\n PARAMS = QtCore.Qt.UserRole + 900\n ID = QtCore.Qt.UserRole + 1000\n\n def __init__(self):\n super().__init__()\n\n self.name = \"\"\n self.full_name = \"\"\n self.description = \"\"\n self.fn = None\n self.params = None\n self.is_active = True\n self.is_processed = False\n self.has_processing_error = False\n self.status_message = \"Not processed\"\n self.output = None\n self.id = str(time.time()) #Item id is the current time, converted to string. This ensures uniqueness\n\n def __getattribute__(self, name):\n if name == 'name':\n return self.data(self.NAME)\n elif name == 'full_name':\n return self.data(QtCore.Qt.DisplayRole)\n elif name == 'description':\n return self.data(QtCore.Qt.ToolTipRole)\n elif name == 'fn':\n return self.data(self.FN)\n elif name == 'params':\n return self.data(self.PARAMS)\n elif name == 'is_active':\n value = self.data(QtCore.Qt.CheckStateRole)\n return True if value == QtCore.Qt.Checked else False\n elif name == 'is_processed':\n return self.data(self.IS_PROCESSED)\n elif name == 'has_processing_error':\n return self.data(self.HAS_PROCESSING_ERROR)\n elif name == 'status_message':\n return self.data(self.STATUS_MESSAGE)\n elif name == 'output':\n return self.data(self.OUTPUT)\n elif name == 'id':\n return self.data(self.ID)\n elif name == 'icon':\n return Item._getIcon(self)\n else:\n return super().__getattribute__(name)\n\n def __setattr__(self, name, value):\n if name == 'name':\n self.setData(value, self.NAME)\n elif name == 'full_name':\n self.setData(value, QtCore.Qt.DisplayRole)\n self.setData(value, QtCore.Qt.EditRole)\n elif name == 'description':\n self.setData(value, QtCore.Qt.ToolTipRole)\n elif name == 'fn':\n self.setData(value, self.FN)\n elif name == 'params': \n self.setData(value, self.PARAMS)\n elif name == 'is_active':\n if type(value) == bool:\n value = QtCore.Qt.Checked if value else QtCore.Qt.Unchecked\n self.setData(value, QtCore.Qt.CheckStateRole)\n elif name == 'is_processed':\n self.setData(value, self.IS_PROCESSED)\n elif name == 'has_processing_error':\n self.setData(value, self.HAS_PROCESSING_ERROR)\n elif name == 'status_message':\n self.setData(value, self.STATUS_MESSAGE)\n elif name == 'output':\n self.setData(value, self.OUTPUT)\n elif name == 'id':\n self.setData(value, self.ID)\n else:\n super().__setattr__(name, value) \n\n def updateParam(self, name, value):\n \"\"\" Update the value of a given parameter. \"\"\"\n params = self.params\n params[name]['value'] = value\n self.params = params\n\n def resetId(self):\n \"\"\" Reset the item's id \"\"\"\n self.id = str(time.time())\n\n def clone(self, keep_id=False, keep_output=False, keep_children_mode='all', keep_children_output=False):\n \"\"\"\n Clone the item.\n\n Parameters\n ----------\n keep_id : bool\n If True, maintain the original item id\n keep_output : bool\n If True, maintain the original item's output. Otherwise output will be None. \n keep_children_mode : str\n Must be one of the following:\n - all: recursively copy all the item's children\n - first: only copy the item's immediate children\n - none: don't copy children\n keep_children_output : bool\n If True, maintain the children's output. \n Only has an effect if `keep_children_mode` is not `none`. \n\n Returns\n -------\n item : Item\n The cloned Item instance\n \"\"\"\n\n item = Item()\n item.name = self.name\n item.full_name = self.full_name\n item.description = self.description\n item.fn = self.fn\n item.params = copy.deepcopy(self.params)\n item.is_active = self.is_active\n\n item.setData(self.type(), self.TYPE)\n item.setData(Item._getIcon(item), QtCore.Qt.DecorationRole)\n item.setFlags(Item._getFlags(item))\n\n if keep_id:\n item.id = self.id\n\n if keep_output:\n item.output = self.output\n \n if keep_children_mode.lower() == 'all':\n for child in self.children():\n child_clone = child.clone(keep_id=keep_id, \n keep_output=keep_children_output, keep_children_mode='all')\n item.appendRow(child_clone)\n\n elif keep_children_mode.lower() == 'first':\n for child in self.children():\n child_clone = child.clone(keep_id=keep_id, \n keep_output=keep_children_output, keep_children_mode='none')\n item.appendRow(child_clone)\n \n else:\n pass\n\n logging.debug(\"Cloned item {} (keep_id={}, keep_output={}, keep_children_mode={}, keep_children_output={})\".format(item.full_name, keep_id, keep_output, keep_children_mode, keep_children_output))\n \n return item\n\n def setParamValueDict(self, params): \n \"\"\" \n Replace all parameter's values with the given values \n \n Parameters\n ----------\n params : dict\n Dictionary with name-value pairs for each parameter\n \"\"\"\n\n for name, value in params.items():\n self.updateParam(name, value)\n\n def getParamValueDict(self):\n \"\"\"\n Return the parameter values dictionary. \n\n Returns\n -------\n params : dict\n Dictionary with name-value pairs for each parameter\n \"\"\"\n\n params = collections.OrderedDict()\n for name, param in self.params.items():\n params[name] = param['value']\n return params\n\n def children(self):\n \"\"\"\n Return iterable of all the item's children. \n\n Returns\n -------\n children : iterable\n All the item's immediate children. \n \"\"\"\n\n if self.hasChildren():\n child_count = self.rowCount()\n for child_i in range(child_count):\n yield self.child(child_i)\n\n def type(self):\n \"\"\" Return the item's type role \"\"\"\n return self.data(self.TYPE)\n\n @classmethod\n def createFilterItem(cls, name, full_name, description=\"\", fn=None, params=collections.OrderedDict()):\n \n item = cls()\n\n item.name = name\n item.full_name = full_name\n item.description = description\n \n item.fn = fn\n if params: \n try: \n item.params = cls._initializeFilterParams(params)\n except ParameterError as e:\n print(\"Parameter error in item {}: \".format(name), e)\n item.params = collections.OrderedDict()\n else:\n item.params = collections.OrderedDict()\n\n item.params['modifier_coefficient'] = {\n 'full_name': 'Modifier Coefficient',\n 'wtype':'double_spinbox',\n 'dtype': float,\n 'description': 'Coefficient to use for this item if it is contained within a modifier',\n 'optional': True,\n 'value': 1.0,\n 'default': 1.0,\n 'minimum': -9999.0,\n 'maximum': 9999.0,\n 'single_step': 0.1,\n 'decimals': 2}\n\n item.setData(cls.FILTER_TYPE, cls.TYPE)\n item.setData(cls._getIcon(item), QtCore.Qt.DecorationRole)\n item.setFlags(cls._getFlags(item))\n \n return item\n\n @classmethod\n def createGroupItem(cls):\n\n item = cls()\n\n item.name = 'group'\n item.full_name = 'Group'\n item.description = \"Processes multiple items in sequence\"\n\n item.params = collections.OrderedDict()\n\n item.params['modifier_coefficient'] = {\n 'full_name': 'Modifier Coefficient',\n 'wtype':'double_spinbox',\n 'dtype': float,\n 'description': 'Coefficient to use for this item if it is contained within a modifier',\n 'optional': True,\n 'value': 1.0,\n 'default': 1.0,\n 'minimum': -9999.0,\n 'maximum': 9999.0,\n 'single_step': 0.1,\n 'decimals': 2}\n\n item.setData(cls.GROUP_TYPE, cls.TYPE)\n item.setData(cls._getIcon(item), QtCore.Qt.DecorationRole)\n item.setFlags(cls._getFlags(item))\n\n return item\n\n @classmethod\n def createModifierItem(cls):\n \n item = cls()\n\n item.name = 'modifier'\n item.full_name = 'Modifier'\n item.description = 'Processes multiple items individually and then combines their results'\n\n item.params = collections.OrderedDict({\n 'mode': {\n 'full_name': 'Modifier Mode',\n 'wtype': 'combobox',\n 'dtype': str,\n 'description': \"Determines whether children of modifier are added or multiplied\",\n 'optional': False,\n 'value': 'add',\n 'default': 'add',\n 'options': ['add', 'multiply'],\n 'options_description': ['Add components', 'Multiply components']},\n 'clip': {\n 'full_name': 'clip',\n 'wtype': 'checkbox',\n 'dtype': bool, \n 'description': \"Clip result to maximum for given dtype, else range will be stretched to dtype range\", \n 'optional': False,\n 'default': True,\n 'value': True},\n 'modifier_coefficient': {\n 'full_name': 'Modifier Coefficient',\n 'wtype': 'double_spinbox',\n 'dtype': float,\n 'description': 'Coefficient to use for this item if it is contained within a modifier',\n 'optional': True,\n 'value': 1.0,\n 'default': 1.0,\n 'minimum': -9999.0,\n 'maximum': 9999.0,\n 'single_step': 0.1,\n 'decimals': 2}})\n\n item.setData(cls.MODIFIER_TYPE, cls.TYPE) \n item.setData(cls._getIcon(item), QtCore.Qt.DecorationRole)\n item.setFlags(cls._getFlags(item))\n\n return item \n\n @classmethod\n def createInputItem(cls,input_path=None):\n\n item = cls()\n \n item.name = 'input_item'\n item.full_name = 'Input Image'\n item.description = \"The tree's input image. Cannot be moved!\"\n\n item.params = collections.OrderedDict(\n {'input_path': {\n 'full_name': 'Input Path',\n 'wtype':'lineedit',\n 'dtype': str,\n 'description': \"Path of the input image\",\n 'optional': False,\n 'value': \"\",\n 'default': \"\",\n },\n 'modifier_coefficient': {\n 'full_name': 'Modifier Coefficient',\n 'wtype':'double_spinbox',\n 'dtype': float,\n 'description': 'Coefficient to use for this item if it is contained within a modifier',\n 'optional': True,\n 'value': 1.0,\n 'default': 1.0,\n 'minimum': -9999.0,\n 'maximum': 9999.0,\n 'single_step': 0.1,\n 'decimals': 2}})\n\n item.setData(cls.INPUT_TYPE, cls.TYPE)\n item.setData(cls._getIcon(item), QtCore.Qt.DecorationRole)\n item.setFlags(cls._getFlags(item))\n\n if input_path:\n item.updateParam('input_path',input_path)\n\n return item\n\n @staticmethod\n def _initializeFilterParams(params):\n \n if not params: \n return collections.OrderedDict()\n else:\n params = collections.OrderedDict(params)\n\n for name, p in params.items():\n if not 'full_name' in p.keys(): p['full_name'] = name\n if not 'optional' in p.keys(): p['options'] = False\n if not 'description' in p.keys(): p['description'] = \"\"\n\n if not 'dtype' in p.keys(): raise ParameterError(\"No dtype provided for parameter {}\".format(name))\n if not p['dtype'] in [float, int, str, bool]: raise ParameterError(\"Invalid dtype for paramter {}\".format(name))\n\n if not 'wtype' in p.keys(): raise ParameterError(\"No wtype provided for parameter {}\".format(name))\n if not p['wtype'] in ['lineedit', 'combobox', 'spinbox', 'double_spinbox', 'checkbox']: raise AttributeError(\"Invalid wtype for parameter {}\".format(name))\n \n if p['wtype'] == 'spinbox':\n if p['dtype'] != int: raise ParameterError(\"dtype for wtype=spinbox must be int in parameter {}\".format(name))\n elif p['wtype'] == 'double_spinbox':\n if p['dtype'] != float: raise ParameterError(\"dtype for wtype=double_spinbox must be float in parameter {}\".format(name))\n\n if not 'default' in p.keys():\n if p['dtype'] == float:\n p['default'] = 0.0\n elif p['dtype'] == int: \n p['default'] = 0\n elif p['dtype'] == str:\n p['default'] = \"\"\n elif p['dtype'] == bool:\n p['default'] = False\n \n if not type(p['default']) == p['dtype']: raise ParameterError(\"Type of default value doesn't match dtype in parameter {}\".format(name))\n \n if p['wtype'] == 'spinbox' or p['wtype'] == 'double_spinbox':\n if 'minimum' in p.keys(): \n if type(p['minimum']) != p['dtype']: raise ParameterError(\"Type of spinbox minimum value doesn't match dtype in parameter {}\".format(name))\n if 'maximum' in p.keys(): \n if type(p['maximum']) != p['dtype']: raise ParameterError(\"Type of spinbox maximum value doesn't match dtype in parameter {}\".format(name))\n if 'single_step' in p.keys(): \n if type(p['single_step']) != p['dtype']: raise ParameterError(\"Type of spinbox single step value doesn't match dtype in parameter {}\".format(name))\n \n if p['wtype'] == 'double_spinbox':\n if not 'decimals' in p.keys():\n p['decimals'] = 2\n\n if p['wtype'] == 'combobox':\n if not 'options' in p.keys(): raise ParameterError(\"No options provided for wtype=combobox in parameter {}\".format(name))\n if 'options_description' in p.keys():\n if len(p['options']) != len(p['options_description']):\n raise ParameterError(\"Length of options list doesn't match length of options_description in parameter {}\".format(name))\n \n if not 'value' in p.keys(): \n p['value'] = p['default']\n\n return params\n \n @staticmethod\n def _getIcon(item):\n\n if item.type() == item.FILTER_TYPE:\n return QtGui.QIcon('resources/filter.png')\n elif item.type() == item.MODIFIER_TYPE:\n return QtGui.QIcon('resources/modifier.png')\n elif item.type() == item.GROUP_TYPE:\n return QtGui.QIcon('resources/folder.png')\n elif item.type() == item.INPUT_TYPE:\n return QtGui.QIcon('resources/input.png')\n else:\n return QtGui.QIcon()\n\n @staticmethod\n def _getFlags(item):\n \n flags = QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsDragEnabled|QtCore.Qt.ItemIsUserCheckable|QtCore.Qt.ItemIsEnabled\n if item.type() == item.FILTER_TYPE:\n flags = flags|QtCore.Qt.ItemNeverHasChildren\n elif item.type() == item.GROUP_TYPE:\n flags = flags|QtCore.Qt.ItemIsDropEnabled|QtCore.Qt.ItemIsEditable\n elif item.type() == item.MODIFIER_TYPE:\n flags = flags|QtCore.Qt.ItemIsDropEnabled\n elif item.type() == item.INPUT_TYPE:\n flags &= ~(QtCore.Qt.ItemIsDragEnabled|QtCore.Qt.ItemIsUserCheckable)\n else: \n return super().flags()\n\n return flags \n\n\nclass ParameterError(Exception):\n pass\n \n", "sub_path": "tree/item_old.py", "file_name": "item_old.py", "file_ext": "py", "file_size_in_byte": 17658, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 10, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui", "line_number": 10, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 28, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui", "line_number": 28, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 29, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui", "line_number": 29, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 30, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui", "line_number": 30, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QStandardItem", "line_number": 31, "usage_type": "attribute"}, {"api_name": "PyQt5.QtGui", "line_number": 31, "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.QtCore.Qt", "line_number": 35, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 35, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 36, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 36, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 37, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 37, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 38, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 38, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 39, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 39, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 40, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 40, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 41, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 41, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 42, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 42, "usage_type": "name"}, {"api_name": "time.time", "line_number": 57, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 63, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 63, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 65, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 65, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 71, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 71, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 72, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 72, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 92, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 92, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 93, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 93, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 95, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 95, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 102, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 102, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 103, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 103, "usage_type": "name"}, {"api_name": "time.time", "line_number": 125, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 157, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 161, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 161, "usage_type": "name"}, {"api_name": "logging.debug", "line_number": 185, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 212, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 237, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 251, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 253, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 269, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 269, "usage_type": "name"}, {"api_name": "collections.OrderedDict", "line_number": 283, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 299, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 299, "usage_type": "name"}, {"api_name": "collections.OrderedDict", "line_number": 313, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 346, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 346, "usage_type": "name"}, {"api_name": "collections.OrderedDict", "line_number": 360, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 384, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 384, "usage_type": "name"}, {"api_name": "collections.OrderedDict", "line_number": 396, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 398, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 455, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 455, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 457, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 457, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 459, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 459, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 461, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 461, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QIcon", "line_number": 463, "usage_type": "call"}, {"api_name": "PyQt5.QtGui", "line_number": 463, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 468, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 468, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 470, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 470, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 472, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 472, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 474, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 474, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 476, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore", "line_number": 476, "usage_type": "name"}]}
+{"seq_id": "537172855", "text": "import copy\nimport pickle\nimport pytz\nimport sys\nimport unittest\n\nfrom datetime import date, datetime, time, timedelta\n\nfrom backports.datetime_fromisoformat import MonkeyPatch\nMonkeyPatch.patch_fromisoformat()\n\n\nclass TestFromIsoFormat(unittest.TestCase):\n def test_basic_naive_parse(self):\n expected = datetime(2014, 2, 5, 23, 45)\n self.assertEqual(expected, datetime.fromisoformat(expected.isoformat()))\n\n\nclass TestsFromCPython(unittest.TestCase):\n # These test cases are taken from cPython's `Lib/test/datetimetester.py`\n\n def test_fromisoformat(self):\n # Test that isoformat() is reversible\n base_dates = [\n (1, 1, 1),\n (1000, 2, 14),\n (1900, 1, 1),\n (2000, 2, 29),\n (2004, 11, 12),\n (2004, 4, 3),\n (2017, 5, 30)\n ]\n\n for date_cls in [datetime, date]:\n for dt_tuple in base_dates:\n dt = date_cls(*dt_tuple)\n dt_str = dt.isoformat()\n with self.subTest(dt_str=dt_str):\n dt_rt = date_cls.fromisoformat(dt.isoformat())\n\n self.assertEqual(dt, dt_rt)\n self.assertIsInstance(dt_rt, date_cls)\n\n def test_fromisoformat_fails(self):\n # Test that fromisoformat() fails on invalid values\n bad_strs = [\n '', # Empty string\n '009-03-04', # Not 10 characters\n '123456789', # Not a date\n '200a-12-04', # Invalid character in year\n '2009-1a-04', # Invalid character in month\n '2009-12-0a', # Invalid character in day\n '2009-01-32', # Invalid day\n '2009-02-29', # Invalid leap day\n '20090228', # Valid ISO8601 output not from isoformat()\n ]\n\n for bad_str in bad_strs:\n with self.assertRaises(ValueError, msg=\"Did not fail on '{0}'\".format(bad_str)):\n datetime.fromisoformat(bad_str)\n\n with self.assertRaises(ValueError, msg=\"Did not fail on '{0}'\".format(bad_str)):\n date.fromisoformat(bad_str)\n\n def test_fromisoformat_fails_typeerror(self):\n # Test that fromisoformat fails when passed the wrong type\n import io\n\n bad_types = [b'2009-03-01', None, io.StringIO('2009-03-01')]\n for bad_type in bad_types:\n with self.assertRaises(TypeError, msg=\"Did not fail on '{0}'\".format(bad_type)):\n datetime.fromisoformat(bad_type)\n\n with self.assertRaises(TypeError, msg=\"Did not fail on '{0}'\".format(bad_type)):\n date.fromisoformat(bad_type)\n\n def test_fromisoformat_datetime(self):\n # Test that isoformat() is reversible\n base_dates = [\n (1, 1, 1),\n (1900, 1, 1),\n (2004, 11, 12),\n (2017, 5, 30)\n ]\n\n base_times = [\n (0, 0, 0, 0),\n (0, 0, 0, 241000),\n (0, 0, 0, 234567),\n (12, 30, 45, 234567)\n ]\n\n separators = [' ', 'T']\n\n tzinfos = [None, pytz.utc,\n pytz.FixedOffset(-5 * 60),\n pytz.FixedOffset(2 * 60)]\n\n dts = [datetime(*(date_tuple + time_tuple), tzinfo=tzi)\n for date_tuple in base_dates\n for time_tuple in base_times\n for tzi in tzinfos]\n\n for dt in dts:\n for sep in separators:\n dtstr = dt.isoformat(sep=sep)\n\n with self.subTest(dtstr=dtstr):\n dt_rt = datetime.fromisoformat(dtstr)\n self.assertEqual(dt, dt_rt)\n\n def test_fromisoformat_timezone(self):\n base_dt = datetime(2014, 12, 30, 12, 30, 45, 217456)\n\n tzoffsets = [\n timedelta(hours=5),\n timedelta(hours=2),\n timedelta(hours=6, minutes=27),\n\n # Our timezone implementation doesn't handle sub-minute offsets.\n # timedelta(hours=12, minutes=32, seconds=30),\n # timedelta(hours=2, minutes=4, seconds=9, microseconds=123456)\n ]\n\n tzoffsets += [-1 * td for td in tzoffsets]\n\n tzinfos = [None, pytz.utc,\n pytz.FixedOffset(0)]\n\n tzinfos += [pytz.FixedOffset(td.total_seconds() / 60) for td in tzoffsets]\n\n for tzi in tzinfos:\n dt = base_dt.replace(tzinfo=tzi)\n dtstr = dt.isoformat()\n\n with self.subTest(tstr=dtstr):\n dt_rt = datetime.fromisoformat(dtstr)\n assert dt == dt_rt, dt_rt\n\n def test_fromisoformat_separators(self):\n separators = [\n ' ', 'T', '\\u007f', # 1-bit widths\n '\\u0080', 'ʁ', # 2-bit widths\n 'ᛇ', '時', # 3-bit widths\n '🐍' # 4-bit widths\n ]\n\n for sep in separators:\n dt = datetime(2018, 1, 31, 23, 59, 47, 124789)\n dtstr = dt.isoformat(sep=sep)\n\n with self.subTest(dtstr=dtstr):\n dt_rt = datetime.fromisoformat(dtstr)\n self.assertEqual(dt, dt_rt)\n\n def test_fromisoformat_ambiguous(self):\n # Test strings like 2018-01-31+12:15 (where +12:15 is not a time zone)\n separators = ['+', '-']\n for sep in separators:\n dt = datetime(2018, 1, 31, 12, 15)\n dtstr = dt.isoformat(sep=sep)\n\n with self.subTest(dtstr=dtstr):\n dt_rt = datetime.fromisoformat(dtstr)\n self.assertEqual(dt, dt_rt)\n\n def test_fromisoformat_timespecs(self):\n if sys.version_info >= (3, 6):\n datetime_bases = [\n (2009, 12, 4, 8, 17, 45, 123456),\n (2009, 12, 4, 8, 17, 45, 0)]\n\n tzinfos = [None, pytz.utc,\n pytz.FixedOffset(-5 * 60),\n pytz.FixedOffset(2 * 60),\n pytz.FixedOffset(6 * 60 + 27)]\n\n timespecs = ['hours', 'minutes', 'seconds', 'milliseconds', 'microseconds']\n\n for ip, ts in enumerate(timespecs):\n for tzi in tzinfos:\n for dt_tuple in datetime_bases:\n if ts == 'milliseconds':\n new_microseconds = 1000 * (dt_tuple[6] // 1000)\n dt_tuple = dt_tuple[0:6] + (new_microseconds,)\n\n dt = datetime(*(dt_tuple[0:(4 + ip)]), tzinfo=tzi)\n dtstr = dt.isoformat(timespec=ts)\n with self.subTest(dtstr=dtstr):\n dt_rt = datetime.fromisoformat(dtstr)\n self.assertEqual(dt, dt_rt)\n\n def test_fromisoformat_fails_datetime(self):\n # Test that fromisoformat() fails on invalid values\n bad_strs = [\n '', # Empty string\n '2009.04-19T03', # Wrong first separator\n '2009-04.19T03', # Wrong second separator\n '2009-04-19T0a', # Invalid hours\n '2009-04-19T03:1a:45', # Invalid minutes\n '2009-04-19T03:15:4a', # Invalid seconds\n '2009-04-19T03;15:45', # Bad first time separator\n '2009-04-19T03:15;45', # Bad second time separator\n '2009-04-19T03:15:4500:00', # Bad time zone separator\n '2009-04-19T03:15:45.2345', # Too many digits for milliseconds\n '2009-04-19T03:15:45.1234567', # Too many digits for microseconds\n\n # Our timezone implementation doesn't mind > 24h offsets\n # '2009-04-19T03:15:45.123456+24:30', # Invalid time zone offset\n # '2009-04-19T03:15:45.123456-24:30', # Invalid negative offset\n\n '2009-04-10ᛇᛇᛇᛇᛇ12:15', # Too many unicode separators\n '2009-04-19T1', # Incomplete hours\n '2009-04-19T12:3', # Incomplete minutes\n '2009-04-19T12:30:4', # Incomplete seconds\n '2009-04-19T12:', # Ends with time separator\n '2009-04-19T12:30:', # Ends with time separator\n '2009-04-19T12:30:45.', # Ends with time separator\n '2009-04-19T12:30:45.123456+', # Ends with timzone separator\n '2009-04-19T12:30:45.123456-', # Ends with timzone separator\n '2009-04-19T12:30:45.123456-05:00a', # Extra text\n '2009-04-19T12:30:45.123-05:00a', # Extra text\n '2009-04-19T12:30:45-05:00a', # Extra text\n ]\n\n for bad_str in bad_strs:\n with self.subTest(bad_str=bad_str):\n with self.assertRaises(ValueError, msg=\"Did not fail on '{0}'\".format(bad_str)):\n datetime.fromisoformat(bad_str)\n\n # Our timezone implementation doesn't have a concept of UTC being special\n # def test_fromisoformat_utc(self):\n # dt_str = '2014-04-19T13:21:13+00:00'\n # dt = datetime.fromisoformat(dt_str)\n # self.assertIs(dt.tzinfo, pytz.utc)\n\n def test_time_fromisoformat(self):\n tsc = time(12, 14, 45, 203745, tzinfo=pytz.utc)\n tsc_rt = time.fromisoformat(tsc.isoformat())\n\n self.assertEqual(tsc, tsc_rt)\n self.assertIsInstance(tsc_rt, time)\n\n\nclass TestCopy(unittest.TestCase):\n def test_basic_pickle_and_copy(self):\n dt = datetime.fromisoformat('2018-11-01 20:42:09.058000')\n dt2 = pickle.loads(pickle.dumps(dt))\n self.assertEqual(dt, dt2)\n dt3 = copy.deepcopy(dt)\n self.assertEqual(dt, dt3)\n\n # FixedOffset\n dt = datetime.fromisoformat('2018-11-01 20:42:09.058000+01:30')\n dt2 = pickle.loads(pickle.dumps(dt))\n self.assertEqual(dt, dt2)\n dt3 = copy.deepcopy(dt)\n self.assertEqual(dt, dt3)\n\n\nif __name__ == '__main__':\n unittest.main()\n", "sub_path": "tests/tests.py", "file_name": "tests.py", "file_ext": "py", "file_size_in_byte": 9986, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "backports.datetime_fromisoformat.MonkeyPatch.patch_fromisoformat", "line_number": 10, "usage_type": "call"}, {"api_name": "backports.datetime_fromisoformat.MonkeyPatch", "line_number": 10, "usage_type": "name"}, {"api_name": "unittest.TestCase", "line_number": 13, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 15, "usage_type": "call"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 16, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 16, "usage_type": "name"}, {"api_name": "unittest.TestCase", "line_number": 19, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 34, "usage_type": "name"}, {"api_name": "datetime.date", "line_number": 34, "usage_type": "name"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 60, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 60, "usage_type": "name"}, {"api_name": "datetime.date.fromisoformat", "line_number": 63, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 63, "usage_type": "name"}, {"api_name": "io.StringIO", "line_number": 69, "usage_type": "call"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 72, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 72, "usage_type": "name"}, {"api_name": "datetime.date.fromisoformat", "line_number": 75, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 75, "usage_type": "name"}, {"api_name": "pytz.utc", "line_number": 95, "usage_type": "attribute"}, {"api_name": "pytz.FixedOffset", "line_number": 96, "usage_type": "call"}, {"api_name": "pytz.FixedOffset", "line_number": 97, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 99, "usage_type": "call"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 109, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 109, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 113, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 116, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 117, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 118, "usage_type": "call"}, {"api_name": "pytz.utc", "line_number": 127, "usage_type": "attribute"}, {"api_name": "pytz.FixedOffset", "line_number": 128, "usage_type": "call"}, {"api_name": "pytz.FixedOffset", "line_number": 130, "usage_type": "call"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 137, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 137, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 149, "usage_type": "call"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 153, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 153, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 160, "usage_type": "call"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 164, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 164, "usage_type": "name"}, {"api_name": "sys.version_info", "line_number": 168, "usage_type": "attribute"}, {"api_name": "pytz.utc", "line_number": 173, "usage_type": "attribute"}, {"api_name": "pytz.FixedOffset", "line_number": 174, "usage_type": "call"}, {"api_name": "pytz.FixedOffset", "line_number": 175, "usage_type": "call"}, {"api_name": "pytz.FixedOffset", "line_number": 176, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 187, "usage_type": "call"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 190, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 190, "usage_type": "name"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 229, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 229, "usage_type": "name"}, {"api_name": "datetime.time", "line_number": 238, "usage_type": "call"}, {"api_name": "pytz.utc", "line_number": 238, "usage_type": "attribute"}, {"api_name": "datetime.time.fromisoformat", "line_number": 239, "usage_type": "call"}, {"api_name": "datetime.time", "line_number": 239, "usage_type": "name"}, {"api_name": "datetime.time", "line_number": 242, "usage_type": "argument"}, {"api_name": "unittest.TestCase", "line_number": 245, "usage_type": "attribute"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 247, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 247, "usage_type": "name"}, {"api_name": "pickle.loads", "line_number": 248, "usage_type": "call"}, {"api_name": "pickle.dumps", "line_number": 248, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 250, "usage_type": "call"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 254, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 254, "usage_type": "name"}, {"api_name": "pickle.loads", "line_number": 255, "usage_type": "call"}, {"api_name": "pickle.dumps", "line_number": 255, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 257, "usage_type": "call"}, {"api_name": "unittest.main", "line_number": 262, "usage_type": "call"}]}
+{"seq_id": "648779513", "text": "import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport IPython.display as ipd\nimport scipy.signal\nfrom scipy import signal, linalg\nfrom scipy.io import wavfile\nimport math\nfrom find_path import solve\n\n\ndef Hist(img):\n row, col = img.shape \n y = np.zeros(256)\n for i in range(0,row):\n for j in range(0,col):\n y[img[i,j]] += 1\n x = np.arange(0,256)\n # plt.bar(x, y, color='b', width=5, align='center', alpha=0.25)\n # plt.show()\n return y\n\ndef variance(h, s, e):\n v = 0\n m = mean(h, s, e)\n w = wieght(h, s, e)\n for i in range(s, e):\n v += ((i - m) **2) * h[i]\n v /= w\n return v\n\ndef wieght(h, s, e):\n w = 0\n for i in range(s, e):\n w += h[i]\n return w\n\n\ndef mean(h, s, e):\n m = 0\n w = wieght(h, s, e)\n for i in range(s, e):\n m += h[i] * i\n \n return m/float(w)\n\ndef countPixel(h):\n cnt = 0\n for i in range(0, len(h)):\n if h[i]>0:\n cnt += h[i]\n return cnt\n\ndef threshold(h, threshold_values):\n cnt = countPixel(h)\n for i in range(1, len(h)):\n vb = variance(h, 0, i)\n wb = wieght(h, 0, i) / float(cnt)\n mb = mean(h, 0, i)\n \n vf = variance(h, i, len(h))\n wf = wieght(h, i, len(h)) / float(cnt)\n mf = mean(h, i, len(h))\n \n V2w = wb * (vb) + wf * (vf)\n V2b = wb * wf * (mb - mf)**2\n \n # fw = open(\"trace.txt\", \"a\")\n # fw.write('T='+ str(i) + \"\\n\")\n\n # fw.write('Wb='+ str(wb) + \"\\n\")\n # fw.write('Mb='+ str(mb) + \"\\n\")\n # fw.write('Vb='+ str(vb) + \"\\n\")\n \n # fw.write('Wf='+ str(wf) + \"\\n\")\n # fw.write('Mf='+ str(mf) + \"\\n\")\n # fw.write('Vf='+ str(vf) + \"\\n\")\n\n # fw.write('within class variance='+ str(V2w) + \"\\n\")\n # fw.write('between class variance=' + str(V2b) + \"\\n\")\n # fw.write(\"\\n\")\n \n if not math.isnan(V2w):\n threshold_values[i] = V2w\n\ndef regenerate_img(img, threshold):\n row, col = img.shape \n y = np.zeros((row, col))\n for i in range(0,row):\n for j in range(0,col):\n if img[i,j] >= threshold:\n y[i,j] = 255\n else:\n y[i,j] = 0\n return y\n\ndef binarize(img, offest = 0):\n threshold_values = {}\n h = [1]\n h = Hist(img.astype(int))\n threshold(h, threshold_values)\n op_thres = get_optimal_threshold(threshold_values)\n res = regenerate_img(img, op_thres + offest)\n return res\n\ndef get_optimal_threshold(threshold_values):\n min_V2w = min(threshold_values.values())\n optimal_threshold = [k for k, v in threshold_values.items() if v == min_V2w]\n return optimal_threshold[0]\n\ndef gkern(size=5, sigma=1.0):\n \"\"\"\n Returns a gaussian kernel with zero mean.\n \n Adapted from:\n https://stackoverflow.com/questions/29731726/how-to-calculate-a-gaussian-kernel-matrix-efficiently-in-numpy\n \n Parameters:\n size - Sidelength of gaussian kernel\n sigma - Value of standard deviation\n \"\"\"\n ax = np.arange(-size // 2 + 1.0, size // 2 + 1.0)\n xx, yy = np.meshgrid(ax, ax)\n kernel = np.exp(-(xx**2 + yy**2) / (2.0 * sigma**2))\n return kernel / np.sum(kernel)\n\ndef rgb2gray(rgb):\n\n r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]\n gray = 0.2989 * r + 0.5870 * g + 0.1140 * b\n \n gray = gray / np.max(gray) * 255\n \n return gray\n\ndef post_porcess(img, whiten_radius = 1, whiten_thres = 3, blacken_radius = 4):\n h, w = img.shape\n ref = img.copy()\n for i in range(h):\n for j in range(w):\n if img[i,j] == 0:\n count = 0\n for i0 in range(max(0, i-whiten_radius), min(h, i + whiten_radius)):\n for j0 in range(max(0, j-whiten_radius), min(w, j + whiten_radius)):\n if not img[i0, j0]:\n count += 1\n if count <= whiten_thres:\n ref[i,j] = 255\n img = ref.copy()\n\n for i in range(h):\n for j in range(w):\n if ref[i,j]:\n flag = False\n for i0 in range(max(0, i-blacken_radius), min(h, i + blacken_radius)):\n if flag:\n break\n for j0 in range(max(0, j-blacken_radius), min(w, j + blacken_radius)):\n if not ref[i0, j0]:\n flag = True\n break\n if flag:\n img[i,j] = 0\n return img\n\n\ndef auto_canny(image, sigma=0.33):\n # compute the median of the single channel pixel intensities\n v = np.median(image)\n \n # apply automatic Canny edge detection using the computed median\n lower = int(max(0, (1.0 - sigma) * v))\n upper = int(min(255, (1.0 + sigma) * v))\n# lower = 100\n# upper = 200\n edged = cv2.Canny(image, lower, upper)\n \n # return the edged image\n return edged\n\ndef find(img, screen_corner, ideal, start, goal):\n img = rgb2gray(img)\n\n\n cv2.imwrite('/home/cc/ee106a/fa19/class/ee106a-adt/ros_workspaces/proj/src/vision/imgs/img.png', img)\n height_0, width_0 = img.shape\n height, width = ideal[3][0], ideal[3][1]\n\n ref = np.ones(img.shape)*255\n for i, j, in screen_corner[0:1]:\n for i0 in range(-20, 20):\n for j0 in range(-20, 20):\n if height_0 > i+i0 >= 0 and width_0 > j + j0 >= 0:\n ref[i+i0,j+j0] = 0\n cv2.imwrite('/home/cc/ee106a/fa19/class/ee106a-adt/ros_workspaces/proj/src/vision/imgs/ref1.png', ref)\n\n ref = np.ones(img.shape)*255\n for i, j, in screen_corner[1:2]:\n for i0 in range(-20, 20):\n for j0 in range(-20, 20):\n if height_0 > i+i0 >= 0 and width_0 > j + j0 >= 0:\n ref[i+i0,j+j0] = 0\n cv2.imwrite('/home/cc/ee106a/fa19/class/ee106a-adt/ros_workspaces/proj/src/vision/imgs/ref2.png', ref)\n\n ref = np.ones(img.shape)*255\n for i, j, in screen_corner[2:3]:\n for i0 in range(-20, 20):\n for j0 in range(-20, 20):\n if height_0 > i+i0 >= 0 and width_0 > j + j0 >= 0:\n ref[i+i0,j+j0] = 0\n cv2.imwrite('/home/cc/ee106a/fa19/class/ee106a-adt/ros_workspaces/proj/src/vision/imgs/ref3.png', ref)\n\n ref = np.ones(img.shape)*255\n for i, j, in screen_corner[3:4]:\n for i0 in range(-20, 20):\n for j0 in range(-20, 20):\n if height_0 > i+i0 >= 0 and width_0 > j + j0 >= 0:\n ref[i+i0,j+j0] = 0\n cv2.imwrite('/home/cc/ee106a/fa19/class/ee106a-adt/ros_workspaces/proj/src/vision/imgs/ref4.png', ref)\n\n\n def average(im, n, x, y):\n count = 0\n total = 0\n for i in range(n):\n for j in range(n):\n if (height > i+x>=0 and width >y+j>=0):\n total += im[i+x, y+j]\n count += 1\n return total/count\n\n M, mask = cv2.findHomography(screen_corner.reshape(-1, 1, 2), ideal.reshape(-1, 1, 2), method = 0)\n\n out = np.zeros((height, width))\n ref = np.zeros((height, width))\n for i in range(height_0):\n for j in range(width_0):\n a = np.dot(M,np.array([i,j,1]))\n a /= a[2]\n a = a.astype(int)\n if (height > a[0]>=0 and width >a[1]>=0):\n out[a[0], a[1]] += img[i,j]\n ref[a[0], a[1]] = 255\n cv2.imwrite('/home/cc/ee106a/fa19/class/ee106a-adt/ros_workspaces/proj/src/vision/imgs/out1.png', out)\n out2 = out.copy()\n for i in range(height):\n for j in range(width):\n if not ref[i,j]:\n out2[i,j] = average(out2, 5, i, j)\n\n cv2.imwrite('/home/cc/ee106a/fa19/class/ee106a-adt/ros_workspaces/proj/src/vision/imgs/out2.png', out2)\n\n kern = gkern(5, 5)\n\n\n blurred = scipy.signal.convolve2d(out2, kern, mode=\"same\")\n blurred = blurred/ np.max(blurred) * 255\n\n\n ref = binarize(blurred, 40)\n print(start, goal)\n i,j = start\n for i0 in range(-5, 5):\n for j0 in range(-5, 5):\n if height > i+i0 >= 0 and width > j + j0 >= 0:\n ref[i+i0,j+j0] = 0\n cv2.imwrite('/home/cc/ee106a/fa19/class/ee106a-adt/ros_workspaces/proj/src/vision/imgs/start2.png', ref)\n\n ref = np.ones(blurred.shape)*255\n print(start, goal)\n i,j = start\n for i0 in range(-5, 5):\n for j0 in range(-5, 5):\n if height > i+i0 >= 0 and width > j + j0 >= 0:\n ref[i+i0,j+j0] = 0\n cv2.imwrite('/home/cc/ee106a/fa19/class/ee106a-adt/ros_workspaces/proj/src/vision/imgs/start.png', ref)\n\n ref = binarize(blurred, 40)\n i, j = goal\n print(goal)\n for i0 in range(-5, 5):\n for j0 in range(-5, 5):\n if height > i+i0 >= 0 and width > j + j0 >= 0:\n ref[i+i0,j+j0] = 0\n cv2.imwrite('/home/cc/ee106a/fa19/class/ee106a-adt/ros_workspaces/proj/src/vision/imgs/goal2.png', ref)\n\n ref = np.ones(blurred.shape)*255\n i, j = goal\n print(goal)\n for i0 in range(-5, 5):\n for j0 in range(-5, 5):\n if height > i+i0 >= 0 and width > j + j0 >= 0:\n ref[i+i0,j+j0] = 0\n cv2.imwrite('/home/cc/ee106a/fa19/class/ee106a-adt/ros_workspaces/proj/src/vision/imgs/goal.png', ref)\n\n j = 0\n path = None\n for i in range(60, -20, -5):\n binary = binarize(blurred, i)\n # cv2.imwrite(str(j)+'binary_' + str(i) +'.png', binary)\n binary = post_porcess(binary)\n # i,j = start\n # for i0 in range(-5, 5):\n # for j0 in range(-5, 5):\n # if height > i+i0 >= 0 and width > j + j0 >= 0:\n # binary[i+i0,j+j0] = 0\n # i,j = goal\n # for i0 in range(-5, 5):\n # for j0 in range(-5, 5):\n # if height > i+i0 >= 0 and width > j + j0 >= 0:\n # binary[i+i0,j+j0] = 0\n\n\n j += 1\n cv2.imwrite('/home/cc/ee106a/fa19/class/ee106a-adt/ros_workspaces/proj/src/vision/imgs/' + str(j)+'binary_post' + str(i) +'.png', binary)\n binary = binary <= 0\n flag = False\n for i in range(-5,5):\n for j in range(-5,5):\n if not binary[start[0] + i][start[1] + j]:\n start0 = np.array([start[0] + i, start[1] + j])\n flag = True\n if not flag:\n print('start not found')\n continue\n flag = False \n for i in range(-10, 10):\n for j in range(-10,10):\n if not binary[goal[0] + i][goal[1] + j]:\n goal0 = np.array([goal[0] + i, goal[1] + j])\n flag = True\n if not flag:\n print('goal not found')\n continue\n \n print(start0, goal0) \n path = solve(binary, start0, goal0)\n if path:\n return path\n\n\n\n\n # blurred = scipy.signal.convolve2d(out2, kern, mode=\"same\")\n # blurred = blurred/ np.max(blurred) * 255\n # binary = binarize(blurred)\n # cv2.imwrite('binary_2.png', binary)\n # paths.append(find_path_bfs(binary))\n\n # binary2 = post_porcess(binary)\n # cv2.imwrite('binary_2_post.png', binary2)\n # paths.append(find_path_bfs(binary2))\n\n # binary = post_porcess(binary, blacken_radius = 2)\n # cv2.imwrite('binary_2_post_2.png', binary)\n # paths.append(find_path_bfs(binary))\n\n\n # blurred = scipy.signal.convolve2d(out2, kern, mode=\"same\")\n # blurred = blurred/ np.max(blurred) * 255\n # binary = binarize(blurred)\n # cv2.imwrite('binary_3.png', binary)\n # paths.append(find_path_bfs(binary))\n\n # binary2 = post_porcess(binary)\n # cv2.imwrite('binary_3_post.png', binary2)\n # paths.append(find_path_bfs(binary2))\n\n # binary = post_porcess(binary, blacken_radius = 2)\n # cv2.imwrite('binary_3_post_2.png', binary)\n # paths.append(find_path_bfs(binary))\n\n # blurred = scipy.signal.convolve2d(out2, kern, mode=\"same\")\n # blurred = blurred/ np.max(blurred) * 255\n # binary = binarize(blurred)\n # cv2.imwrite('binary_4.png', binary)\n # paths.append(find_path_bfs(binary))\n\n # binary2 = post_porcess(binary)\n # cv2.imwrite('binary_4_post.png', binary2)\n # paths.append(find_path_bfs(binary2))\n\n # binary = post_porcess(binary, blacken_radius = 2)\n # cv2.imwrite('binary_4_post_2.png', binary)\n # paths.append(find_path_bfs(binary))\n\n\n\n# img = cv2.imread('Screenshot at 2019-12-10 11_18_43.png')\n# screen_corner = np.array([[610, 650], [800, 600], [600, 950], [750, 1000]])\n# ideal = np.array([[0,0], [100,0],[0,140], [100,140]])\n# find(img, screen_corner, ideal)", "sub_path": "vision/src/image_processing.py", "file_name": "image_processing.py", "file_ext": "py", "file_size_in_byte": 12564, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "numpy.zeros", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 18, "usage_type": "call"}, {"api_name": "math.isnan", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 122, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 124, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 125, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 132, "usage_type": "call"}, {"api_name": "numpy.median", "line_number": 169, "usage_type": "call"}, {"api_name": "cv2.Canny", "line_number": 176, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 185, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 189, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 195, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 197, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 203, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 205, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 211, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 213, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 219, "usage_type": "call"}, {"api_name": "cv2.findHomography", "line_number": 232, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 234, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 235, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 238, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 238, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 244, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 251, "usage_type": "call"}, {"api_name": "scipy.signal.signal.convolve2d", "line_number": 256, "usage_type": "call"}, {"api_name": "scipy.signal.signal", "line_number": 256, "usage_type": "attribute"}, {"api_name": "scipy.signal", "line_number": 256, "usage_type": "name"}, {"api_name": "numpy.max", "line_number": 257, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 267, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 269, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 276, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 285, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 287, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 294, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 315, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 321, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 330, "usage_type": "call"}, {"api_name": "find_path.solve", "line_number": 337, "usage_type": "call"}]}
+{"seq_id": "144211308", "text": "\"\"\" User Interface (UI) module \"\"\"\nimport common\n\n\ndef get_width_columns(table, title_list):\n \"\"\"\n Find the longest width in table.\n :param table: table to display - text file where are included some information.\n :return: List with width of columns.\n \"\"\"\n number_of_columns = len(table[0])\n file_columns_width = [max([len(data[index]) for data in table])\n for index in range(number_of_columns)]\n\n titles_width = (list(len(title) for title in title_list))\n width_columns = [file_columns_width[index] if file_columns_width[index] >\n titles_width[index] else titles_width[index]\n for index in range(number_of_columns)]\n\n return width_columns\n\n\n\ndef get_position_value_dictionary(table, title_list):\n \"\"\"\n Create a dictionary with position and column width. Is need to **kwargs\n in print table function.\n :return: Dictionary with position:column width\n \"\"\"\n width_columns = get_width_columns(table, title_list)\n number_of_columns = len(width_columns)\n string_positions = [\"pos\" + str(index) for index in range(number_of_columns)]\n position_value = dict(zip(string_positions, width_columns))\n\n return position_value\n\n\ndef get_total_sum_of_width_columns(table, title_list):\n \"\"\"\n Calcualte total sum of width in each column.\n :param table: table: table to display - text file where are included some information.\n :param title_list: title_list: list containing table headers\n :return: Sum of width\n \"\"\"\n width_columns = get_width_columns(table, title_list)\n total_column_lenght = common.sum_values(width_columns) + 1 # due to end in var:string \"|\"\n number_of_columns = len(width_columns)\n PADDINGS = 3\n\n total_width_sum = total_column_lenght + (number_of_columns * PADDINGS)\n return total_width_sum\n\n\ndef print_table(table, title_list):\n \"\"\"\n Prints table with data.\n :param table: table to display - text file where are included some information.\n :param title_list: list containing table headers\n \"\"\"\n dict_pos_value = get_position_value_dictionary(table, title_list)\n total_width_sum = get_total_sum_of_width_columns(table, title_list)\n string = ''.join(['| {:^{' + pos + '}} ' for pos in dict_pos_value.keys()]) + \"|\"\n\n print(\"-\" * total_width_sum)\n print(string.format(*title_list, **dict_pos_value))\n\n print(\"-\" * total_width_sum)\n for record in table:\n print(string.format(*record, **dict_pos_value))\n print(\"-\" * total_width_sum)\n\n\ndef print_result(result, label):\n \"\"\"\n Displays results of the special functions.\n\n Args:\n result: result of the special function (string, list or dict)\n label (str): label of the result\n\n Returns:\n None: This function doesn't return anything it only prints to console.\n \"\"\"\n\n # your code\n\n\ndef print_menu(title, list_options, exit_message):\n \"\"\"\n Displays a menu.\n :param title: menu title\n :param list_options: list of strings - options that will be shown in menu\n :param exit_message: option for back to main menu\n \"\"\"\n print(\"{}:\" .format(title))\n i = 1\n for option in list_options:\n print(\"({}) {}\" .format(i, option))\n i += 1\n print(\"(0) {}\" .format(exit_message))\n\n\ndef get_inputs(list_labels, title):\n \"\"\"\n Gets list of inputs from the user.\n :param list_labels: labels of inputs\n :param title: title of the \"input section\"\n :return: list of data given by the user\n \"\"\"\n print(\"{}:\" .format(title))\n inputs = []\n for label in list_labels:\n answers = input(\"{}: \" .format(label))\n inputs.append(answers)\n\n return inputs\n\n\ndef print_error_message(message):\n \"\"\"\n Displays an error message\n :param message: error message to be displayed\n \"\"\"\n print(\"{}\" .format(message))\n", "sub_path": "ui.py", "file_name": "ui.py", "file_ext": "py", "file_size_in_byte": 3866, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "common.sum_values", "line_number": 46, "usage_type": "call"}]}
+{"seq_id": "321176917", "text": "# Copyright The PyTorch Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nAzure Machine Learning\n----------------------\n\"\"\"\n\n\nimport uuid\nfrom typing import Optional\n\nfrom pytorch_lightning.loggers import MLFlowLogger\n\ntry:\n from azureml.core import Run as AzureMlRun\nexcept ImportError: # pragma: no-cover\n AzureMlOfflineRun = None\n _AZURE_ML_AVAILABLE = False\nelse:\n _AZURE_ML_AVAILABLE = True\n\n\nclass AzureMlLogger(MLFlowLogger):\n r\"\"\"\n Log using `Azure Machine Learning `_.\n Install it with pip:\n\n .. code-block:: bash\n\n pip install mlflow azureml-mlflow\n\n The Azure Machine Learning logger will log to standard output if running in\n offline mode, or to\n `Azure Machine Learning metrics `_\n via\n `MLFlow `_\n if running remotely.\n\n **Online and offline mode**\n\n Example::\n\n from azureml.core import Run\n from pytorch_lightning.loggers import AzureMlLogger\n\n # Optional: this is the default value if no run argument is provided.\n run = Run.get_context()\n azureml_logger = AzureMlLogger(run)\n trainer = Trainer(max_epochs=10, logger=azureml_logger)\n\n Args:\n run: Optionally inject Azure Machine Learning `Run` object directly.\n If this is not provided, default to `Run.get_context()`.\n \"\"\"\n\n def __init__(self, run: Optional[AzureMlRun] = None):\n\n if not _AZURE_ML_AVAILABLE:\n raise ImportError(\n \"You want to use `azureml-sdk` logger which is not installed yet,\"\n \" install it with `pip install azureml-sdk`.\"\n )\n\n if run is None:\n run = AzureMlRun.get_context(allow_offline=True)\n\n try:\n experiment = run.experiment\n tracking_uri = experiment.workspace.get_mlflow_tracking_uri()\n experiment_name = experiment.name\n except AttributeError:\n tracking_uri = None\n experiment_name = str(uuid.uuid4())\n\n super().__init__(experiment_name, tracking_uri)\n", "sub_path": "pl_bolts/loggers/azureml.py", "file_name": "azureml.py", "file_ext": "py", "file_size_in_byte": 2759, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "pytorch_lightning.loggers.MLFlowLogger", "line_number": 35, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 68, "usage_type": "name"}, {"api_name": "azureml.core.Run", "line_number": 68, "usage_type": "name"}, {"api_name": "azureml.core.Run.get_context", "line_number": 77, "usage_type": "call"}, {"api_name": "azureml.core.Run", "line_number": 77, "usage_type": "name"}, {"api_name": "uuid.uuid4", "line_number": 85, "usage_type": "call"}]}
+{"seq_id": "375723516", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nhttps://colab.research.google.com/github/pytorch/pytorch.github.io/blob/master/assets/hub/facebookresearch_pytorch-gan-zoo_pgan.ipynb\nhttps://github.com/pytorch/pytorch/blob/98362d11ffe81ca48748f6b0e1e417cb81ba5998/torch/hub.py#L330\n the following models only: alexnet, densenet121, densenet169, densenet201,\\\n densenet161, inception_v3, resnet18, resnet34, resnet50, resnet101, resnet152,\\\n resnext50_32x4d, resnext101_32x8d, wide_resnet50_2, wide_resnet101_2, squeezenet1_0,\\\n squeezenet1_1, vgg11, vgg13, vgg16, vgg19, vgg11_bn, vgg13_bn, vgg16_bn, vgg19_bn,\\\n googlenet, shufflenet_v2_x0_5, shufflenet_v2_x1_0, mobilenet_v2\"\n assert _model in ['alexnet', 'densenet121', 'densenet169', 'densenet201', 'densenet161', \n 'inception_v3', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152', \n 'resnext50_32x4d', 'resnext101_32x8d', 'wide_resnet50_2', 'wide_resnet101_2',\n 'squeezenet1_0', 'squeezenet1_1', 'vgg11', 'vgg13', 'vgg16', 'vgg19', 'vgg11_bn',\n 'vgg13_bn', 'vgg16_bn', 'vgg19_bn', 'googlenet', 'shufflenet_v2_x0_5', \n 'shufflenet_v2_x1_0', 'mobilenet_v2'],\\\n \"Pretrained models are available for \\\n the following models only: alexnet, densenet121, densenet169, densenet201,\\\n densenet161, inception_v3, resnet18, resnet34, resnet50, resnet101, resnet152,\\\n resnext50_32x4d, resnext101_32x8d, wide_resnet50_2, wide_resnet101_2, squeezenet1_0,\\\n squeezenet1_1, vgg11, vgg13, vgg16, vgg19, vgg11_bn, vgg13_bn, vgg16_bn, vgg19_bn,\\\n googlenet, shufflenet_v2_x0_5, shufflenet_v2_x1_0, mobilenet_v2\"\n\"\"\"\nimport os, json\nimport copy\nfrom pathlib import Path\n\nimport torch\nimport torch.optim as optim\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms\nfrom torch import hub \n\nfrom mlmodels.util import os_package_root_path, log, path_norm, get_model_uri, path_norm_dict\nMODEL_URI = get_model_uri(__file__)\n\n# CV datasets come in various formats, we should write a dataloader for each dataset\n# I assume that the dataloader (itrator) will be ready and imported from another file\n\n###########################################################################################################\n###########################################################################################################\ndef _train(m, device, train_itr, criterion, optimizer, epoch, max_epoch, imax=1):\n m.train()\n corrects, train_loss = 0.0,0.0\n\n for i,batch in enumerate(train_itr):\n if i >= imax: break\n\n image, target = batch[0], batch[1]\n image, target = image.to(device), target.to(device)\n optimizer.zero_grad()\n logit = m(image)\n \n loss = criterion(logit, target)\n loss.backward()\n optimizer.step()\n \n train_loss += loss.item()\n result = torch.max(logit,1)[1]\n corrects += (result.view(target.size()).data == target.data).sum()\n \n size = len(train_itr)\n train_loss /= size \n accuracy = 100.0 * corrects/size\n \n return train_loss, accuracy\n \ndef _valid(m, device, test_itr, criterion, imax=1):\n m.eval()\n corrects, test_loss = 0.0,0.0\n for i,batch in enumerate(test_itr):\n if i >= imax: break\n \n image, target = batch[0], batch[1]\n image, target = image.to(device), target.to(device)\n \n logit = m(image)\n loss = criterion(logit, target)\n\n \n test_loss += loss.item()\n result = torch.max(logit,1)[1]\n corrects += (result.view(target.size()).data == target.data).sum()\n \n size = len(test_itr)\n test_loss /= size \n accuracy = 100.0 * corrects/size\n \n return test_loss, accuracy\n\ndef _get_device():\n # use GPU if it is available\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n return device\n\ndef get_config_file():\n return path_norm('config/model_tch/Imagecnn.json')\n\n\n\n\n\n###########################################################################################################\n###########################################################################################################\nclass Model:\n def __init__(self, model_pars=None, data_pars=None, compute_pars=None, out_pars=None):\n self.model_pars = copy.deepcopy(model_pars)\n self.compute_pars = copy.deepcopy(compute_pars)\n self.data_pars = copy.deepcopy(data_pars)\n m = model_pars \n\n ### Model Structure ################################\n if model_pars is None :\n self.model = None\n return None\n\n #### Progressive GAN ################################\n if m['repo_uri'] == 'facebookresearch/pytorch_GAN_zoo:hub' :\n #'DCGAN',\n self.model = torch.hub.load(m['repo_uri'],\n m.get('model', 'PGAN'), \n model_name = m.get('model_name', 'celebAHQ-512'),\n pretrained = bool( m.get('pretrained', True)), \n useGPU = compute_pars.get('use_gpu', _get_device()) )\n return None\n \n\n #### Other CNN models ################################\n num_classes = m['num_classes']\n _model = m['model']\n self.model = hub.load( m['repo_uri'], _model, \n # model_name = m.get(\"model_name\", m['model']),\n pretrained = bool( m.get('pretrained', True)),\n # useGPU = m.get('use_gpu',False)\n ) \n\n if num_classes != 1000:\n fc_in_features = self.model.fc.in_features\n self.model.fc = nn.Linear(fc_in_features, num_classes)\n\n\n\n\ndef get_params(param_pars=None, **kw):\n pp = param_pars\n choice = pp['choice']\n config_mode = pp['config_mode']\n data_path = pp['data_path']\n\n if choice == \"json\":\n data_path = path_norm(data_path)\n cf = json.load(open(data_path, mode='r'))\n cf = cf[config_mode]\n\n ####Normalize path : add /models/dataset/\n cf['data_pars'] = path_norm_dict(cf['data_pars'])\n cf['out_pars'] = path_norm_dict(cf['out_pars'])\n\n return cf['model_pars'], cf['data_pars'], cf['compute_pars'], cf['out_pars']\n\n else:\n raise Exception(f\"Not support choice {choice} yet\")\n\n\n\n\n# def get_dataset(data_pars=None, **kw):\n\n# #if data_pars['dataset'] == 'MNIST':\n# # train_loader, valid_loader = get_dataset_mnist_torch(data_pars)\n# # return train_loader, valid_loader \n# from mlmodels.preprocess.generic import get_dataset_torch\n\n# if data_pars['dataset'] :\n# train_loader, valid_loader = get_dataset_torch(data_pars)\n# return train_loader, valid_loader \n\n# else:\n# raise Exception(\"dataset not provided \")\n# return 0\n\n\ndef get_dataset(data_pars=None, **kw):\n\n #if data_pars['dataset'] == 'MNIST':\n # train_loader, valid_loader = get_dataset_mnist_torch(data_pars)\n # return train_loader, valid_loader \n from mlmodels.dataloader import DataLoader\n\n loader = DataLoader(data_pars)\n\n if data_pars['data_info']['dataset'] :\n loader.compute()\n try:\n (train_loader, valid_loader), internal_states = loader.get_data()\n except:\n raise Exception(\"the last Preprocessor have to return (train_loader, valid_loader), internal_states.\")\n \n return train_loader, valid_loader \n\n else:\n raise Exception(\"dataset not provided \")\n return 0\n\n\n\n\ndef fit(model, data_pars=None, compute_pars=None, out_pars=None, **kwargs):\n model0 = model.model\n lr = compute_pars['learning_rate']\n epochs = compute_pars[\"epochs\"]\n criterion = nn.CrossEntropyLoss()\n device = _get_device()\n model0.to(device)\n train_loss = []\n train_acc = []\n test_loss = []\n test_acc = []\n best_test_acc = -1\n \n optimizer = optim.Adam(model0.parameters(), lr=lr)\n train_iter, valid_iter = get_dataset(data_pars)\n\n imax_train = compute_pars.get('max_batch_sample', len(train_iter) )\n imax_valid = compute_pars.get('max_batch_sample', len(valid_iter) )\n\n os.makedirs(out_pars[\"checkpointdir\"], exist_ok=True)\n \n for epoch in range(1, epochs + 1):\n #train loss\n tr_loss, tr_acc = _train(model0, device, train_iter, criterion, optimizer, epoch, epochs, imax=imax_train)\n print( f'Train Epoch: {epoch} \\t Loss: {tr_loss} \\t Accuracy: {tr_acc}')\n\n\n ts_loss, ts_acc = _valid(model0, device, valid_iter, criterion, imax=imax_valid)\n print( f'Train Epoch: {epoch} \\t Loss: {ts_loss} \\t Accuracy: {ts_acc}')\n\n if ts_acc > best_test_acc:\n best_test_acc = ts_acc\n #save paras(snapshot)\n print( f\"model saves at {best_test_acc} accuracy\")\n torch.save(model0.state_dict(), os.path.join(out_pars[\"checkpointdir\"], \"best_accuracy\"))\n\n train_loss.append(tr_loss)\n train_acc.append(tr_acc)\n test_loss.append(ts_loss)\n test_acc.append(ts_acc)\n\n model.model = model0\n return model, None\n\n\ndef predict(model, session=None, data_pars=None, compute_pars=None, out_pars=None, imax = 1, return_ytrue=1):\n ###### Progressive GAN\n if model.model_pars['repo_uri'] == 'facebookresearch/pytorch_GAN_zoo:hub' :\n model0 = model.model \n num_images = compute_pars.get('num_images', 4)\n noise, _ = model0.buildNoiseData(num_images)\n with torch.no_grad():\n generated_images = model0.test(noise)\n\n # let's plot these images using torchvision and matplotlib\n import matplotlib.pyplot as plt\n import torchvision\n grid = torchvision.utils.make_grid(generated_images.clamp(min=-1, max=1), scale_each=True, normalize=True)\n plt.imshow(grid.permute(1, 2, 0).cpu().numpy())\n # plt.show()\n\n os.makedirs(out_pars['path'], exist_ok=True)\n plt.savefig(out_pars['path'] + \"/img_01.png\")\n os.system(\"ls \" + out_pars['path'])\n return 0\n \n\n ###### CNN models\n import numpy as np\n from mlmodels.metrics import metrics_eval\n device = _get_device()\n model = model.model\n _, test_iter = get_dataset(data_pars=data_pars)\n\n # test_iter = get_dataset(data_pars, out_pars)\n y_pred = []\n y_true = []\n for i,batch in enumerate(test_iter):\n if i >= imax: break\n image, target = batch[0], batch[1]\n image = image.to(device)\n logit = model(image)\n predictions = torch.max(logit,1)[1].cpu().numpy()\n y_pred.append(predictions)\n y_true.append(target)\n y_pred = np.vstack(y_pred)[0]\n y_true = np.vstack(y_true)[0]\n\n return y_pred, y_true if return_ytrue else y_pred\n\n\ndef evaluate(model, data_pars=None, compute_pars=None, out_pars=None):\n pass\n\n\ndef save(model, session=None, save_pars=None):\n import pickle\n from mlmodels.util import save_tch\n save2 = copy.deepcopy(save_pars)\n path = path_norm( save_pars['path'] + \"/torch_model/\")\n os.makedirs(Path(path), exist_ok = True)\n\n\n ### Specialized part\n save2['path'] = path\n save_tch(model=model, save_pars=save2)\n\n\n ### Setup Model\n d = {\"model_pars\" : model.model_pars, \n \"compute_pars\": model.compute_pars,\n \"data_pars\" : model.data_pars\n }\n pickle.dump(d, open(path + \"/torch_model_pars.pkl\", mode=\"wb\"))\n log(path, os.listdir(path))\n\n\ndef load(load_pars):\n from mlmodels.util import load_tch\n import pickle\n load_pars2 = copy.deepcopy(load_pars)\n path = path_norm( load_pars['path'] + \"/torch_model/\" )\n\n ### Setup Model\n d = pickle.load( open(path + \"/torch_model_pars.pkl\", mode=\"rb\") )\n model = Model(model_pars= d['model_pars'], compute_pars= d['compute_pars'],\n data_pars= d['data_pars']) \n\n ### Specialized part\n load_pars2['path'] = path\n model2 = load_tch(load_pars2)\n model.model = model2.model\n\n return model\n\n\n\n###########################################################################################################\n###########################################################################################################\ndef test(data_path=\"dataset/\", pars_choice=\"json\", config_mode=\"test\"):\n ### Local test\n\n log(\"#### Loading params ##############################################\")\n param_pars = {\"choice\":pars_choice, \"data_path\":data_path, \"config_mode\": config_mode}\n model_pars, data_pars, compute_pars, out_pars = get_params(param_pars)\n log( data_pars, out_pars )\n\n log(\"#### Loading dataset #############################################\")\n xtuple = get_dataset(data_pars)\n\n\n log(\"#### Model init, fit #############################################\")\n session = None\n model = Model(model_pars, data_pars, compute_pars)\n model, session = fit(model, data_pars, compute_pars, out_pars)\n\n\n log(\"#### Predict #####################################################\")\n ypred = predict(model, session, data_pars, compute_pars, out_pars)\n\n\n log(\"#### metrics #####################################################\")\n metrics_val = evaluate(model, data_pars, compute_pars, out_pars)\n print(metrics_val)\n\n\n log(\"#### Plot ########################################################\")\n\n\n log(\"#### Save #########################################################\")\n save_pars = { \"path\": out_pars[\"path\"] }\n save(model=model, save_pars=save_pars)\n\n\n log(\"#### Load ########################################################\")\n model2 = load( save_pars )\n # ypred = predict(model2, data_pars=data_pars, compute_pars=compute_pars, out_pars=out_pars)\n print(model2)\n\n\n\ndef test2(data_path=\"dataset/\", pars_choice=\"json\", config_mode=\"test\"):\n ### Local test\n\n log(\"#### Loading params ##############################################\")\n param_pars = {\"choice\":pars_choice, \"data_path\":data_path, \"config_mode\": config_mode}\n model_pars, data_pars, compute_pars, out_pars = get_params(param_pars)\n log( data_pars, out_pars )\n\n log(\"#### Loading dataset #############################################\")\n #xtuple = get_dataset(data_pars)\n\n\n log(\"#### Model init, fit #############################################\")\n session = None\n model = Model(model_pars, data_pars, compute_pars)\n #model, session = fit(model, data_pars, compute_pars, out_pars)\n\n\n log(\"#### Predict #####################################################\")\n predict(model, session, data_pars, compute_pars, out_pars)\n\n\n log(\"#### metrics #####################################################\")\n #metrics_val = evaluate(model, data_pars, compute_pars, out_pars)\n #print(metrics_val)\n\n\n log(\"#### Plot ########################################################\")\n\n\n log(\"#### Save/Load ###################################################\")\n save_pars = { \"path\": out_pars[\"path\"] }\n save(model=model, save_pars=save_pars)\n model2 = load( save_pars )\n ypred = predict(model2, data_pars=data_pars, compute_pars=compute_pars, out_pars=out_pars)\n print(model2)\n\n\nif __name__ == \"__main__\":\n\n #### CNN Type\n # test(data_path=\"model_tch/torchhub_cnn_list.json\", pars_choice=\"json\", config_mode=\"resnet18\")\n test(data_path=\"dataset/json/refactor/resnet18_benchmark_mnist.json\", pars_choice=\"json\", config_mode=\"test\")\n\n\n\n #### GAN Type\n # test2(data_path=\"model_tch/torchhub_gan_list.json\", pars_choice=\"json\", config_mode=\"PGAN\")\n test2(data_path=\"dataset/json/refactor/torchhub_cnn_dataloader.json\", pars_choice=\"json\", config_mode=\"test\")\n\n\n\n\n\n\n\n\"\"\"\ndef get_dataset2(data_pars=None, **kw):\n import importlib\n \n from torchvision import datasets, transforms\n data_path = data_pars['data_path']\n train_batch_size = data_pars['train_batch_size']\n test_batch_size = data_pars['test_batch_size']\n try:\n transform=transforms.Compose([\n transforms.Grayscale(num_output_channels=3),\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])\n dset = getattr(importlib.import_module(\"torchvision.datasets\"), data_pars[\"dataset\"])\n train_loader = torch.utils.data.DataLoader( dset(data_pars['data_path'], train=True, download=True, transform= transform),\n batch_size=train_batch_size, shuffle=True)\n\n valid_loader = torch.utils.data.DataLoader( dset(data_pars['data_path'], train=False, download=True, transform= transform),\n batch_size=test_batch_size, shuffle=True)\n return train_loader, valid_loader \n except :\n raise Exception(\"Dataset doesn't exist\")\n\"\"\"\n\n\n\"\"\"\ndef get_dataset_mnist_torch(data_pars):\n train_loader = torch.utils.data.DataLoader( datasets.MNIST(data_pars['data_path'], train=True, download=True,\n transform=transforms.Compose([\n transforms.Grayscale(num_output_channels=3),\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])),\n batch_size=data_pars['train_batch_size'], shuffle=True)\n\n\n valid_loader = torch.utils.data.DataLoader( datasets.MNIST(data_pars['data_path'], train=False,\n transform=transforms.Compose([\n transforms.Grayscale(num_output_channels=3),\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])),\n batch_size=data_pars['test_batch_size'], shuffle=True)\n return train_loader, valid_loader \n\"\"\"\n\n\n\n\"\"\"\ndef load_function(uri_name=\"path_norm\"):\n # Can load remote part \n import importlib\n pkg = uri_name.split(\":\")\n package, name = pkg[0], pkg[1]\n return getattr(importlib.import_module(package), name)\n\n\n\ndef get_dataset_torch(data_pars):\n\n transform = None\n if data_pars.get(\"transform_uri\") :\n transform = load_function( data_pars.get(\"transform_uri\", \"mlmodels.preprocess.image:torch_transform_mnist\" ))()\n \n\n dset = load_function(data_pars.get(\"dataset\", \"torchvision.datasets:MNIST\") )\n\n train_loader = torch.utils.data.DataLoader( dset(data_pars['data_path'], train=True, download=True, transform= transform),\n batch_size=data_pars['train_batch_size'], shuffle=True)\n \n valid_loader = torch.utils.data.DataLoader( dset(data_pars['data_path'], train=False, download=True, transform= transform),\n batch_size=data_pars['train_batch_size'], shuffle=True)\n\n return train_loader, valid_loader \n\"\"\"\n\n", "sub_path": "source/models/atorch/torchhub.py", "file_name": "torchhub.py", "file_ext": "py", "file_size_in_byte": 19067, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "mlmodels.util.get_model_uri", "line_number": 35, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 59, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 82, "usage_type": "call"}, {"api_name": "torch.device", "line_number": 93, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 93, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 93, "usage_type": "attribute"}, {"api_name": "mlmodels.util.path_norm", "line_number": 97, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 107, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 108, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 109, "usage_type": "call"}, {"api_name": "torch.hub.load", "line_number": 120, "usage_type": "call"}, {"api_name": "torch.hub", "line_number": 120, "usage_type": "attribute"}, {"api_name": "torch.hub.load", "line_number": 131, "usage_type": "call"}, {"api_name": "torch.hub", "line_number": 131, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 139, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 139, "usage_type": "name"}, {"api_name": "mlmodels.util.path_norm", "line_number": 151, "usage_type": "call"}, {"api_name": "json.load", "line_number": 152, "usage_type": "call"}, {"api_name": "mlmodels.util.path_norm_dict", "line_number": 156, "usage_type": "call"}, {"api_name": "mlmodels.util.path_norm_dict", "line_number": 157, "usage_type": "call"}, {"api_name": "mlmodels.dataloader.DataLoader", "line_number": 190, "usage_type": "call"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 212, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 212, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 221, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 221, "usage_type": "name"}, {"api_name": "os.makedirs", "line_number": 227, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 242, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 242, "usage_type": "call"}, {"api_name": "os.path", "line_number": 242, "usage_type": "attribute"}, {"api_name": "torch.no_grad", "line_number": 259, "usage_type": "call"}, {"api_name": "torchvision.utils.make_grid", "line_number": 265, "usage_type": "call"}, {"api_name": "torchvision.utils", "line_number": 265, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 266, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 266, "usage_type": "name"}, {"api_name": "os.makedirs", "line_number": 269, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 270, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 270, "usage_type": "name"}, {"api_name": "os.system", "line_number": 271, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 290, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 293, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 294, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 306, "usage_type": "call"}, {"api_name": "mlmodels.util.path_norm", "line_number": 307, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 308, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 308, "usage_type": "call"}, {"api_name": "mlmodels.util.save_tch", "line_number": 313, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 321, "usage_type": "call"}, {"api_name": "mlmodels.util.log", "line_number": 322, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 322, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 328, "usage_type": "call"}, {"api_name": "mlmodels.util.path_norm", "line_number": 329, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 332, "usage_type": "call"}, {"api_name": "mlmodels.util.load_tch", "line_number": 338, "usage_type": "call"}, {"api_name": "mlmodels.util.log", "line_number": 350, "usage_type": "call"}, {"api_name": "mlmodels.util.log", "line_number": 353, "usage_type": "call"}, {"api_name": "mlmodels.util.log", "line_number": 355, "usage_type": "call"}, {"api_name": "mlmodels.util.log", "line_number": 359, "usage_type": "call"}, {"api_name": "mlmodels.util.log", "line_number": 365, "usage_type": "call"}, {"api_name": "mlmodels.util.log", "line_number": 369, "usage_type": "call"}, {"api_name": "mlmodels.util.log", "line_number": 374, "usage_type": "call"}, {"api_name": "mlmodels.util.log", "line_number": 377, "usage_type": "call"}, {"api_name": "mlmodels.util.log", "line_number": 382, "usage_type": "call"}, {"api_name": "mlmodels.util.log", "line_number": 392, "usage_type": "call"}, {"api_name": "mlmodels.util.log", "line_number": 395, "usage_type": "call"}, {"api_name": "mlmodels.util.log", "line_number": 397, "usage_type": "call"}, {"api_name": "mlmodels.util.log", "line_number": 401, "usage_type": "call"}, {"api_name": "mlmodels.util.log", "line_number": 407, "usage_type": "call"}, {"api_name": "mlmodels.util.log", "line_number": 411, "usage_type": "call"}, {"api_name": "mlmodels.util.log", "line_number": 416, "usage_type": "call"}, {"api_name": "mlmodels.util.log", "line_number": 419, "usage_type": "call"}]}
+{"seq_id": "285703208", "text": "from mpl_toolkits.basemap import Basemap\nimport seaborn as sns\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom netCDF4 import Dataset \n\n\nplt.figure(figsize=(40,40))\nmap = Basemap(llcrnrlon=95, llcrnrlat=-20, urcrnrlon=165, urcrnrlat=25, ellps='WGS84', resolution='i')\nmap.drawcoastlines(linewidth=0.25)\nmap.drawcountries(linewidth=0.25)\nmap.fillcontinents(color='gray')\nmap.drawmapboundary()\n\nlats = np.load(\"../Data/NPZ/Data_lat.npy\")\nlons = np.load(\"../Data/NPZ/Data_lon.npy\")\nArea = np.load(\"../Data/NPZ/Data_Area.npy\")\nArea_log = np.log(Area)\n\nx,y = map(lons,lats)\nfigure = map.scatter(x, y, s=150, marker='o', alpha=0.5, c=Area_log, edgecolors='none', cmap='jet')\ncaxis = plt.axes([0.83,0.3,0.02,0.4])#manual positioning of the colorbar[x-position, y-position, dx, dy]\ncbar = plt.colorbar(figure, cax=caxis, orientation=\"vertical\") #plot the colorbar\ncbar.ax.tick_params(labelsize=20) #set the size of colorbar labels \nplt.savefig(\"CT_areas.eps\")\nplt.close(\"all\")", "sub_path": "Python/BK/V4/Figs/plot_areas.py", "file_name": "plot_areas.py", "file_ext": "py", "file_size_in_byte": 1001, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "matplotlib.pyplot.figure", "line_number": 9, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 9, "usage_type": "name"}, {"api_name": "mpl_toolkits.basemap.Basemap", "line_number": 10, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 19, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.axes", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 23, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.colorbar", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 24, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 26, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 27, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 27, "usage_type": "name"}]}
+{"seq_id": "566493556", "text": "# https://leetcode-cn.com/problems/sliding-window-maximum/\n# 双端队列 滑动窗口最大值\n# - 只保留当前滑动窗口中有的元素的索引。\n# - 移除比当前元素小的所有元素,它们不可能是最大的。\nimport collections\n\nnums = [1,3,-1,-3,5,3,6,7]\nk = 3\n\n# https://leetcode-cn.com/problems/sliding-window-maximum/solution/python-deque-by-dangerusswilson/\nq, res = collections.deque(), [] \nres.append(max(nums[:k]))\nfor i in range(len(nums)):\n while q and nums[i] > q[-1]: # 移除队列尾部比 nums[i] 小的\n q.pop()\n q.append(nums[i]) # 加入队列\n if i-k >= 0:\n if nums[i-k] == q[0]:\n q.popleft() # 移除上个窗口的\n res.append(q[0]) # 队列头始终是最大的\nprint (res)\n", "sub_path": "others/sliding_window/239_maxSlidingWindow.py", "file_name": "239_maxSlidingWindow.py", "file_ext": "py", "file_size_in_byte": 803, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "collections.deque", "line_number": 11, "usage_type": "call"}]}
+{"seq_id": "554822386", "text": "import os\nimport copy\nimport src.imageclassify as ic\nfrom flask import Flask, jsonify, send_from_directory, render_template, request, session,json\nfrom flask_dropzone import Dropzone\nfrom flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class\nfrom werkzeug import secure_filename, FileStorage\n\n# import flask_uploads\n# import flask_dropzone\n# from flask import CORS, cross_origin\n\nUPLOAD_DIRECTORY = \"kaplptreeimages\"\n\napi = Flask(__name__)\napi.secret_key = (\"DG123\")\ndropzone = Dropzone(api)\n# Dropzone settingsapp.config['DROPZONE_UPLOAD_MULTIPLE'] = True\napi.config['DROPZONE_ALLOWED_FILE_CUSTOM'] = True\napi.config['DROPZONE_ALLOWED_FILE_TYPE'] = 'image/*'\napi.config['DROPZONE_REDIRECT_VIEW'] = 'results'\ndestination = ''\n\n# Uploads settings\napi.config['UPLOADED_PHOTOS_DEST'] = os.getcwd() + '/kaplptreeimages/uploads'\nphotos = UploadSet('photos', IMAGES)\nconfigure_uploads(api, photos)\npatch_request_class(api) # set maximum file size, default is 16MB\nfile_srces = []\nclass_output=[None] * 20\nclass_output_2d=[[None] *2]*10\n# CORS(api)\nSWAGGER_URL = '/api/docs'\nAPI_URL = '/static/swagger.json'\napi_result_str = ''\n\n# Call factory function to create our blueprint\n@api.route('/')\n@api.route('/', methods=['GET', 'POST'])\ndef index():\n # list to hold our uploaded image urls\n # set session for image results\n\n if \"file_srces\" not in session:\n session['file_srces'] = []\n # list to hold our uploaded image urls\n # file_srces = session['file_srces']\n if request.method == 'POST':\n file_obj = request.files\n\n for f in file_obj:\n file = request.files.get(f)\n # save the file with to our photos folder\n target = os.path.join(os.getcwd(), \"kaplptreeimages\")\n target = os.path.join(target, \"uploads\")\n print(target)\n if not os.path.isdir(target):\n os.mkdir(target)\n filename = photos.save(file, name=file.filename)\n #filename = photos.save(file)\n\n print(photos.url(filename))\n #file_srces.append(photos.url(filename))\n destination = os.path.join(target, filename)\n\n print(file.filename)\n print(destination)\n #file.save(destination)\n # Load API keys\n api_keys={}\n print('before json- api_keys' )\n with open('./api_keys.json') as data_file:\n api_keys= json.loads(data_file.read())\n\n print(type(api_keys),'- ',api_keys)\n api_result = ic.call_vision_api(destination, api_keys)\n # api_result = ic.call_vision_api(photos.url(filename), api_keys)\n file_srces.append(api_result)\n os.remove(destination)\n api_result_str = json.dumps(api_result, sort_keys=True, indent=4, separators=(',', ': '))\n print(api_result)\n print(api_result[\"images\"])\n classifiers=api_result[\"images\"]\n for clx in classifiers:\n list_classfier=clx[\"classifiers\"]\n print(len(list_classfier))\n for i in range(len(clx[\"classifiers\"])):\n\n classes=list_classfier[0].get(\"classes\")\n print('XXXXDDGGG')\n\n class_output_2d=copy.copy(classes)\n\n for i in range(len(classes)):\n class_output[i]= classes[i].get('class') +' | '+str(classes[i].get('score')*100)+'%'\n\n #for image_class in jsonData:\n # print (image_class.get(\"class\"))\n\n # session['file_srces'] = file_srces\n # return \"uploading...\"\n # return dropzone template on GET request\n\n return render_template('index.html')\n\n\n@api.route('/results')\ndef results():\n print(\" in results\")\n\n # redirect to home if no images to display\n # if \"file_srces\" not in session or session['file_srces'] == []:\n # return render_template('index.html')\n\n # set the file_urls and remove the session variable\n # file_srces = session['file_srces']\n # session.pop('file_srces', None)\n print(*class_output_2d)\n print(*class_output)\n return render_template('success.html', result=file_srces,class_output=[x for x in class_output if x is not None])\n #return render_template('success.html', result=file_srces, class_output=[x for x in class_output_2d if x[0] is not None])\n\n\n@api.route('/info')\ndef info():\n print(\" in info\")\n\nif __name__ == \"__main__\":\n #api.run(host=\"0.0.0.0\")\n api.run(debug=True, port=5020)\n", "sub_path": "src/FileUploadDownloadGooglesearch.py", "file_name": "FileUploadDownloadGooglesearch.py", "file_ext": "py", "file_size_in_byte": 4570, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "flask.Flask", "line_number": 15, "usage_type": "call"}, {"api_name": "flask_dropzone.Dropzone", "line_number": 17, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 25, "usage_type": "call"}, {"api_name": "flask_uploads.UploadSet", "line_number": 26, "usage_type": "call"}, {"api_name": "flask_uploads.IMAGES", "line_number": 26, "usage_type": "argument"}, {"api_name": "flask_uploads.configure_uploads", "line_number": 27, "usage_type": "call"}, {"api_name": "flask_uploads.patch_request_class", "line_number": 28, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 44, "usage_type": "name"}, {"api_name": "flask.session", "line_number": 45, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 48, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 48, "usage_type": "name"}, {"api_name": "flask.request.files", "line_number": 49, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 49, "usage_type": "name"}, {"api_name": "flask.request.files.get", "line_number": 52, "usage_type": "call"}, {"api_name": "flask.request.files", "line_number": 52, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 52, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 54, "usage_type": "call"}, {"api_name": "os.path", "line_number": 54, "usage_type": "attribute"}, {"api_name": "os.getcwd", "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.path.isdir", "line_number": 57, "usage_type": "call"}, {"api_name": "os.path", "line_number": 57, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 58, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 64, "usage_type": "call"}, {"api_name": "os.path", "line_number": 64, "usage_type": "attribute"}, {"api_name": "flask.json.loads", "line_number": 73, "usage_type": "call"}, {"api_name": "flask.json", "line_number": 73, "usage_type": "name"}, {"api_name": "src.imageclassify.call_vision_api", "line_number": 76, "usage_type": "call"}, {"api_name": "src.imageclassify", "line_number": 76, "usage_type": "name"}, {"api_name": "os.remove", "line_number": 79, "usage_type": "call"}, {"api_name": "flask.json.dumps", "line_number": 80, "usage_type": "call"}, {"api_name": "flask.json", "line_number": 80, "usage_type": "name"}, {"api_name": "copy.copy", "line_number": 92, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 104, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 120, "usage_type": "call"}]}
+{"seq_id": "280650204", "text": "import jieba\nfrom wordcloud import WordCloud, ImageColorGenerator\nfrom scipy.misc import imread\n\n# 读取文本\nlyric = ''\nwith open('page.txt', 'r', encoding='utf-8') as f:\n lyric = f.readlines()\n# 分词\nresult = jieba.lcut(str(lyric))\n# 已空格拼接形成一个字符串\nkeywords = ' '.join(result)\nprint(keywords)\n# 读取图片\nimage = imread('timg.jpg')\n# 实例化词云\nwc = WordCloud(background_color='White', max_words=50, mask=image)\n# 绘制词云\nwc.generate(keywords)\n# 收集原图色彩\nimage_color = ImageColorGenerator(image)\n# 使用原图色彩着色词云\nwc.recolor(color_func=image_color)\n# 保存图像\nwc.to_file('output.png')\n", "sub_path": "wdcloud.py", "file_name": "wdcloud.py", "file_ext": "py", "file_size_in_byte": 658, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "jieba.lcut", "line_number": 10, "usage_type": "call"}, {"api_name": "scipy.misc.imread", "line_number": 15, "usage_type": "call"}, {"api_name": "wordcloud.WordCloud", "line_number": 17, "usage_type": "call"}, {"api_name": "wordcloud.ImageColorGenerator", "line_number": 21, "usage_type": "call"}]}
+{"seq_id": "243076942", "text": "import torch\r\nfrom torch import nn\r\nfrom torch.nn import functional as F\r\n\r\n\r\n# 사용 채널들 리스트 \r\n# 추후 제거 고민중 굳이 파이썬에서도 제거할 필요가 있을까\r\n# list 0 1 2 3 4 5 6 7 8 9 \r\nCHANNELS = [512,512,512,512,512,256,128, 64, 32, 16]\r\nPIXELS = [ 0, 4, 8, 16, 32, 64,128,256,512,1024]\r\nNOISE_PROB = [0,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1, 0.1]\r\nEPSILON = 1e-8\r\nZ_SIZE = 100\r\nMAPPING_UINT = 512\r\n\r\n\r\n\r\n# 생성기 정의\r\nclass Generator(nn.Module) :\r\n def __init__(self, batch_size, block_count = 9) :\r\n super(Generator, self).__init__()\r\n self.mapping = MappingNet()\r\n self.block = nn.ModuleDict()\r\n self.to_RGB = nn.ModuleDict()\r\n\r\n self.base = nn.Parameter(torch.randn(batch_size, CHANNELS[1], PIXELS[1], PIXELS[1]))\r\n\r\n for i in range(1, block_count+1) :\r\n\r\n self.block[str(i)] = GBlock(i)\r\n self.to_RGB[str(i)] = ToRGB(i)\r\n\r\n\r\n def forward(self, z, step, alpha=0):\r\n\r\n x = self.base\r\n w = self.mapping(z)\r\n\r\n # 스텝 수만큼 레이어 반복\r\n for i in range(1, step+1) :\r\n x = self.block[str(i)](x, w, NOISE_PROB[i])\r\n\r\n x = self.to_RGB[str(i)](x)\r\n \r\n # 3채널로 변경\r\n return x \r\n\r\n #######################\r\n # 스무스한 변화를 위한 알파 적용 구현 필요 - 보류\r\n #######################\r\n\r\n #for i in range(1, step) :\r\n # x = self.block[str(i)](x, w, NOISE_PROB[i+1])\r\n #ori = nn.Upsample(scale_factor=2, mode='bilinear')(x)\r\n #new = self.block[str(step)](x, w, NOISE_PROB[i+1])\r\n\r\n #ori = self.to_RGB[str(step)](ori) * alpha\r\n #new = self.to_RGB[str(step)](new) * (1-alpha)\r\n #x = ori + new\r\n\r\n \r\n \r\n \r\n# 생성기 내부 반복블럭 정의, step별 생성가능\r\nclass GBlock(nn.Module) :\r\n def __init__(self, step) :\r\n super(GBlock, self).__init__()\r\n\r\n self.step = step\r\n self.pixel = PIXELS[self.step]\r\n self.prev_channel = CHANNELS[self.step - 1]\r\n self.channel = CHANNELS[self.step]\r\n\r\n self.conv0 = nn.Conv2d(self.prev_channel, self.channel, 3, padding = 1)\r\n self.conv1 = nn.Conv2d(self.channel, self.channel, 3, padding = 1)\r\n\r\n # 현재 스텝에서 사용할 레이어의 크기 미리 저장, 계산 최소화\r\n self.layer_shape = [-1, 2, self.channel, 1, 1]\r\n self.noise_shape = [1, self.channel, self.pixel, self.pixel]\r\n\r\n # StyleMixing을 위해 W 에서 a, b 로 맵핑\r\n layer_size = 2 * self.channel\r\n self.style1 = nn.Linear(MAPPING_UINT, layer_size)\r\n self.style2 = nn.Linear(MAPPING_UINT, layer_size)\r\n\r\n # noise 미리지정 \r\n self.noise1 = nn.Parameter(torch.randn(self.noise_shape))\r\n self.noise2 = nn.Parameter(torch.randn(self.noise_shape))\r\n\r\n # 그냥 업샘플\r\n self.upsample = nn.Upsample(scale_factor=2, mode='bilinear')\r\n\r\n # 리키렐루\r\n self.leaky1 = nn.LeakyReLU(0.2)\r\n self.leaky2 = nn.LeakyReLU(0.2)\r\n \r\n\r\n\r\n def forward(self, x, w, noise_prob) :\r\n\r\n # 업샘플 및 컨볼류션, 첫블록에서는 사용하지않음\r\n if self.step != 1 :\r\n x = self.upsample(x)\r\n x = self.conv0(x)\r\n x = self.leaky1(x)\r\n\r\n ################\r\n # 노이즈 추가 - 추후 방식 변경\r\n ################\r\n noise = self.noise1\r\n x = x + noise * noise_prob\r\n\r\n # 피쳐당 노말라이즈 실행, 배치당이 아님\r\n x = x - torch.mean(x, dim=(2,3), keepdim=True)\r\n p = torch.rsqrt(torch.mean(x**2, dim=(2,3), keepdim=True) + EPSILON) \r\n x = torch.mul(p,x)\r\n\r\n # 생성된 스타일로 ax + b Pixelwise 연산\r\n style = self.style1(w)\r\n style = style.view(self.layer_shape)\r\n x = x * style[:,0] + style[:,1]\r\n\r\n # 위 과정 반복, 모듈화 시킬까 고민중\r\n x = self.conv1(x)\r\n x = self.leaky2(x)\r\n\r\n noise = self.noise2\r\n x = x + noise * noise_prob\r\n\r\n x = x - torch.mean(x, dim=(2,3), keepdim=True)\r\n p = torch.rsqrt(torch.mean(x**2, dim=(2,3), keepdim=True) + EPSILON) \r\n x = torch.mul(p,x)\r\n\r\n style = self.style2(w)\r\n x = x * style[0] + style[1]\r\n\r\n return x\r\n\r\n# 다채널 데이터를 3채널로 변경\r\nclass ToRGB(nn.Module) :\r\n def __init__(self, step) :\r\n super(ToRGB, self).__init__()\r\n self.conv = nn.Conv2d(CHANNELS[step] ,3, 1)\r\n\r\n def forward(self, x):\r\n return self.conv(x)\r\n\r\n# 3채널 데이터를 레이어에 필요한 채널수로 변경\r\nclass FromRGB(nn.Module) :\r\n def __init__(self, step) :\r\n super(FromRGB, self).__init__()\r\n self.conv = nn.Conv2d(3, CHANNELS[step], 1)\r\n\r\n def forward(self, x) :\r\n return self.conv(x)\r\n \r\n# Discriminator 정의\r\nclass Discriminator(nn.Module) :\r\n def __init__(self, block_count = 9) :\r\n super(Discriminator, self).__init__()\r\n self.block = nn.ModuleDict()\r\n self.from_RGB = nn.ModuleDict()\r\n\r\n for i in range(block_count, 0, -1) :\r\n self.from_RGB[str(i)] = FromRGB(i)\r\n self.block[str(i)] = DBlock(i)\r\n\r\n\r\n def forward(self, x, step) :\r\n\r\n #######################\r\n # 스무스한 변화를 위한 알파 적용 구현 필요\r\n #######################\r\n\r\n # 다채널 데이터로 변경, 전체 스텝에서 1회만 필요\r\n x = self.from_RGB[str(step)](x)\r\n\r\n # 블록 반복 실행\r\n for i in range(step, 0, -1) :\r\n x = self.block[str(i)](x)\r\n\r\n return x\r\n\r\n\r\nclass DBlock(nn.Module):\r\n def __init__(self, step):\r\n super(DBlock, self).__init__()\r\n\r\n self.step = step\r\n self.pixel = PIXELS[self.step]\r\n self.channel = CHANNELS[self.step]\r\n self.next_channel = CHANNELS[self.step - 1]\r\n\r\n self.leaky1 = nn.LeakyReLU(0.2)\r\n self.leaky2 = nn.LeakyReLU(0.2)\r\n \r\n\r\n self.stddev = MinibatchStandardDeviation()\r\n\r\n\r\n if self.step != 1 :\r\n self.conv1 = nn.Conv2d(self.channel, self.channel, 3, padding=1)\r\n self.conv2 = nn.Conv2d(self.channel, self.next_channel, 3, padding=1) \r\n self.avgpool = nn.AvgPool2d(2)\r\n\r\n else :\r\n self.conv1 = nn.Conv2d(self.channel+1, self.channel, 3, padding=1)\r\n self.conv2 = nn.Conv2d(self.channel, self.channel, 4, padding=0)\r\n self.fc = nn.Linear(self.next_channel, 1)\r\n\r\n \r\n \r\n def forward(self, x) :\r\n\r\n if self.step == 1 :\r\n # minibatch standard deviation 구현\r\n x = self.stddev(x)\r\n\r\n x = self.conv1(x)\r\n x = self.leaky1(x)\r\n x = self.conv2(x)\r\n x = self.leaky2(x)\r\n\r\n if self.step != 1 :\r\n x = self.avgpool(x)\r\n\r\n else :\r\n\r\n \r\n\r\n x = x.view(x.shape[0], -1)\r\n x = self.fc(x)\r\n\r\n return x\r\n\r\nclass MinibatchStandardDeviation(nn.Module) :\r\n def __init__(self) :\r\n super(MinibatchStandardDeviation, self).__init__()\r\n\r\n def forward(self, x) :\r\n s = x.shape\r\n y = x - x.mean(dim=0, keepdim=True)\r\n y = (y**2).mean(0)\r\n y = torch.sqrt(y + EPSILON)\r\n y = y.mean()\r\n y = y.expand((s[0],1,s[2],s[3]))\r\n x = torch.cat([x, y], 1)\r\n return x\r\n\r\n\r\n# Latent space 맵핑 네트워크 z > w\r\nclass MappingNet(nn.Module) :\r\n def __init__(self) :\r\n super(MappingNet, self).__init__()\r\n\r\n self.dense = nn.ModuleList([nn.Linear(Z_SIZE, MAPPING_UINT)])\r\n\r\n for i in range(7) :\r\n self.dense.append(nn.Linear(MAPPING_UINT, MAPPING_UINT))\r\n\r\n def forward(self, x) :\r\n # 추후 조절을 위해 입력을 따로 받음\r\n # 입력은 (100,1) 의 Unifrom-Dist 벡터\r\n for i in range(8) :\r\n x = self.dense[i](x)\r\n x = nn.ReLU()(x)\r\n\r\n return x\r\n\r\n# 테스트\r\nif __name__ == \"__main__\" :\r\n z = torch.rand(100).cuda()\r\n \r\n g = Generator(9)\r\n g = g.cuda()\r\n d = Discriminator(9)\r\n d = d.cuda()\r\n step = 6\r\n\r\n\r\n y = g(z, step)\r\n print(y.shape)\r\n\r\n z = d(y, step)\r\n print(z.shape)\r\n\r\n\r\n\r\n", "sub_path": "model.py", "file_name": "model.py", "file_ext": "py", "file_size_in_byte": 8376, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "torch.nn.Module", "line_number": 19, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 19, "usage_type": "name"}, {"api_name": "torch.nn.ModuleDict", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 23, "usage_type": "name"}, {"api_name": "torch.nn.ModuleDict", "line_number": 24, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 24, "usage_type": "name"}, {"api_name": "torch.nn.Parameter", "line_number": 26, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 26, "usage_type": "name"}, {"api_name": "torch.randn", "line_number": 26, "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": 74, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 74, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 75, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 75, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "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.Parameter", "line_number": 87, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 87, "usage_type": "name"}, {"api_name": "torch.randn", "line_number": 87, "usage_type": "call"}, {"api_name": "torch.nn.Parameter", "line_number": 88, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 88, "usage_type": "name"}, {"api_name": "torch.randn", "line_number": 88, "usage_type": "call"}, {"api_name": "torch.nn.Upsample", "line_number": 91, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 91, "usage_type": "name"}, {"api_name": "torch.nn.LeakyReLU", "line_number": 94, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 94, "usage_type": "name"}, {"api_name": "torch.nn.LeakyReLU", "line_number": 95, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 95, "usage_type": "name"}, {"api_name": "torch.mean", "line_number": 114, "usage_type": "call"}, {"api_name": "torch.rsqrt", "line_number": 115, "usage_type": "call"}, {"api_name": "torch.mean", "line_number": 115, "usage_type": "call"}, {"api_name": "torch.mul", "line_number": 116, "usage_type": "call"}, {"api_name": "torch.mean", "line_number": 130, "usage_type": "call"}, {"api_name": "torch.rsqrt", "line_number": 131, "usage_type": "call"}, {"api_name": "torch.mean", "line_number": 131, "usage_type": "call"}, {"api_name": "torch.mul", "line_number": 132, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 140, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 140, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 143, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 143, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 149, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 149, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 152, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 152, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 158, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 158, "usage_type": "name"}, {"api_name": "torch.nn.ModuleDict", "line_number": 161, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 161, "usage_type": "name"}, {"api_name": "torch.nn.ModuleDict", "line_number": 162, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 162, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 185, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 185, "usage_type": "name"}, {"api_name": "torch.nn.LeakyReLU", "line_number": 194, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 194, "usage_type": "name"}, {"api_name": "torch.nn.LeakyReLU", "line_number": 195, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 195, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 202, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 202, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 203, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 203, "usage_type": "name"}, {"api_name": "torch.nn.AvgPool2d", "line_number": 204, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 204, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 207, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 207, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 208, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 208, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 209, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 209, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 236, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 236, "usage_type": "name"}, {"api_name": "torch.sqrt", "line_number": 244, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 247, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 252, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 252, "usage_type": "name"}, {"api_name": "torch.nn.ModuleList", "line_number": 256, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 256, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 256, "usage_type": "call"}, {"api_name": "torch.nn.Linear", "line_number": 259, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 259, "usage_type": "name"}, {"api_name": "torch.nn.ReLU", "line_number": 266, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 266, "usage_type": "name"}, {"api_name": "torch.rand", "line_number": 272, "usage_type": "call"}]}
+{"seq_id": "321888724", "text": "from minio import Minio\nimport os\nimport logbook\n\n# from ..utils.log_helper import g_log_helper\n# g_log = g_log_helper.make_logger(logbook.INFO)\n\nSERVER_ADDR = os.environ.get('MINIO_SERVER_ADDR', '192.168.135.15:9000')\nACCESS_KEY = os.environ.get('MINIO_ACCESS_KEY', 'minioadmin')\nSECRET_KEY = os.environ.get('MINIO_SECRET_KEY', 'minioadmin@pcl')\nHTTP_PROTOCOL = os.environ.get('MINIO_HTTP_PROTOCOL', 'http')\n\n\nclass MinioHelper(object):\n def __init__(self, access_key=ACCESS_KEY, secret_key=SECRET_KEY, server_addr=SERVER_ADDR):\n self.server_addr = server_addr\n # g_log.info('server_addr: %s' % SERVER_ADDR)\n self.minio_client = Minio(server_addr,\n access_key=access_key,\n secret_key=secret_key,\n secure=False)\n\n def upload_file(self, object_name, file_path=None, file=None, bucket_name='panos', content_type=''):\n ret_dict = {\n 'code': 0,\n 'file_url': '',\n 'code_msg': '',\n }\n try:\n if file is not None:\n etag = self.minio_client.put_object(bucket_name=bucket_name, object_name=object_name, data=file, length=len(file.getvalue()) )\n \n if file_path is not None:\n etag = self.minio_client.fput_object(bucket_name=bucket_name,\n file_path=file_path,\n object_name=object_name,\n content_type=content_type)\n\n ret_dict['etag'] = etag\n ret_dict['public_url'] = HTTP_PROTOCOL + '://' + self.server_addr + '/' + bucket_name + '/' + object_name\n ret_dict['presigned_url'] = self.minio_client.presigned_get_object(bucket_name=bucket_name,\n object_name=object_name)\n return ret_dict\n except Exception as e:\n ret_dict['code'] = 1\n ret_dict['code_msg'] = str(e)\n return ret_dict\n\n def file_exist(self, object_name, bucket_name='panos'):\n try:\n data = self.minio_client.get_object(bucket_name, object_name)\n return True\n except Exception as err:\n # print(err)\n return False\n\n\ndef get_minio_file(url, folder=\"./download\"):\n import requests\n\n r = requests.get(url)\n fn = os.path.join( folder, url.split(\"?\")[0].split(\"/\")[-1] )\n \n with open( fn, \"wb\") as f:\n f.write(r.content)\n \n return fn\n\n\nif __name__ == '__main__':\n minio_helper = MinioHelper()\n # ret_dict = minio_helper.upload_file(file_path='./09005700121902131735110055A.jpg', object_name='09005700121902131735110055A.jpg')\n ret_dict = minio_helper.upload_file(file_path='./9e7a5c-a72d-1625-bed6-b74eb6_15_01005700001312021447154435T_181.jpg', \n object_name='9e7a5c-a72d-1625-bed6-b74eb6_15_01005700001312021447154435T_181.jpg')\n url = ret_dict['public_url']\n get_minio_file(url, '../download')\n\n fn = '9e7a5c-a72d-1625-bed6-b74eb6_15_01005700001312021447154435T_181.jpg'\n minio_helper.file_exist( fn )\n \n# import zipfile\n\n# zip_file = zipfile.ZipFile(\"./download/LSTMAC_input.zip\")\n# zip_file.extractall()\n\n\n", "sub_path": "src/utils/minio_helper.py", "file_name": "minio_helper.py", "file_ext": "py", "file_size_in_byte": 3373, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "os.environ.get", "line_number": 8, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 8, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 9, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 9, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 10, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 10, "usage_type": "attribute"}, {"api_name": "os.environ.get", "line_number": 11, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 11, "usage_type": "attribute"}, {"api_name": "minio.Minio", "line_number": 18, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 61, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 62, "usage_type": "call"}, {"api_name": "os.path", "line_number": 62, "usage_type": "attribute"}]}
+{"seq_id": "302057378", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport glob\nimport time\nfrom mpl_toolkits.mplot3d import Axes3D\n#from keras.models import load_model\n\npath = \"/hdd1/work1/neural/\"\n#factor = np.array([256.,1024.,256.,1024.,256.,1024.,256.,1024.])\n#ans1 = np.empty((0,8))\n#ans2 = np.empty((0,5))\n#pred = np.empty((0,8))\n#model = load_model(path+\"/keras/exp/indirect_norm-7.h5\")\n#\n#p = glob.glob(path+\"data/result/*.npy\")\n#filename = []\n#for i in range(len(p)):\n# temp = p[i].split(\"/\")[-1].split(\"_\")[0]\n# if (temp == \"run0178\" or\n# temp == \"run0179\" or\n# temp == \"run0180\" or\n# temp == \"run0181\" or\n# temp == \"run0182\" or\n# temp == \"run0183\" or\n# temp == \"run0184\" or\n# temp == \"run0185\" or\n# temp == \"run0186\" or\n# temp == \"run0187\" or\n# temp == \"run0188\" or\n# temp == \"run0189\"):\n# continue\n# print(temp)\n# filename.append(temp)\n#\n#start = time.time()\n#for i in range(len(filename)):\n# cell = np.load(path+\"data/track/\"+filename[i]+\"_track.npy\")\n# ans = np.load(path+\"data/result/\"+filename[i]+\"_result.npy\")\n# ans1 = np.append(ans1,ans[:,5:13],axis=0)\n# ans2 = np.append(ans2,ans[:,:5],axis=0)\n# temp = model.predict([cell[:,0:1],cell[:,1:2]])\n# pred = np.append(pred,temp*factor,axis=0)\n# print(filename[i],len(pred))\n#end = time.time()\n#\n#print((end-start)/60.,\" min.\")\n#np.savetxt(\"ans_1_all.dat\",ans1,header=\"avs avc aes aec cvs csc ces cec [pixel]\")\n#np.savetxt(\"ans_2_all.dat\",ans2,header=\"dx theta phi [degree]\")\n#np.savetxt(\"pred_all.dat\",pred,header=\"avs avc aes aec cvs csc ces cec [pixel]\")\n\nans = np.loadtxt(\"ans_1_all.dat\")\npred = np.loadtxt(\"pred_all.dat\")\n\ndiff = ans-pred\ndiff = diff[np.all(diff<1e8,axis=1),:]\nfactor = np.array([.4,.174,.4,.174,.4,.174,.4,.174])\ndiff = diff*factor\n\ndiff_v_x = diff[:,0]\ndiff_v_y = diff[:,4]\ndiff_v_z = (diff[:,1]+diff[:,5])/2.\ndiff_e_x = diff[:,2]\ndiff_e_y = diff[:,6]\ndiff_e_z = (diff[:,3]+diff[:,7])/2.\n\nnp.savetxt(\"diff_v_all.dat\",np.concatenate((diff_v_x.reshape((-1,1)),diff_v_y.reshape((-1,1)),diff_v_z.reshape((-1,1))),axis=1),header=\"x y z [mm]\")\nnp.savetxt(\"diff_e_all.dat\",np.concatenate((diff_e_x.reshape((-1,1)),diff_e_y.reshape((-1,1)),diff_e_z.reshape((-1,1))),axis=1),header=\"x y z [mm]\")\n\nfig = plt.figure()\nax = Axes3D(fig)\n\nax.set_xlabel(\"x (mm)\")\nax.set_ylabel(\"y (mm)\")\nax.set_zlabel(\"z (mm)\")\n\n#ax.set_xlim(-1,1)\n#ax.set_ylim(-1,1)\n#ax.set_zlim(-1,1)\n\nax.plot(diff_v_x,diff_v_y,diff_v_z,\"ro\",ms=4,mew=0.5)\nax.plot(diff_e_x,diff_e_y,diff_e_z,\"bo\",ms=4,mew=0.5)\n\nv = np.sqrt(diff_v_x*diff_v_x+diff_v_y*diff_v_y+diff_v_z*diff_v_z)\nfig2 = plt.figure()\nax2 = fig2.add_subplot(1,1,1)\nax2.hist(v,bins=100,range=(0,20))\n#ax2.hist(v,bins=100,range=(v.min(),v.max()))\n\ne = np.sqrt(diff_e_x*diff_e_x+diff_e_y*diff_e_y+diff_e_z*diff_e_z)\nfig3 = plt.figure()\nax3 = fig3.add_subplot(1,1,1)\nax3.hist(e,bins=100,range=(0,20))\n#ax3.hist(e,bins=100,range=(e.min(),e.max()))\n\nplt.show()\n", "sub_path": "evaluation/point_detection/diff_plot.py", "file_name": "diff_plot.py", "file_ext": "py", "file_size_in_byte": 2961, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "numpy.loadtxt", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.loadtxt", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.savetxt", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.savetxt", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 67, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 69, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 69, "usage_type": "name"}, {"api_name": "mpl_toolkits.mplot3d.Axes3D", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 83, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 84, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 84, "usage_type": "name"}, {"api_name": "numpy.sqrt", "line_number": 89, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 90, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 90, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 95, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 95, "usage_type": "name"}]}
+{"seq_id": "443740685", "text": "\"\"\"\r\nSam Lambert - sam.gervase.lambert@gmail.com\r\n\r\nThis script looks in a directory for docx files\r\n\r\n\r\n\"\"\"\r\n\r\nimport os\r\nimport docx2txt\r\n\r\nos.chdir('c:/users/Sam Lambert/desktop/projectx')\r\n\r\npath = ('c:/users/Sam Lambert/desktop/projectx')\r\n\r\nfiles = []\r\n\r\nx = str(input(\"search: \"))\r\n\r\nfor file in os.listdir(path):\r\n if file.endswith('.docx'):\r\n files.append(file)\r\n\r\nfor i in range(len(files)):\r\n text = docx2txt.process(files[i])\r\n if x.upper() in text.upper() or x.lower() in text.lower():\r\n print (files[i])\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "sub_path": "word_search.py", "file_name": "word_search.py", "file_ext": "py", "file_size_in_byte": 558, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "os.chdir", "line_number": 12, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 20, "usage_type": "call"}, {"api_name": "docx2txt.process", "line_number": 25, "usage_type": "call"}]}
+{"seq_id": "180156841", "text": "#!/usr/bin/python3\nfrom collections import namedtuple\nimport math\nimport sys\nimport re\nimport subprocess\nimport time\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\ndocorrect = False\n\ndef process( name ):\n #f = open(\"cosy_optics.twiss\")\n f = open( name )\n for line in f:\n if line[0] == \"@\":\n l = line.split()\n if l[1] == \"LENGTH\":\n lenght = float(l[3])\n if l[1] == \"GAMMA\":\n gamma = float(l[3])\n beta = math.sqrt(1-1./(gamma*gamma))\n if l[1] == \"ALFA\":\n alfa = float(l[3])\n if l[1] == \"PC\":\n p = float(l[3])\n if l[1] == \"CHARGE\":\n q = float(l[3])\n elif line[0] == \"*\":\n column_names = line.split()[1:]\n break\n c = 299792458\n rigidity = p * 1e9/(c * q)\n twiss = namedtuple(\"twiss\", column_names)\n twiss_data = []\n for line in f:\n if line[0] != \"$\":\n data = [x.strip('\"').lstrip(\"M\") for x in line.split()]\n if data[0].startswith(\"BLW\"):\n data[0] = data[0][:3] + \"0\" + data[0][3:]\n if data[0][-2] == \"D\":\n dl = list(data[0])\n dl[-3] = \"-\"\n data[0] = \"\".join(dl)\n if data[0].startswith(\"DPOS\"):\n m = re.match(r\"DPOS(\\d\\d)(H|V)\", data[0])\n if m:\n data[0] = (\"bpmx\" if m.group(2) == \"H\" else \"bpmy\") + m.group(1)\n else:\n m = re.match(r\"DPOSEC1(\\d\\d)(V|H)\", data[0])\n if m:\n data[0] = (\"ecbpmx1\" if m.group(2) == \"H\" else \"ecbpmy1\") + m.group(1)\n else:\n m = re.match(r\"DPOSANKE(\\d)(V|H)\", data[0])\n if m:\n data[0] = (\"banx0\" if m.group(2) == \"H\" else \"bany0\") + m.group(1)\n else:\n m = re.match(r\"DPOSEC(\\d)(V|H)\", data[0])\n if m:\n data[0] = (\"becx0\" if m.group(2) == \"H\" else \"becy0\") + m.group(1)\n\n twiss_data.append(twiss(*data))\n hs, hv = [], []\n for d in twiss_data:\n if d.KEYWORD == \"HKICKER\" and (d.NAME.startswith(\"SH\") or d.NAME.startswith(\"BLW\")) :\n hs.append(d)\n for d in twiss_data:\n if d.KEYWORD == \"VKICKER\" and (d.NAME.startswith(\"SV\") or d.NAME.startswith(\"BLW\")):\n hv.append(d)\n if d.NAME == \"COSY$END\":\n mu = (d.MUX, d.MUY)\n bpmh, bpmv = [], []\n for d in twiss_data:\n if d.KEYWORD == \"VMONITOR\":\n bpmv.append(d)\n if d.KEYWORD == \"HMONITOR\":\n bpmh.append(d)\n\n print(\"Len(hs) = \", len(hs))\n print(\"Len(hv) = \", len(hv))\n print(\"Len bpm = \", len(bpmv) + len(bpmh))\n f.close()\n return hs, hv, bpmh, bpmv, mu, beta, lenght, alfa, gamma, rigidity\n\ndef process_cf():\n files = [\"cosmoBLW.txt\", \"cosmoSH.txt\", \"cosmoSV.txt\"]\n fd = [open(f, \"r\") for f in files]\n correction_data = []\n for f in fd:\n for line in f:\n l = line.split(\":\")\n if l[2] == '%/mrad/brho' and not l[0].startswith(\"SHblw\") and not l[0].startswith(\"SVblw\"):\n correction_data.append([l[0], float(l[6]), float(l[7])])\n return correction_data\n\ndef correction_factors(cf, steerer_name):\n names = [n[0] for n in cf]\n i = names.index(steerer_name)\n return cf[i][2]\n\ndef response_matrix_x(steerers, bpms, mu, beta, lenght, alfa, gamma):\n response_matrix = [[0]*len(steerers) for i in range(len(bpms))]\n eta = alfa - 1./(gamma * gamma)\n for ib, b in enumerate(bpms):\n for ic, c in enumerate(steerers):\n response_matrix[ ib ][ ic ] = \\\n math.sqrt(float(b.BETX) * float(c.BETX)) / math.sin(math.pi * float(mu)) *\\\n math.cos(2. * math.pi * abs(float(b.MUX) - float(c.MUX)) - math.pi * float(mu)) * 0.5-\\\n float(b.DX) * beta * float(c.DX) * beta / (eta * lenght)\n return response_matrix\n\ndef response_matrix_y(steerers, bpms, mu):\n response_matrix = [[0]*len(steerers) for i in range(len(bpms))]\n for ib, b in enumerate(bpms):\n for ic, c in enumerate(steerers):\n response_matrix[ ib ][ ic ] = \\\n math.sqrt(float(b.BETY) * float(c.BETY)) / math.sin(math.pi * float(mu)) *\\\n math.cos(2. * math.pi * abs(float(b.MUY) - float(c.MUY)) - math.pi * float(mu)) * 0.5\n return response_matrix\n\ndef matrix_100_units(response_matrix, rigidity, cf, steerers, bpms):\n response_matrix_u = [[0]*len(response_matrix[0]) for i in range(len(response_matrix))]\n for ib, b in enumerate(bpms):\n for ic, c in enumerate(steerers):\n response_matrix_u[ib][ic] = response_matrix[ib][ic] / (correction_factors(cf, c.NAME) * rigidity)\n return response_matrix_u\n\n\ndef index_from_name(data, name):\n names = [d.NAME for d in data]\n return names.index(name)\n\ndef create_matrix_fabian_format(matrix, matriy, hs, vs, bpmh, bpmv):\n bfile = open(\"BPMS.txt\", \"r\")\n sfile = open(\"STEERERS.data\", \"r\")\n outfile = open(\"normal_matrix.data\", \"w\")\n\n lenx = len(matrix[0]) + len(matriy[0])\n leny = len(matrix) + len(matriy)\n\n\n bpm_names, steerer_names = [], []\n for line in bfile:\n bpm_names.append(line.split()[0])\n for line in sfile:\n if line[0] != \"#\":\n steerer_names.append(line.split(\":\")[0])\n\n out_matrix = [[0] * len(steerer_names) for i in range(len(bpm_names))]\n\n for indb, bpmn in enumerate(bpm_names[:32]):\n for inds, sn in enumerate(steerer_names[:22]):\n idb = index_from_name(bpmh, bpmn)\n ids = index_from_name(hs, sn)\n out_matrix[indb][inds] = matrix[idb][ids]\n #print(lenx, leny)\n #print(len(bpm_names), len(steerer_names))\n for indb, bpmn in enumerate(bpm_names[32:]):\n for inds, sn in enumerate(steerer_names[22:]):\n idb = index_from_name(bpmv, bpmn)\n ids = index_from_name(vs, sn)\n out_matrix[32 + indb][22 + inds] = matriy[idb][ids]\n for row in out_matrix:\n for c in row:\n outfile.write(str(c) + \" \")\n outfile.write(\"\\n\")\n bfile.close()\n sfile.close()\n outfile.close()\n return out_matrix\n\n\ndef makeresponse( twiss, cnames, bnames, positions, plane, printRM=False ):\n endTwiss = twiss[ 'ende' ]\n muTotx = endTwiss.mux\n muToty = endTwiss.muy\n print( \"mu_x, mu_y:\", muTotx, muToty )\n selected = dict(zip(bnames, positions))\n # print selected\n\n # [len(bnames), len(cnames)] x [len(cnames), 1] = [len(bnames), 1]\n ResponseMatrix = np.zeros((len(bnames), len(cnames)))\n OrbitVector = np.zeros((len(bnames)))\n for ib, b in enumerate(bnames):\n if plane == 'v':\n for ic, c in enumerate(cnames):\n ResponseMatrix[ ib, ic ] = \\\n math.sqrt(twiss[ b ].betay * twiss[ c ].betay) / math.sin(math.pi * muToty) *\\\n math.cos(2. * math.pi * abs(twiss[ b ].muy - twiss[ c ].muy) - math.pi * muToty) * 0.5\n else:\n for ic, c in enumerate(cnames):\n ResponseMatrix[ ib, ic ] = \\\n math.sqrt(twiss[ b ].betax * twiss[ c ].betax) / math.sin(math.pi * muTotx) *\\\n math.cos(2. * math.pi * abs(twiss[ b ].mux - twiss[ c ].mux) - math.pi * muTotx) * 0.5\n if abs(ResponseMatrix[ ib, ic ]) > 2e3:\n print( \"FAIL: ResponseMatrix[\", ib, \",\", ic, \"] =\", ResponseMatrix[ ib, ic ] )\n if b in selected:\n OrbitVector[ ib ] = selected[ b ]\n\n if printRM:\n print( 'ResponseMatrix size =', ResponseMatrix.shape )\n print( ResponseMatrix )\n print( 'OrbitVector size =', OrbitVector.shape )\n print( OrbitVector )\n return ResponseMatrix, OrbitVector\n\ndef threeBump( twiss, name1, name2, name3 ):\n index1 = index_from_name( twiss, name1 )\n index2 = index_from_name( twiss, name2 )\n index3 = index_from_name( twiss, name3 )\n\n bhc = float( twiss[ index2 ].BETY )\n fihc = float( twiss[ index2 ].MUY ) * 2. * math.pi\n\n # Check the phase relations between correctors\n bhcl = float( twiss[ index1 ].BETY )\n fihcl = float( twiss[ index1 ].MUY ) * 2. * math.pi\n # if(i0 > i1) fihcl -= mu_tot // if the bump overlap the ring initial point\n\n bhcr = float( twiss[ index3 ].BETY )\n fihcr = float( twiss[ index3 ].MUY ) * 2. * math.pi\n # if(i1 > i2) fihcr += mu_tot // if the bump overlap the ring initial point\n\n correctorResponse = [0,0,0]\n correctorResponse[0] = (1.0 / math.sqrt(bhcl * bhc)) * (1.0 / math.sin(fihc - fihcl))\n correctorResponse[1] = (1.0 / bhc) * (math.sin(fihcl - fihcr) / (math.sin(fihcr - fihc) * math.sin(fihc - fihcl)))\n correctorResponse[2] = (1.0 / math.sqrt(bhcr * bhc)) * (1.0 / math.sin(fihcr - fihc))\n strengths = [0.] * len(twiss)\n strengths[ index1 ] = correctorResponse[0]\n strengths[ index2 ] = correctorResponse[1]\n strengths[ index3 ] = correctorResponse[2]\n print( name1, name2, name3, correctorResponse[0], correctorResponse[1], correctorResponse[2] )\n return correctorResponse, strengths\n\ndef makeb( args ):\n twname = args[0]\n hs, vs, bpmh, bpmv, mu, beta, lenght, alfa, gamma, rigidity = process(twname)\n cf = process_cf()\n rmy = response_matrix_y(vs, bpmv, mu[1])\n u,svalues,vh = np.linalg.svd( rmy )\n plt.plot(svalues, marker=2)\n plt.show()\n if True:\n rmyu = matrix_100_units(rmy, rigidity, cf, vs, bpmv)\n u,svalues,vh = np.linalg.svd( rmyu )\n plt.plot(svalues, marker=2)\n plt.show()\n if True:\n rmx = response_matrix_x(hs, bpmh, mu[0], beta, lenght, alfa, gamma)\n if True:\n u,svalues,vh = np.linalg.svd( rmx )\n plt.plot(svalues, marker=2)\n plt.show()\n rmxu = matrix_100_units(rmx, rigidity, cf, hs, bpmh)\n rmf = create_matrix_fabian_format(rmxu, rmyu, hs, vs, bpmh, bpmv)\n u,svalues,vh = np.linalg.svd( rmf )\n plt.plot(svalues, marker=2)\n plt.show()\n for s in vs:\n c = \"caput \" + s.NAME + \" 0\"\n print(c)\n if docorrect:\n subprocess.call(c, shell=True)\n scord = [x.S for x in bpmv]\n #time.sleep(5)\n junk= input('--> start ')\n for i in range(len(vs) - 2):\n name = [x.NAME for x in vs[i : i + 3]]\n print( [x.NAME for x in vs[i : i + 3]] )\n if any(['BLW' in x for x in name]): continue\n \n #name = [\"\"] * 3;\n t = [\"\"] * 3\n '''\n name[0] = 'SV10'; t[0] = 'SV08/10/12/14:SDI2'\n name[1] = 'SV12'; t[1] = 'SV08/10/12/14:SDI3'\n name[2] = 'SV14'; t[2] = 'SV08/10/12/14:SDI4'\n '''\n t[0] = 'SV08/10/12/14:SDI2'\n t[1] = 'SV08/10/12/14:SDI3'\n t[2] = 'SV08/10/12/14:SDI4'\n\n s, sv = threeBump( vs, name[0], name[1], name[2] )\n calcResponse( rmy, sv, scord )\n a = 2.\n p = [0.] * 3; c = [\"\"] * 3\n for i in range(3):\n p[i] = a * s[i] / (correction_factors(cf, name[i]) * rigidity) * 2048\n c[i] = \"caput \" + name[i] + \" \" + str(p[i])\n print(c[i])\n if docorrect:\n subprocess.call(c[i], shell=True)\n #junk = input('--> 5 ')\n #time.sleep(5)\n calcResponse( rmy, [-x for x in sv], scord )\n for i in range(3):\n p[i] = -a * s[i] / (correction_factors(cf, name[i]) * rigidity) * 2048\n c[i] = \"caput \" + name[i] + \" \" + str(p[i])\n print(c[i])\n if docorrect:\n subprocess.call(c[i], shell=True)\n #junk = input('--> -5 ')\n #time.sleep(5)\n calcResponse( rmy, [0. for x in sv], scord )\n for i in range(3):\n c[i] = \"caput \" + name[i] + \" 0\"\n print(c[i])\n if docorrect:\n subprocess.call(c[i], shell=True)\n #junk = input('--> 0 ')\n #time.sleep(5)\n\ndef calcResponse( rm, strengths, scord ):\n # print( len(strengths), len(rm), len(rm[0]) )\n pos = [0.] * len(rm)\n for i in range( len(rm) ):\n for j in range( len(rm[0]) ):\n pos[i] += strengths[j] * rm[i][j]\n plt.plot(scord, pos)\n plt.show()\n'''\ndef name_to_target():\n file_crateh s = open(\"crate_steererv.data\", \"r\")\n for line in s:\n l = line.split(line)\n print(l[0], l[4:])\n'''\n\ndef makematrix():\n hs, vs, bpmh, bpmv, mu, beta, lenght, alfa, gamma, rigidity = process()\n cd = process_cf()\n rmx = response_matrix_x(hs, bpmh, mu[0], beta, lenght, alfa, gamma)\n rmy = response_matrix_y(vs, bpmv, mu[1])\n rmxu = matrix_100_units(rmx, rigidity, cd, hs, bpmh)\n rmyu = matrix_100_units(rmy, rigidity, cd, vs, bpmv)\n create_matrix_fabian_format(rmxu, rmyu, hs, vs, bpmh, bpmv)\n\n\nif __name__ == \"__main__\":\n #name_to_target()\n sys.exit( makeb( sys.argv[1:] ) )\n\n'''\n \"MSV10\" \"VKICKER\" 49.771 0 0 14.96869392 6.648205105 14.01694053 0 1.20580545 1.153532505\n \"DPOS11H\" \"HMONITOR\" 59.99 0 0 7.02140788 21.04016513 11.00821148 0 1.328283583 1.371387996\n \"DPOS11V\" \"VMONITOR\" 60.15 0 0 6.648254238 21.85627509 10.83037948 0 1.33201105 1.372575491\n \"MSV12\" \"VKICKER\" 61.1534 0 0 5.592221629 23.52779521 10.55459841 0 1.3589585 1.379452598\n \"DPOS12H\" \"HMONITOR\" 66.318 0 0 12.80546554 11.28969619 14.95153491 0 1.481987687 1.421787535\n \"DPOS12V\" \"VMONITOR\" 66.483 0 0 13.40127951 10.59549147 15.26582399 0 1.483992365 1.424188683\n \"MSV14\" \"VKICKER\" 67.1092 0 0 14.41949265 9.077319218 15.70792023 0 1.491011324 1.434577182\n'''\n", "sub_path": "EPICS_IOCs/orbitCorrectionIOC/Scripts/makebumps.py", "file_name": "makebumps.py", "file_ext": "py", "file_size_in_byte": 14531, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "math.sqrt", "line_number": 23, "usage_type": "call"}, {"api_name": "collections.namedtuple", "line_number": 35, "usage_type": "call"}, {"api_name": "re.match", "line_number": 47, "usage_type": "call"}, {"api_name": "re.match", "line_number": 51, "usage_type": "call"}, {"api_name": "re.match", "line_number": 55, "usage_type": "call"}, {"api_name": "re.match", "line_number": 59, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 108, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 108, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 108, "usage_type": "attribute"}, {"api_name": "math.cos", "line_number": 109, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 109, "usage_type": "attribute"}, {"api_name": "math.sqrt", "line_number": 118, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 118, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 118, "usage_type": "attribute"}, {"api_name": "math.cos", "line_number": 119, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 119, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 183, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 184, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 189, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 189, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 189, "usage_type": "attribute"}, {"api_name": "math.cos", "line_number": 190, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 190, "usage_type": "attribute"}, {"api_name": "math.sqrt", "line_number": 194, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 194, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 194, "usage_type": "attribute"}, {"api_name": "math.cos", "line_number": 195, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 195, "usage_type": "attribute"}, {"api_name": "math.pi", "line_number": 214, "usage_type": "attribute"}, {"api_name": "math.pi", "line_number": 218, "usage_type": "attribute"}, {"api_name": "math.pi", "line_number": 222, "usage_type": "attribute"}, {"api_name": "math.sqrt", "line_number": 226, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 226, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 227, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 228, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 228, "usage_type": "call"}, {"api_name": "numpy.linalg.svd", "line_number": 241, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 241, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.plot", "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": "numpy.linalg.svd", "line_number": 246, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 246, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.plot", "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"}, {"api_name": "numpy.linalg.svd", "line_number": 252, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 252, "usage_type": "attribute"}, {"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.show", "line_number": 254, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 254, "usage_type": "name"}, {"api_name": "numpy.linalg.svd", "line_number": 257, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 257, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 258, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 258, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 259, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 259, "usage_type": "name"}, {"api_name": "subprocess.call", "line_number": 264, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 293, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 302, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 310, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 320, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 320, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 321, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 321, "usage_type": "name"}, {"api_name": "sys.exit", "line_number": 342, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 342, "usage_type": "attribute"}]}
+{"seq_id": "640799924", "text": "import pytest\n\nimport bloop.tables\nimport bloop.util\n\nfrom test_models import SimpleModel, ComplexModel, User\n\n\nstatuses = [\n (\"ACTIVE\", \"ACTIVE\", \"ACTIVE\"),\n (\"ACTIVE\", None, \"ACTIVE\"),\n (\"ACTIVE\", \"BUSY\", \"BLOOP_NOT_ACTIVE\"),\n (\"BUSY\", \"ACTIVE\", \"BLOOP_NOT_ACTIVE\"),\n (\"BUSY\", \"BUSY\", \"BLOOP_NOT_ACTIVE\")\n]\n\n\ndef assert_unordered(obj, other):\n assert bloop.util.ordered(obj) == bloop.util.ordered(other)\n\n\ndef test_create_simple():\n expected = {\n 'AttributeDefinitions': [\n {'AttributeName': 'id', 'AttributeType': 'S'}],\n 'KeySchema': [{'AttributeName': 'id', 'KeyType': 'HASH'}],\n 'ProvisionedThroughput': {\n 'ReadCapacityUnits': 1,\n 'WriteCapacityUnits': 1},\n 'TableName': 'Simple'}\n assert_unordered(bloop.tables.create_request(SimpleModel), expected)\n\n\ndef test_create_complex():\n expected = {\n 'AttributeDefinitions': [\n {'AttributeType': 'S', 'AttributeName': 'date'},\n {'AttributeType': 'S', 'AttributeName': 'email'},\n {'AttributeType': 'S', 'AttributeName': 'joined'},\n {'AttributeType': 'S', 'AttributeName': 'name'}],\n 'GlobalSecondaryIndexes': [{\n 'IndexName': 'by_email',\n 'KeySchema': [{'KeyType': 'HASH', 'AttributeName': 'email'}],\n 'Projection': {'ProjectionType': 'ALL'},\n 'ProvisionedThroughput': {\n 'ReadCapacityUnits': 4, 'WriteCapacityUnits': 5}}],\n 'KeySchema': [{'KeyType': 'HASH', 'AttributeName': 'name'},\n {'KeyType': 'RANGE', 'AttributeName': 'date'}],\n 'LocalSecondaryIndexes': [{\n 'IndexName': 'by_joined',\n 'KeySchema': [\n {'KeyType': 'HASH', 'AttributeName': 'name'},\n {'KeyType': 'RANGE', 'AttributeName': 'joined'}],\n 'Projection': {\n 'NonKeyAttributes': ['joined', 'email', 'date', 'name'],\n 'ProjectionType': 'INCLUDE'}}],\n 'ProvisionedThroughput': {\n 'ReadCapacityUnits': 3, 'WriteCapacityUnits': 2},\n 'TableName': 'CustomTableName'}\n assert_unordered(bloop.tables.create_request(ComplexModel), expected)\n\n\ndef test_expected_description():\n # Eventually expected_description will probably diverge from create_table\n # This will guard against (or coverage should show) if there's drift\n create = bloop.tables.create_request(ComplexModel)\n expected = bloop.tables.expected_description(ComplexModel)\n assert_unordered(create, expected)\n\n\ndef test_sanitize_drop_empty_lists():\n expected = bloop.tables.expected_description(ComplexModel)\n # Start from the same base, but inject an unnecessary NonKeyAttributes\n description = bloop.tables.expected_description(ComplexModel)\n index = description[\"GlobalSecondaryIndexes\"][0]\n index[\"Projection\"][\"NonKeyAttributes\"] = []\n\n assert_unordered(expected, bloop.tables.sanitized_description(description))\n\n\ndef test_sanitize_drop_empty_indexes():\n expected = bloop.tables.expected_description(SimpleModel)\n # Start from the same base, but inject an unnecessary NonKeyAttributes\n description = bloop.tables.expected_description(SimpleModel)\n description[\"GlobalSecondaryIndexes\"] = []\n\n assert_unordered(expected, bloop.tables.sanitized_description(description))\n\n\ndef test_sanitize_expected():\n expected = bloop.tables.expected_description(User)\n # Add some extra fields\n description = {\n 'AttributeDefinitions': [\n {'AttributeType': 'S', 'AttributeName': 'email'},\n {'AttributeType': 'S', 'AttributeName': 'id'}],\n 'CreationDateTime': 'EXTRA_FIELD',\n 'ItemCount': 'EXTRA_FIELD',\n 'KeySchema': [{'AttributeName': 'id', 'KeyType': 'HASH'}],\n 'GlobalSecondaryIndexes': [{\n 'IndexArn': 'EXTRA_FIELD',\n 'IndexName': 'by_email',\n 'IndexSizeBytes': 'EXTRA_FIELD',\n 'IndexStatus': 'EXTRA_FIELD',\n 'KeySchema': [{'AttributeName': 'email', 'KeyType': 'HASH'}],\n 'Projection': {'ProjectionType': 'ALL'},\n 'ProvisionedThroughput': {\n 'NumberOfDecreasesToday': 'EXTRA_FIELD',\n 'ReadCapacityUnits': 1,\n 'WriteCapacityUnits': 1}}],\n 'ProvisionedThroughput': {\n 'LastDecreaseDateTime': 'EXTRA_FIELD',\n 'LastIncreaseDateTime': 'EXTRA_FIELD',\n 'NumberOfDecreasesToday': 'EXTRA_FIELD',\n 'ReadCapacityUnits': 1,\n 'WriteCapacityUnits': 1},\n 'TableArn': 'EXTRA_FIELD',\n 'TableName': 'User',\n 'TableSizeBytes': 'EXTRA_FIELD',\n 'TableStatus': 'EXTRA_FIELD'}\n sanitized = bloop.tables.sanitized_description(description)\n assert_unordered(expected, sanitized)\n\n\n@pytest.mark.parametrize(\"table_status, gsi_status, expected_status\", statuses)\ndef test_simple_status(table_status, gsi_status, expected_status):\n \"\"\"Status is busy because table isn't ACTIVE, no GSIs\"\"\"\n description = {\"TableStatus\": table_status}\n if gsi_status is not None:\n description[\"GlobalSecondaryIndexes\"] = [{\"IndexStatus\": gsi_status}]\n assert bloop.tables.simple_status(description) == expected_status\n", "sub_path": "tests/test_tables.py", "file_name": "test_tables.py", "file_ext": "py", "file_size_in_byte": 5242, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "bloop.tables.util.ordered", "line_number": 19, "usage_type": "call"}, {"api_name": "bloop.tables.util", "line_number": 19, "usage_type": "attribute"}, {"api_name": "bloop.tables", "line_number": 19, "usage_type": "name"}, {"api_name": "bloop.tables.tables.create_request", "line_number": 31, "usage_type": "call"}, {"api_name": "test_models.SimpleModel", "line_number": 31, "usage_type": "argument"}, {"api_name": "bloop.tables.tables", "line_number": 31, "usage_type": "attribute"}, {"api_name": "bloop.tables", "line_number": 31, "usage_type": "name"}, {"api_name": "bloop.tables.tables.create_request", "line_number": 60, "usage_type": "call"}, {"api_name": "test_models.ComplexModel", "line_number": 60, "usage_type": "argument"}, {"api_name": "bloop.tables.tables", "line_number": 60, "usage_type": "attribute"}, {"api_name": "bloop.tables", "line_number": 60, "usage_type": "name"}, {"api_name": "bloop.tables.tables.create_request", "line_number": 66, "usage_type": "call"}, {"api_name": "test_models.ComplexModel", "line_number": 66, "usage_type": "argument"}, {"api_name": "bloop.tables.tables", "line_number": 66, "usage_type": "attribute"}, {"api_name": "bloop.tables", "line_number": 66, "usage_type": "name"}, {"api_name": "bloop.tables.tables.expected_description", "line_number": 67, "usage_type": "call"}, {"api_name": "test_models.ComplexModel", "line_number": 67, "usage_type": "argument"}, {"api_name": "bloop.tables.tables", "line_number": 67, "usage_type": "attribute"}, {"api_name": "bloop.tables", "line_number": 67, "usage_type": "name"}, {"api_name": "bloop.tables.tables.expected_description", "line_number": 72, "usage_type": "call"}, {"api_name": "test_models.ComplexModel", "line_number": 72, "usage_type": "argument"}, {"api_name": "bloop.tables.tables", "line_number": 72, "usage_type": "attribute"}, {"api_name": "bloop.tables", "line_number": 72, "usage_type": "name"}, {"api_name": "bloop.tables.tables.expected_description", "line_number": 74, "usage_type": "call"}, {"api_name": "test_models.ComplexModel", "line_number": 74, "usage_type": "argument"}, {"api_name": "bloop.tables.tables", "line_number": 74, "usage_type": "attribute"}, {"api_name": "bloop.tables", "line_number": 74, "usage_type": "name"}, {"api_name": "bloop.tables.tables.sanitized_description", "line_number": 78, "usage_type": "call"}, {"api_name": "bloop.tables.tables", "line_number": 78, "usage_type": "attribute"}, {"api_name": "bloop.tables", "line_number": 78, "usage_type": "name"}, {"api_name": "bloop.tables.tables.expected_description", "line_number": 82, "usage_type": "call"}, {"api_name": "test_models.SimpleModel", "line_number": 82, "usage_type": "argument"}, {"api_name": "bloop.tables.tables", "line_number": 82, "usage_type": "attribute"}, {"api_name": "bloop.tables", "line_number": 82, "usage_type": "name"}, {"api_name": "bloop.tables.tables.expected_description", "line_number": 84, "usage_type": "call"}, {"api_name": "test_models.SimpleModel", "line_number": 84, "usage_type": "argument"}, {"api_name": "bloop.tables.tables", "line_number": 84, "usage_type": "attribute"}, {"api_name": "bloop.tables", "line_number": 84, "usage_type": "name"}, {"api_name": "bloop.tables.tables.sanitized_description", "line_number": 87, "usage_type": "call"}, {"api_name": "bloop.tables.tables", "line_number": 87, "usage_type": "attribute"}, {"api_name": "bloop.tables", "line_number": 87, "usage_type": "name"}, {"api_name": "bloop.tables.tables.expected_description", "line_number": 91, "usage_type": "call"}, {"api_name": "test_models.User", "line_number": 91, "usage_type": "argument"}, {"api_name": "bloop.tables.tables", "line_number": 91, "usage_type": "attribute"}, {"api_name": "bloop.tables", "line_number": 91, "usage_type": "name"}, {"api_name": "bloop.tables.tables.sanitized_description", "line_number": 121, "usage_type": "call"}, {"api_name": "bloop.tables.tables", "line_number": 121, "usage_type": "attribute"}, {"api_name": "bloop.tables", "line_number": 121, "usage_type": "name"}, {"api_name": "bloop.tables.tables.simple_status", "line_number": 131, "usage_type": "call"}, {"api_name": "bloop.tables.tables", "line_number": 131, "usage_type": "attribute"}, {"api_name": "bloop.tables", "line_number": 131, "usage_type": "name"}, {"api_name": "pytest.mark.parametrize", "line_number": 125, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 125, "usage_type": "attribute"}]}
+{"seq_id": "560697620", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('voterguide', '0008_auto_20160907_1439'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='district',\n name='chamber',\n field=models.IntegerField(verbose_name='Chamber', choices=[(1, 'State Senate'), (2, 'State House'), (3, 'County'), (8, 'Mayor'), (4, 'City Council'), (5, 'US Senate'), (6, 'US House'), (7, \"Governor's Council\")]),\n ),\n migrations.AlterField(\n model_name='office',\n name='chamber',\n field=models.IntegerField(blank=True, help_text='Optional', null=True, verbose_name='Chamber', choices=[(1, 'State Senate'), (2, 'State House'), (3, 'County'), (8, 'Mayor'), (4, 'City Council'), (5, 'US Senate'), (6, 'US House'), (7, \"Governor's Council\")]),\n ),\n ]\n", "sub_path": "voterguide/migrations/0009_auto_20170709_1938.py", "file_name": "0009_auto_20170709_1938.py", "file_ext": "py", "file_size_in_byte": 957, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "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.AlterField", "line_number": 14, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 14, "usage_type": "name"}, {"api_name": "django.db.models.IntegerField", "line_number": 17, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 17, "usage_type": "name"}, {"api_name": "django.db.migrations.AlterField", "line_number": 19, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 19, "usage_type": "name"}, {"api_name": "django.db.models.IntegerField", "line_number": 22, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 22, "usage_type": "name"}]}
+{"seq_id": "453763003", "text": "# SPDX-License-Identifier: BSD-3-Clause\n# Copyright (c) 2021 Scipp contributors (https://github.com/scipp)\n# @file\n# @author Neil Vaytet\n\nimport numpy as np\nimport scipp as sc\nfrom ..factory import make_dense_data_array, make_binned_data_array\nfrom .plot_helper import plot\nimport matplotlib\nmatplotlib.use('Agg')\n\n\ndef _with_fake_pos(*args, **kwargs):\n da = make_dense_data_array(*args, **kwargs)\n da.coords['pos'] = sc.geometry.position(da.coords['xx'], da.coords['yy'],\n da.coords['zz']).transpose(da.dims[:3])\n return da\n\n\ndef make_data_array_with_position_vectors():\n N = 1000\n M = 100\n theta = np.random.random(N) * np.pi\n phi = np.random.random(N) * 2.0 * np.pi\n r = 10.0 + (np.random.random(N) - 0.5)\n x = r * np.sin(theta) * np.sin(phi)\n y = r * np.sin(theta) * np.cos(phi)\n z = r * np.cos(theta)\n time = np.arange(M, dtype=np.float64)\n a = np.arange(M * N).reshape([M, N]) * np.sin(y)\n da = sc.DataArray(data=sc.Variable(dims=['time', 'xyz'], values=a),\n coords={\n 'xyz':\n sc.vectors(dims=['xyz'], values=np.array([x, y, z]).T),\n 'pos':\n sc.vectors(dims=['xyz'], values=np.array([x, y, z]).T + 20.0),\n 'time':\n sc.Variable(dims=['time'], values=time)\n })\n return da\n\n\ndef test_plot_projection_3d():\n da = _with_fake_pos(ndim=3)\n plot(da, positions='pos', projection=\"3d\")\n plot(da, positions='pos', projection=\"3d\", resampling_mode='sum')\n plot(da, positions='pos', projection=\"3d\", resampling_mode='mean')\n\n\ndef test_plot_projection_3d_log_norm():\n plot(_with_fake_pos(ndim=3), positions='pos', projection=\"3d\", norm='log')\n\n\ndef test_plot_projection_3d_dataset():\n plot(_with_fake_pos(ndim=3), positions='pos', projection=\"3d\")\n\n\ndef test_plot_projection_3d_with_labels():\n plot(_with_fake_pos(ndim=3, labels=True),\n positions='pos',\n projection=\"3d\",\n labels={'x': \"lab\"})\n\n\ndef test_plot_projection_3d_with_masks():\n plot(_with_fake_pos(ndim=3, masks=True), positions='pos', projection=\"3d\")\n\n\ndef test_plot_projection_3d_with_vectors():\n plot(make_data_array_with_position_vectors(), projection=\"3d\", positions=\"xyz\")\n\n\ndef test_plot_projection_3d_with_vectors_non_dim_coord():\n plot(make_data_array_with_position_vectors(), projection=\"3d\", positions=\"pos\")\n\n\ndef test_plot_variable_3d():\n N = 50\n v3d = sc.Variable(dims=['time', 'y', 'x'],\n values=np.random.rand(N, N, N),\n unit=sc.units.m)\n positions = sc.vectors(dims=v3d.dims, values=np.random.rand(N, N, N, 3))\n plot(v3d, positions=positions, projection=\"3d\")\n\n\ndef test_plot_4d_with_masks_projection_3d():\n da = sc.DataArray(data=sc.Variable(dims=['pack', 'tube', 'straw', 'pixel'],\n values=np.random.rand(2, 8, 7, 256)),\n coords={})\n a = np.sin(np.linspace(0, 3.14, num=256))\n da += sc.Variable(dims=['pixel'], values=a)\n da.masks['tube_ends'] = sc.Variable(dims=['pixel'],\n values=np.where(a > 0.5, True, False))\n da.coords['pos'] = sc.geometry.position(sc.arange(dim='pack', start=0., stop=2),\n sc.arange(dim='tube', start=0., stop=8),\n sc.arange(dim='straw', start=0., stop=7))\n plot(da, positions='pos', projection=\"3d\")\n\n\ndef test_plot_customized_axes():\n da = _with_fake_pos(ndim=3)\n plot(da,\n positions='pos',\n projection=\"3d\",\n xlabel=\"MyXlabel\",\n ylabel=\"MyYlabel\",\n zlabel=\"MyZlabel\")\n\n\ndef test_plot_3d_with_2d_position_coordinate():\n nx = 50\n ny = 40\n nt = 10\n\n xx, yy = np.meshgrid(np.arange(nx, dtype=np.float64), np.arange(ny,\n dtype=np.float64))\n da = sc.DataArray(\n data=sc.Variable(dims=['x', 'y', 't'],\n values=np.arange(nx * ny * nt).reshape(nx, ny, nt)),\n coords={\n 'pos':\n sc.vectors(dims=['x', 'y'],\n values=np.array([xx, yy,\n np.zeros_like(xx)]).T.reshape(nx, ny, 3)),\n 't':\n sc.arange('t', nt + 1, dtype=np.float64)\n })\n\n plot(da, projection=\"3d\", positions=\"pos\")\n\n\ndef test_plot_3d_binned_data():\n da = make_binned_data_array(ndim=1)\n pos = sc.vectors(dims=da.dims, values=np.random.rand(da.sizes[da.dims[0]], 3))\n plot(da, projection='3d', positions=pos)\n plot(da, projection='3d', positions=pos, resampling_mode='sum')\n plot(da, projection='3d', positions=pos, resampling_mode='mean')\n\n\ndef test_plot_redraw():\n da = _with_fake_pos(ndim=3, unit='K')\n p = sc.plot(da, positions='pos', projection=\"3d\")\n before = p.view.figure.points_geometry.attributes[\"rgba_color\"].array\n da *= 5.0\n p.redraw()\n after = p.view.figure.points_geometry.attributes[\"rgba_color\"].array\n assert np.any(before != after)\n", "sub_path": "tests/plotting/plot_3d_test.py", "file_name": "plot_3d_test.py", "file_ext": "py", "file_size_in_byte": 5206, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "matplotlib.use", "line_number": 11, "usage_type": "call"}, {"api_name": "factory.make_dense_data_array", "line_number": 15, "usage_type": "call"}, {"api_name": "scipp.geometry.position", "line_number": 16, "usage_type": "call"}, {"api_name": "scipp.geometry", "line_number": 16, "usage_type": "attribute"}, {"api_name": "numpy.random.random", "line_number": 24, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 24, "usage_type": "attribute"}, {"api_name": "numpy.pi", "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.pi", "line_number": 25, "usage_type": "attribute"}, {"api_name": "numpy.random.random", "line_number": 26, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 26, "usage_type": "attribute"}, {"api_name": "numpy.sin", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 30, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 31, "usage_type": "call"}, {"api_name": "scipp.DataArray", "line_number": 32, "usage_type": "call"}, {"api_name": "scipp.Variable", "line_number": 32, "usage_type": "call"}, {"api_name": "scipp.vectors", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 35, "usage_type": "call"}, {"api_name": "scipp.vectors", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 37, "usage_type": "call"}, {"api_name": "scipp.Variable", "line_number": 39, "usage_type": "call"}, {"api_name": "plot_helper.plot", "line_number": 46, "usage_type": "call"}, {"api_name": "plot_helper.plot", "line_number": 47, "usage_type": "call"}, {"api_name": "plot_helper.plot", "line_number": 48, "usage_type": "call"}, {"api_name": "plot_helper.plot", "line_number": 52, "usage_type": "call"}, {"api_name": "plot_helper.plot", "line_number": 56, "usage_type": "call"}, {"api_name": "plot_helper.plot", "line_number": 60, "usage_type": "call"}, {"api_name": "plot_helper.plot", "line_number": 67, "usage_type": "call"}, {"api_name": "plot_helper.plot", "line_number": 71, "usage_type": "call"}, {"api_name": "plot_helper.plot", "line_number": 75, "usage_type": "call"}, {"api_name": "scipp.Variable", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 81, "usage_type": "attribute"}, {"api_name": "scipp.units", "line_number": 82, "usage_type": "attribute"}, {"api_name": "scipp.vectors", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 83, "usage_type": "attribute"}, {"api_name": "plot_helper.plot", "line_number": 84, "usage_type": "call"}, {"api_name": "scipp.DataArray", "line_number": 88, "usage_type": "call"}, {"api_name": "scipp.Variable", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 89, "usage_type": "attribute"}, {"api_name": "numpy.sin", "line_number": 91, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 91, "usage_type": "call"}, {"api_name": "scipp.Variable", "line_number": 92, "usage_type": "call"}, {"api_name": "scipp.Variable", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 94, "usage_type": "call"}, {"api_name": "scipp.geometry.position", "line_number": 95, "usage_type": "call"}, {"api_name": "scipp.geometry", "line_number": 95, "usage_type": "attribute"}, {"api_name": "scipp.arange", "line_number": 95, "usage_type": "call"}, {"api_name": "scipp.arange", "line_number": 96, "usage_type": "call"}, {"api_name": "scipp.arange", "line_number": 97, "usage_type": "call"}, {"api_name": "plot_helper.plot", "line_number": 98, "usage_type": "call"}, {"api_name": "plot_helper.plot", "line_number": 103, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 116, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 116, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 116, "usage_type": "attribute"}, {"api_name": "numpy.float64", "line_number": 117, "usage_type": "attribute"}, {"api_name": "scipp.DataArray", "line_number": 118, "usage_type": "call"}, {"api_name": "scipp.Variable", "line_number": 119, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 120, "usage_type": "call"}, {"api_name": "scipp.vectors", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 124, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 125, "usage_type": "call"}, {"api_name": "scipp.arange", "line_number": 127, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 127, "usage_type": "attribute"}, {"api_name": "plot_helper.plot", "line_number": 130, "usage_type": "call"}, {"api_name": "factory.make_binned_data_array", "line_number": 134, "usage_type": "call"}, {"api_name": "scipp.vectors", "line_number": 135, "usage_type": "call"}, {"api_name": "numpy.random.rand", "line_number": 135, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 135, "usage_type": "attribute"}, {"api_name": "plot_helper.plot", "line_number": 136, "usage_type": "call"}, {"api_name": "plot_helper.plot", "line_number": 137, "usage_type": "call"}, {"api_name": "plot_helper.plot", "line_number": 138, "usage_type": "call"}, {"api_name": "scipp.plot", "line_number": 143, "usage_type": "call"}, {"api_name": "numpy.any", "line_number": 148, "usage_type": "call"}]}
+{"seq_id": "592201682", "text": "# -*- coding:utf-8 -*-\n# @Author: Phoebe\n# @File: test_touchactions.py\nfrom selenium import webdriver\nfrom selenium.webdriver import TouchActions\n\n\nclass TestTouchActions:\n def setup(self):\n option = webdriver.ChromeOptions()\n option.add_experimental_option('w3', False)\n self.driver = webdriver.Chrome(options=option)\n self.driver.implicitly_wait(3)\n self.driver.maximize_window()\n\n def teardown(self):\n self.driver.quit()\n\n def test_touchactions_scrollbottom(self):\n self.driver.get('https://www.baidu.com/')\n el = self.driver.find_element_by_id('kw')\n el_search = self.driver.find_element_by_id('su')\n el.send_keys('selenium测试')\n action = TouchActions(self.driver)\n action.tap(el_search)\n action.perform()\n\n action.scroll_from_element(el, 0, 1000).perform()\n", "sub_path": "selenium_event/test_touchactions.py", "file_name": "test_touchactions.py", "file_ext": "py", "file_size_in_byte": 874, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "selenium.webdriver.ChromeOptions", "line_number": 10, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 10, "usage_type": "name"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 12, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 12, "usage_type": "name"}, {"api_name": "selenium.webdriver.TouchActions", "line_number": 24, "usage_type": "call"}]}
+{"seq_id": "591446899", "text": "\r\nfrom typing import List\r\n\r\n# Definition for a Node.\r\nclass Node:\r\n def __init__(self, val=None, children=None):\r\n self.val = val\r\n self.children = children\r\n\r\nclass Solution:\r\n def postorder(self, root: 'Node') -> List[int]:\r\n a = []\r\n if not root:\r\n return a\r\n b = [root]\r\n while len(b) != 0:\r\n c = b.pop()\r\n if c.children:\r\n b += c.children\r\n if c:\r\n a.append(c.val)\r\n return a[::-1]\r\n\r\nn1 = Node(1)\r\nn2 = Node(2)\r\nn3 = Node(3)\r\nn4 = Node(4)\r\nn5 = Node(5)\r\nn6 = Node(6)\r\n\r\nn1.children = [n3, n2, n4]\r\nn3.children = [n5, n6]\r\n\r\ns = Solution()\r\nprint(s.postorder(n1))\r\n", "sub_path": "leetcode/t000590_2.py", "file_name": "t000590_2.py", "file_ext": "py", "file_size_in_byte": 700, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "typing.List", "line_number": 11, "usage_type": "name"}]}
+{"seq_id": "255609090", "text": "import math\nimport tensorflow as tf\nfrom termcolor import colored as c, cprint\nimport numpy as np\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n\nfrom . import helpers\n\n### helper functions\nfrom functools import reduce\n\n\ndef fc_layer(x, weight_shape, bias_shape, layer_name):\n with tf.name_scope(layer_name):\n # initializing at 0 is no-good.\n norm = math.sqrt(float(\n reduce(lambda v, e: v * e, weight_shape)\n ))\n weight = tf.Variable(\n tf.truncated_normal(weight_shape,\n mean=0.5,\n stddev=1.0 / norm),\n name='weight')\n bias = tf.Variable(tf.zeros(bias_shape), name='bias')\n activation = tf.matmul(x, weight) + bias\n return weight, bias, activation\n\n\n# main network build stages\ndef inference():\n x = tf.placeholder(tf.float32, shape=[None, 784], name='input')\n image = tf.reshape(x, [-1, 28, 28, 1])\n\n with tf.name_scope('conv_layer_1'):\n W_conv1 = helpers.weight_variable([5, 5, 1, 32], 'W_conv1')\n b_conv1 = helpers.bias_variable([32], 'bias_conv1')\n # alphas_conv1 = helpers.bias_variable([32], 'alpha_conv1')\n layer_conv_1 = tf.nn.softplus(helpers.conv2d(image, W_conv1) + b_conv1)\n stage_1_pool = helpers.max_pool_2x2(layer_conv_1)\n\n with tf.name_scope('conv_layer_2'):\n W_conv2 = helpers.weight_variable([5, 5, 32, 64], \"W_conv2\")\n b_conv2 = helpers.bias_variable([64], 'bias_conv2')\n # alphas_conv3 = helpers.bias_variable([64], 'alpha_conv3')\n layer_conv_2 = tf.nn.softplus(helpers.conv2d(stage_1_pool, W_conv2) + b_conv2)\n stage_2_pool = helpers.max_pool_2x2(layer_conv_2)\n stage_2_pool_flat = tf.reshape(stage_2_pool, [-1, 7 * 7 * 64])\n\n with tf.name_scope('conv_layer_3'):\n W_conv3 = helpers.weight_variable([5, 5, 64, 128], \"W_conv3\")\n b_conv3 = helpers.bias_variable([128], 'bias_conv3')\n # alphas_conv3 = helpers.bias_variable([64], 'alpha_conv3')\n layer_conv_3 = tf.nn.softplus(helpers.conv2d(stage_2_pool, W_conv3) + b_conv3)\n stage_3_pool = helpers.max_pool_2x2(layer_conv_3)\n\n stage_3_pool_flat = tf.reshape(stage_3_pool, [-1, 4 * 4 * 128])\n\n with tf.name_scope('fc_layer_1'):\n W_fc1 = helpers.weight_variable([4 * 4 * 128, 2], \"W_fc1\")\n b_fc1 = helpers.bias_variable([2], 'bias_fc1')\n output = tf.nn.softplus(tf.matmul(stage_3_pool_flat, W_fc1) + b_fc1)\n\n # with tf.name_scope('fc_output'):\n # W_output = helpers.weight_variable([500, 10], \"W_putput\")\n # b_output = helpers.bias_variable([10], 'bias_output')\n # output = tf.nn.softplus(tf.matmul(h_fc1, W_output) + b_output)\n\n # with tf.name_scope('output'):\n # W_output = helpers.weight_variable([2, 10], \"W_output\")\n # b_output = helpers.bias_variable([10])\n # output = tf.nn.softplus(tf.matmul(h_fc2, W_output) + b_output)\n\n return x, output\n\n\ndef loss(deep_features):\n with tf.name_scope('softmax_loss'):\n batch_labels = tf.placeholder(tf.float32, name='labels')\n W_loss = helpers.weight_variable([2, 10], \"W_loss\")\n bias_loss = tf.Variable(\n tf.truncated_normal(shape=[10], stddev=1e-2, mean=1e-1), 'bias_loss')\n # Note: we don't use the bias here because it does not affect things. removing the\n # bias also makes the analysis simpler.\n logits = tf.matmul(deep_features, W_loss) + bias_loss\n cross_entropy = - tf.reduce_mean(\n tf.mul(batch_labels, tf.nn.log_softmax(logits)),\n reduction_indices=[1]\n )\n xentropy_mean = tf.reduce_mean(cross_entropy, name=\"xentropy_mean\")\n tf.scalar_summary(xentropy_mean.op.name, xentropy_mean)\n\n return batch_labels, logits, xentropy_mean\n\n\ndef training(loss, learning_rate):\n with tf.name_scope('training'):\n global_step = tf.Variable(0, name='global_step', trainable=False)\n # optimizer = tf.train.GradientDescentOptimizer(learning_rate)\n optimizer = tf.train.AdamOptimizer(learning_rate)\n train_op = optimizer.minimize(loss, global_step=global_step)\n # optimizer = tf.train.GradientDescentOptimizer(learning_rate)\n # grads_and_vars = optimizer.compute_gradients(loss, tf.trainable_variables())\n # capped_grads_and_vars = [(tf.clip_by_value(grads, 1e-10, 1e10), vars) for grads, vars in grads_and_vars]\n # train_op = optimizer.apply_gradients(capped_grads_and_vars)\n return train_op, global_step\n\n\ndef evaluation(logits, labels):\n correct = tf.nn.in_top_k(logits, tf.cast(tf.argmax(labels, dimension=1), dtype=tf.int32), 1)\n accuracy = tf.reduce_mean(tf.cast(correct, tf.float64), name='accuracy')\n tf.scalar_summary(accuracy.op.name, accuracy)\n # Return the number of true entries.\n return accuracy\n", "sub_path": "Proj_Centroid_Loss_LeNet/convnet_2_hidden/network.py", "file_name": "network.py", "file_ext": "py", "file_size_in_byte": 4936, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "tensorflow.examples.tutorials.mnist.input_data.read_data_sets", "line_number": 7, "usage_type": "call"}, {"api_name": "tensorflow.examples.tutorials.mnist.input_data", "line_number": 7, "usage_type": "name"}, {"api_name": "tensorflow.name_scope", "line_number": 16, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 18, "usage_type": "call"}, {"api_name": "functools.reduce", "line_number": 19, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 21, "usage_type": "call"}, {"api_name": "tensorflow.truncated_normal", "line_number": 22, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 26, "usage_type": "call"}, {"api_name": "tensorflow.zeros", "line_number": 26, "usage_type": "call"}, {"api_name": "tensorflow.matmul", "line_number": 27, "usage_type": "call"}, {"api_name": "tensorflow.placeholder", "line_number": 33, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 33, "usage_type": "attribute"}, {"api_name": "tensorflow.reshape", "line_number": 34, "usage_type": "call"}, {"api_name": "tensorflow.name_scope", "line_number": 36, "usage_type": "call"}, {"api_name": "tensorflow.nn.softplus", "line_number": 40, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 40, "usage_type": "attribute"}, {"api_name": "tensorflow.name_scope", "line_number": 43, "usage_type": "call"}, {"api_name": "tensorflow.nn.softplus", "line_number": 47, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 47, "usage_type": "attribute"}, {"api_name": "tensorflow.reshape", "line_number": 49, "usage_type": "call"}, {"api_name": "tensorflow.name_scope", "line_number": 51, "usage_type": "call"}, {"api_name": "tensorflow.nn.softplus", "line_number": 55, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 55, "usage_type": "attribute"}, {"api_name": "tensorflow.reshape", "line_number": 58, "usage_type": "call"}, {"api_name": "tensorflow.name_scope", "line_number": 60, "usage_type": "call"}, {"api_name": "tensorflow.nn.softplus", "line_number": 63, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 63, "usage_type": "attribute"}, {"api_name": "tensorflow.matmul", "line_number": 63, "usage_type": "call"}, {"api_name": "tensorflow.name_scope", "line_number": 79, "usage_type": "call"}, {"api_name": "tensorflow.placeholder", "line_number": 80, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 80, "usage_type": "attribute"}, {"api_name": "tensorflow.Variable", "line_number": 82, "usage_type": "call"}, {"api_name": "tensorflow.truncated_normal", "line_number": 83, "usage_type": "call"}, {"api_name": "tensorflow.matmul", "line_number": 86, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 87, "usage_type": "call"}, {"api_name": "tensorflow.mul", "line_number": 88, "usage_type": "call"}, {"api_name": "tensorflow.nn.log_softmax", "line_number": 88, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 88, "usage_type": "attribute"}, {"api_name": "tensorflow.reduce_mean", "line_number": 91, "usage_type": "call"}, {"api_name": "tensorflow.scalar_summary", "line_number": 92, "usage_type": "call"}, {"api_name": "tensorflow.name_scope", "line_number": 98, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 99, "usage_type": "call"}, {"api_name": "tensorflow.train.AdamOptimizer", "line_number": 101, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 101, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.in_top_k", "line_number": 111, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 111, "usage_type": "attribute"}, {"api_name": "tensorflow.cast", "line_number": 111, "usage_type": "call"}, {"api_name": "tensorflow.argmax", "line_number": 111, "usage_type": "call"}, {"api_name": "tensorflow.int32", "line_number": 111, "usage_type": "attribute"}, {"api_name": "tensorflow.reduce_mean", "line_number": 112, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 112, "usage_type": "call"}, {"api_name": "tensorflow.float64", "line_number": 112, "usage_type": "attribute"}, {"api_name": "tensorflow.scalar_summary", "line_number": 113, "usage_type": "call"}]}
+{"seq_id": "514650363", "text": "\"\"\"\r\nDeveloper: Jc\r\nGoal: To Create a Simple Game Engine /Game FrameWork To help me make simple 2d games using pygame \r\n\r\nTodo: \r\n\t\t- Colors \t\t\t\t********DONE********\r\n\r\n\t\t- State class \t\t\t********DONE********\r\n\r\n\t\t- Entity Class \t\t\t********DONE********\r\n\r\n\t\t- Button Class \t\t\t********DONE********\r\n\r\n\t \t- DisplayText \t\t\t********DONE********\r\n\r\n\t\t- Text box \t\t\t\t\r\n\r\n\t\t- Animation \r\n\r\n\t\t- Collision Detection \tAABB Detection\r\n\r\n\t\t- Game Class \r\n\r\n\t\t- Create a Simple Website in Royalcraft.co/Jc (That Documents Your Simple Game Engine) (learn a little HTML/ Javascript)\r\n\r\n\r\n\"\"\"\r\n\r\nimport pygame\r\nimport random \r\nfrom enum import Enum \r\nfrom time import sleep\r\n\r\n#Initializing pygame \r\npygame.init()\r\n\r\n\r\n#pygame Colors \r\nBLACK = (0,0,0)\r\nWHITE = (255,255,255)\r\nLIGHTGRAY = (200,200,200)\r\nGRAY = (150,150,150)\r\nDARKGRAY = (75,75,75)\r\nRED = (200,0,0)\r\nGREEN = (0,200,0)\r\nBLUE = (0,0,200)\r\nPURPLE = (100,0,100)\r\nLIGHTBLUE = (0,200,255)\r\nPINK = (230,0,230)\r\n\r\n\r\n\r\n#Base Class For All States \r\nclass State:\r\n\r\n\tdef __init__(self):\r\n\t\tself.isActive = False #initially False \r\n\r\n\tdef update(self,mouseState):\r\n\t\tpass\r\n\r\n\tdef draw(self, screen):\r\n\t\tpass\r\n\r\n\r\n#Entity Class (all Entities inherit from this class)\r\nclass Entity(pygame.Surface):\r\n\r\n\tdef __init__(self,pos, size = (100,100), fillColor = PINK):\r\n\t\tsuper().__init__(size) #Initializing the size of the entity \r\n\t\tself.pos = pos #Saving the Position of the entity \r\n\t\tself.fill(fillColor)\r\n\t\tself.size = size #Saving the Size of the Entity\r\n\r\n\t#Update Place Holder \r\n\tdef update(self,mouseState):\r\n\t\tpass\t\t\r\n\r\n\t#Draws the Entity to the Screen \r\n\tdef draw(self,screen):\r\n\t\tscreen.blit(self,self.pos)\r\n\r\n\r\n#Allows the User to Easily display text on the screen \r\nclass DisplayText:\r\n\tdef __init__(self, message, pos, textColor = BLACK, sizeOfText = 30, fontFile = \"BebasNeue-Regular.ttf\"):\r\n\t\tself.font = pygame.font.Font(fontFile,sizeOfText)\r\n\t\t#Saving the textColor\r\n\t\tself.textColor = textColor\r\n\t\t#Creating a text surface object on which text is drawn on to \r\n\t\tself.text = self.font.render(message, True,textColor)\r\n\t\t#Saving the position of the text\r\n\t\tself.pos = pos \r\n\t\t#Saving the message \r\n\t\tself.message = message\r\n\r\n\t#Changes the Message of the DisplayText Object \r\n\tdef update(self, newMessage):\r\n\t\t#Ensures it only changes the message when it has to \r\n\t\tif self.message != newMessage:\r\n\t\t\tself.text = self.font.render(newMessage, True, self.textColor)\r\n\t\t\tself.message = newMessage\r\n\r\n\t#Draws the DisplayText Object To the Screen \r\n\tdef draw(self,screen):\r\n\t\tscreen.blit(self.text, self.pos)\r\n\r\n#Compacts all the colors of the button into a simple data structure \r\nclass ButtonColor:\r\n\tdef __init__(self, idleColor = WHITE, hoverColor = GRAY, pressedColor = DARKGRAY):\r\n\t\tself.idleColor = idleColor\r\n\t\tself.hoverColor = hoverColor\r\n\t\tself.pressedColor = pressedColor\r\n\r\n#Keeps Track of the Button State \r\nclass ButtonState(Enum):\r\n\tIDLE = 1\r\n\tHOVER = 2\r\n\tPRESSED = 3\r\n#Button Class \r\nclass Button(Entity):\r\n\r\n\tdef __init__(self, message, pos, size = (200,50), buttonColor = ButtonColor()):\r\n\t\tsuper().__init__(pos,size)\r\n\r\n\t\tself.message = message\r\n\t\tself.buttonColor = buttonColor \r\n\t\tself.buttonState = ButtonState.IDLE #Initially The Button is Idle \r\n\r\n\t\t#message, pos, textColor = BLACK, sizeOfText = 30, fontFile = \"BebasNeue-Regular.ttf\"\r\n\t\ttextPos = (pos[0] + 50, pos[1] )\r\n\t\tself.text = DisplayText(self.message,textPos, BLACK, 50)\r\n\r\n\t\tself.isPressed = False #Initially the Button is Not Pressed \r\n\r\n\tdef update(self, mouseState):\r\n\r\n\t\tself.buttonState = ButtonState.IDLE #If Nothing Happening then its IDLE \r\n\r\n\t\t#Getting the Position of the Mouse \r\n\t\tmousePos = pygame.mouse.get_pos()\r\n\r\n\t\t#Checking if the Mouse is Hovering over the Button \r\n\t\tif mousePos[0] >= self.pos[0] and mousePos[0] <= (self.pos[0] + self.get_width()):\r\n\t\t\tif mousePos[1] > self.pos[1] and mousePos[1] <= (self.pos[1] + self.get_height()):\r\n\t\t\t\t#Mouse is Currently Hovering over the Button \r\n\t\t\t\tself.buttonState = ButtonState.HOVER\r\n\r\n\t\t\t\t#Check if the button is being pressed \r\n\t\t\t\tif mouseState[0]:\r\n\t\t\t\t\tself.buttonState = ButtonState.PRESSED #Switching the Button State \r\n\t\t\t\t\tself.isPressed = True # \r\n\r\n\tdef draw(self, screen, outline = True):\r\n\r\n\t\t#Changing the Button Color Based off its State \r\n\t\tif self.buttonState == ButtonState.IDLE:\r\n\t\t\tfillColor = self.buttonColor.idleColor\r\n\t\tif self.buttonState == ButtonState.HOVER:\r\n\t\t\tfillColor = self.buttonColor.hoverColor\r\n\t\tif self.buttonState == ButtonState.PRESSED:\r\n\t\t\tfillColor = self.buttonColor.pressedColor\r\n\r\n\t\tself.fill(fillColor) #Changing the Color Based off the Button State \r\n\t\t\r\n\t\t#Draws the Button Outline \r\n\t\tif outline == True:\r\n\t\t\tpygame.draw.rect(screen, (0,0,0), (self.pos[0] - 2, self.pos[1] -2, self.get_width() + 4, self.get_height() + 4), 0)\r\n\t\t\tpass\r\n\t\t#Drawing the Button (Using the Entity draw Function)\r\n\t\tsuper().draw(screen)\r\n\t\t#Drawing the Text Of the button \r\n\t\tself.text.draw(screen)\r\n\r\n\r\ndef main():\r\n\r\n\tscreen = pygame.display.set_mode((800,800)) #Main Screen \r\n\tscreen.fill(RED)\r\n\r\n\ttestEntity = Entity((200,20), (10,300))\r\n\r\n\r\n\t#self, message, pos, textColor = BLACK, sizeOfText = 30, fontFile = \"BebasNeue-Regular.ttf\"\r\n\ttext = DisplayText(\"TEST\" , (400,400), LIGHTBLUE, 100)\r\n\r\n\r\n\t#Testing the Button Class \r\n\t#self, message, pos, size = (100,50), buttonColor = ButtonColor()\r\n\ttestButton = Button(\"Play\", (400,400))\r\n\r\n\r\n\t#Temp Variable Used to Count the DisplayText\r\n\tx = 0\r\n\r\n\r\n\t#Game Loop\r\n\tisOver = False \r\n\twhile(not isOver):\r\n\r\n\t\t#Event Loop Handler \r\n\t\tfor event in pygame.event.get():\r\n\t\t\tif event.type == pygame.QUIT:\r\n\t\t\t\tisOver = True #Stop The game loop \r\n\r\n\t\tmouseState = pygame.mouse.get_pressed()\r\n\r\n\t\tkeys = pygame.key.get_pressed() #Getting a list of booleans of all the keys in the game \r\n\r\n\t\tscreen.fill(RED)\r\n\r\n\r\n\t\t#Testing the Button \r\n\t\ttestButton.update(mouseState)\r\n\t\ttestButton.draw(screen)\r\n\r\n\r\n\t\tpygame.display.update() #Updating the display module \r\n\r\n\tpygame.quit() #Quitting pygame \r\n\r\nif __name__ == \"__main__\":\r\n\tmain()", "sub_path": "gameEngine/engine_1.py", "file_name": "engine_1.py", "file_ext": "py", "file_size_in_byte": 5999, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "pygame.init", "line_number": 35, "usage_type": "call"}, {"api_name": "pygame.Surface", "line_number": 67, "usage_type": "attribute"}, {"api_name": "pygame.font.Font", "line_number": 87, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 87, "usage_type": "attribute"}, {"api_name": "enum.Enum", "line_number": 116, "usage_type": "name"}, {"api_name": "pygame.mouse.get_pos", "line_number": 141, "usage_type": "call"}, {"api_name": "pygame.mouse", "line_number": 141, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 168, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 168, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 178, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 178, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 202, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 202, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 203, "usage_type": "attribute"}, {"api_name": "pygame.mouse.get_pressed", "line_number": 206, "usage_type": "call"}, {"api_name": "pygame.mouse", "line_number": 206, "usage_type": "attribute"}, {"api_name": "pygame.key.get_pressed", "line_number": 208, "usage_type": "call"}, {"api_name": "pygame.key", "line_number": 208, "usage_type": "attribute"}, {"api_name": "pygame.display.update", "line_number": 218, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 218, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 220, "usage_type": "call"}]}
+{"seq_id": "464243898", "text": "\" Import of modules \"\r\nimport numpy.random as np\r\nimport xlsxwriter\r\n\r\n\" Initialization \"\r\nprob = [0] * 5 #Range of mutational probabilities\r\na = len ( prob )\r\nfor i in range ( 0, a ):\r\n prob [i] = 10 ** -(i+4)\r\n\r\ngrowth_rate = [0] * 20 #Range of growth rates\r\nb = len ( growth_rate )\r\nfor i in range ( 0, b ):\r\n growth_rate [i] = 0.25 * (i+1)\r\n\r\nmut_pop = [ [0 for i in range ( 0, b )] for j in range ( 0, a ) ] #Threshold values for mutant population sizes\r\nproduct = [ [0 for i in range ( 0, b )] for j in range ( 0, a ) ] #Product of p and mut_pop will be stored here\r\nmutant_prev = [ [0 for i in range ( 0, b )] for j in range ( 0, a ) ] #Size of mutant population at the step preceding transition\r\n\r\niter_num = 100 #Number of iterations for the entire simuation\r\nn = 8 * 10 ** 9 #Stem cell carrying capacity for the tissue\r\n\r\n\" Main simulation \"\r\n\r\nfor i in range ( 0,a ):\r\n p = prob [i]\r\n \r\n for j in range ( 0, b ):\r\n g = growth_rate [j]\r\n time = 100 #Duration of each simulation\r\n \r\n for x in range ( 0, iter_num ):\r\n t = 0 #Index to track time\r\n n_mut = [0] * time\r\n m = 0 #Initial mutant population\r\n g_total = 0 #Total number of mutant cells with a particular set of mutations\r\n m_prev = 0 #Number of cells in the previous step\r\n m_hold = 0 #Holding variable for previous population size\r\n avg = 0 #Average mutant population size per mutation\r\n p_mut = 1 - ( (1-p) ** n ) #Initial probabiltiy of first mutation arising in the population\r\n\r\n if p_mut > np.random_sample ( ): #At t = 0\r\n n_mut [0] += 1\r\n m = 1\r\n else:\r\n m = 0\r\n\r\n for t in range ( 1, time ): #From t = 1 to end of time\r\n n_mut [t] = n_mut [t-1]\r\n m_hold = m\r\n m += ( ( m*g ) * ( 1 - ( m/n ) ) )\r\n p_mut = 1 - ( (1-p) ** m )\r\n\r\n if p_mut > np.random_sample ( ):\r\n n_mut [t] += 1\r\n m_prev += m_hold\r\n g_total += m\r\n m = 1\r\n \r\n den = n_mut [time-1] - 1 #Number of mutations - 1 = number of transitions between subsequent mutant populations\r\n avg = g_total / den #Average mutant population size per iteration\r\n m_prev = m_prev / den\r\n mut_pop [i][j] += avg / iter_num #Average mutant population size over all iterations\r\n mutant_prev [i][j] += m_prev / iter_num\r\n\r\n\" Calculation of the product, p * mut_pop \"\r\nfor i in range ( 0, a ):\r\n for j in range ( 0, b ):\r\n product [i][j] = prob [i] * mutant_prev [i][j]\r\n\r\n\"\"\" Export to Excel \"\"\"\r\nworkbook = xlsxwriter.Workbook ( 'Model.xlsx' )\r\nworksheet = workbook.add_worksheet ( )\r\nrow = 0\r\ncol = 0\r\n\r\nfor i in range ( 0, a ):\r\n for j in range ( 0, b ):\r\n worksheet.write ( row, col, mut_pop [i][j] )\r\n worksheet.write ( row + 7, col, mutant_prev [i][j] )\r\n col += 1\r\n row += 1\r\n col = 0\r\n\r\nworkbook.close ( )\r\n \r\n\r\n \r\n \r\n \r\n \r\n", "sub_path": "MGW/codes/old-codes/cancer_incidence_model05_v2 (2017_06_10 00_46_26 UTC).py", "file_name": "cancer_incidence_model05_v2 (2017_06_10 00_46_26 UTC).py", "file_ext": "py", "file_size_in_byte": 3154, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "numpy.random.random_sample", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 42, "usage_type": "name"}, {"api_name": "numpy.random.random_sample", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 54, "usage_type": "name"}, {"api_name": "xlsxwriter.Workbook", "line_number": 72, "usage_type": "call"}]}
+{"seq_id": "86249924", "text": "import streamlit as st\n\ndef main():\n uploaded_files = st.file_uploader(\"Choose a CSV file\", accept_multiple_files=True)\n for uploaded_file in uploaded_files:\n bytes_data = uploaded_file.read()\n st.write(\"filename:\", uploaded_file.name)\n st.write(bytes_data)\n\nif __name__ == \"__main__\":\n #application.run()\n main()\n", "sub_path": "app/upload.py", "file_name": "upload.py", "file_ext": "py", "file_size_in_byte": 347, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "streamlit.file_uploader", "line_number": 4, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 7, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 8, "usage_type": "call"}]}
+{"seq_id": "403726527", "text": "import numpy as np\nfrom typing import List\nfrom classifier import Classifier\n\nclass DecisionTree(Classifier):\n\tdef __init__(self):\n\t\tself.clf_name = \"DecisionTree\"\n\t\tself.root_node = None\n\n\tdef train(self, features: List[List[float]], labels: List[int]):\n\t\t# init.\n\t\tassert(len(features) > 0)\n\t\tself.feautre_dim = len(features[0])\n\t\tnum_cls = np.max(labels)+1\n\n\t\t# build the tree\n\t\tself.root_node = TreeNode(features, labels, num_cls)\n\t\tif self.root_node.splittable:\n\t\t\tself.root_node.split()\n\n\t\treturn\n\t\t\n\tdef predict(self, features: List[List[float]]) -> List[int]:\n\t\ty_pred = []\n\t\tfor feature in features:\n\t\t\ty_pred.append(self.root_node.predict(feature))\n\t\treturn y_pred\n\n\tdef print_tree(self, node=None, name='node 0', indent=''):\n\t\tif node is None:\n\t\t\tnode = self.root_node\n\t\tprint(name + '{')\n\t\t\n\t\tstring = ''\n\t\tfor idx_cls in range(node.num_cls):\n\t\t\tstring += str(node.labels.count(idx_cls)) + ' '\n\t\tprint(indent + ' num of sample / cls: ' + string)\n\n\t\tif node.splittable:\n\t\t\tprint(indent + ' split by dim {:d}'.format(node.dim_split))\n\t\t\tfor idx_child, child in enumerate(node.children):\n\t\t\t\tself.print_tree(node=child, name= ' '+name+'/'+str(idx_child), indent=indent+' ')\n\t\telse:\n\t\t\tprint(indent + ' cls', node.cls_max)\n\t\tprint(indent+'}')\n\n\nclass TreeNode(object):\n\tdef __init__(self, features: List[List[float]], labels: List[int], num_cls: int):\n\t\tself.features = features\n\t\tself.labels = labels\n\t\tself.children = []\n\t\tself.num_cls = num_cls\n\n\t\tcount_max = 0\n\t\tfor label in np.unique(labels):\n\t\t\tif self.labels.count(label) > count_max:\n\t\t\t\tcount_max = labels.count(label)\n\t\t\t\tself.cls_max = label # majority of current node\n\n\t\tif len(np.unique(labels)) < 2:\n\t\t\tself.splittable = False\n\t\telse:\n\t\t\tself.splittable = True\n\n\t\tself.dim_split = None # the index of the feature to be split\n\n\t\tself.feature_uniq_split = None # the possible unique values of the feature to be split\n\n\n\tdef split(self):\n\t\tdef conditional_entropy(branches: List[List[int]]) -> float:\n\t\t\t'''\n\t\t\tbranches: C x B array, \n\t\t\t\t\t C is the number of classes,\n\t\t\t\t\t B is the number of branches\n\t\t\t\t\t it stores the number of \n\t\t\t\t\t corresponding training samples \n\t\t\t\t\t e.g.\n\t\t\t\t\t ○ ○ ○ ○\n\t\t\t\t\t ● ● ● ●\n\t\t\t\t\t ┏━━━━┻━━━━┓\n\t\t\t\t ○ ○ ○ ○\n\t\t\t\t ● ● ● ●\n\t\t\t\t \n\t\t\t\t branches = [[2,2], [4,0]]\n\t\t\t'''\n\t\t\t########################################################\n\t\t\t# TODO: compute the conditional entropy\n\t\t\t########################################################\n\t\t\tbranch_arr = np.array(branches)\n\t\t\tbranch_T = np.transpose(branch_arr).tolist()\n\t\t\ttotal = float(np.sum(branch_arr)) # 8\n\t\t\tcd_entropy = 0.0\n\n\t\t\tfor b in branch_T:\n\t\t\t br_total = float(sum(b)) # 6 and then for = 2\n\t\t\t weight = br_total / total\n\t\t\t if br_total == 0:\t# can't divide by zero so go to next iteration\n\t\t\t continue\n\t\t\t for cls_val in b:\n\t\t\t \tif cls_val > 0:\n\t\t\t \t prob = float(cls_val) / br_total # 2/6 and then 2/2\n\t\t\t \t cd_entropy -= prob * np.log(prob) * weight\n\t\t\treturn cd_entropy\n\n\t\tif not self.splittable:\n\t\t\treturn\n\n\t\tfeatures = np.array(self.features)\n\t\tentr = []\n\n\t\tfor idx_dim in range(len(self.features[0])):\n\t\t############################################################\n\t\t# TODO: compare each split using conditional entropy\n\t\t# find the best split\n\t\t############################################################\n\t\t\tfeat = features[:, idx_dim]\n\t\t\tdivn = []\n\n\t\t\tfor t in np.unique(feat):\n\t\t\t\tt_features = feat[np.where(feat == t)]\n\t\t\t\tt_labels = np.array(self.labels)[np.where(feat == t)]\n\t\t\t\tbran = []\n\n\t\t\t\tfor i in range(self.num_cls):\n\t\t\t\t\tbran.append(np.sum(t_labels == i))\n\t\t\t\tdivn.append(bran)\n\n\t\t\tentr.append(conditional_entropy(np.array(divn).T.tolist()))\n\n\t\tself.dim_split = np.argmin(entr)\n\t\tfeat = features[:,self.dim_split]\n\t\tself.feature_uniq_split = np.unique(feat).tolist()\n\t\t#print('self.feature unique = ',self.feature_uniq_split)\n\n\t\t############################################################\n\t\t# TODO: split the node, add child nodes\n\t\t############################################################\n\t\tif len(np.unique(feat)) > 1:\n\t\t\tfor t in np.unique(feat):\n\t\t\t\tt_features = features[np.where(feat == t)].tolist()\n\t\t\t\tt_labels = np.array(self.labels)[np.where(feat == t)].tolist()\n\t\t\t\tself.children.append(TreeNode(t_features, t_labels, self.num_cls))\n\t\telse:\n\t\t\tself.splittable = False\n\n\t\t# split the child nodes\n\t\tfor child in self.children:\n\t\t\tif child.splittable:\n\t\t\t\tchild.split()\n\n\t\treturn\n\n\tdef predict(self, feature: List[int]) -> int:\n\t\tif self.splittable:\n\t\t\t# print(feature)\n\t\t\tidx_child = self.feature_uniq_split.index(feature[self.dim_split])\n\t\t\treturn self.children[idx_child].predict(feature)\n\t\telse:\n\t\t\treturn self.cls_max\n\n\n\n", "sub_path": "machine_learning_assignments/P3/decision_tree.py", "file_name": "decision_tree.py", "file_ext": "py", "file_size_in_byte": 4813, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "classifier.Classifier", "line_number": 5, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 10, "usage_type": "name"}, {"api_name": "numpy.max", "line_number": 14, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 23, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 49, "usage_type": "name"}, {"api_name": "numpy.unique", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 61, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 72, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 91, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 121, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 122, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 127, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 130, "usage_type": "call"}, {"api_name": "numpy.argmin", "line_number": 132, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 134, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 140, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 141, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 142, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 143, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 143, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 155, "usage_type": "name"}]}
+{"seq_id": "506787415", "text": "import base64\nimport hmac\nimport time\nimport traceback\nimport typing\nimport re\nimport jwt\nimport datetime\nfrom jwt.exceptions import ExpiredSignatureError, DecodeError\nfrom starlette.requests import Request\nfrom starlette.responses import JSONResponse\nfrom app.core.utils.exceptions import APIException\nfrom starlette.status import HTTP_500_INTERNAL_SERVER_ERROR\nfrom app.core.middlewares.api_logger import api_logger\n\nEXCEPT_PATH_REGEX = \"^(/docs|/redoc|/api/auth)\"\nEXCEPT_PATH_LIST = [\"/\", \"/openapi.json\"]\n\ndef to_dict(data):\n return data.__dict__['__data__']\n\nasync def access_control(request: Request, call_next):\n request.state.req_time = datetime.date.today()\n request.state.start = time.time()\n request.state.inspect = None\n request.state.user = None\n request.state.service = None\n\n ip = request.headers[\"x-forwarded-for\"] if \"x-forwarded-for\" in request.headers.keys() else request.client.host\n request.state.ip = ip.split(\",\")[0] if \",\" in ip else ip\n headers = request.headers\n cookies = request.cookies\n\n url = request.url.path\n if await url_pattern_check(url, EXCEPT_PATH_REGEX) or url in EXCEPT_PATH_LIST:\n response = await call_next(request)\n if url != \"/\":\n await api_logger(request=request, response=response)\n return response\n\n try:\n if url.startswith(\"/test\"):\n # test 인경우 헤더로 토큰 검사 => 너가 원하는대로 고쳐서 쓰면 됨\n if url.startswith(\"/api/services\"):\n qs = str(request.query_params)\n qs_list = qs.split(\"&\")\n\n response = await call_next(request)\n return response\n\n else:\n # 템플릿 렌더링인 경우 쿠키에서 토큰 검사\n cookies[\"Authorization\"] = \"Bearer\"\n\n response = await call_next(request)\n await api_logger(request=request, response=response)\n except APIException as e:\n response = await test_exception_handler(e)\n await api_logger(request=request, error=e)\n except Exception as e:\n\n error = await exception_handler(e)\n\n # error_dict = dict(status=error.status_code, msg=error.msg, detail=error.detail, code=error.code)\n # response = JSONResponse(status_code=error.status_code, content=error_dict)\n print(e.args)\n print(traceback.format_exc())\n error.status_code, content = HTTP_500_INTERNAL_SERVER_ERROR, {\n \"statusCode\": 500,\n \"error\": \"Bad Request\",\n \"message\": \"잠시 후 다시 시도해 주시길 바랍니다.\"\n }\n response = JSONResponse(status_code=error.status_code, content=content)\n try:\n request.errorMessage = e.args\n except:\n pass\n await api_logger(request=request, error=error)\n\n return response\n\n\nasync def url_pattern_check(path, pattern):\n result = re.match(pattern, path)\n if result:\n return True\n return False\n\nasync def exception_handler(error: Exception):\n print(error)\n return error\n\nasync def test_exception_handler(error: APIException):\n error_dict = dict(status=error.status_code, msg=error.msg, detail=error.detail, code=error.code)\n res = JSONResponse(status_code=error.status_code,content=error_dict)\n return res", "sub_path": "app/core/middlewares/token_validator.py", "file_name": "token_validator.py", "file_ext": "py", "file_size_in_byte": 3304, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "starlette.requests.Request", "line_number": 22, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 23, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 23, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 24, "usage_type": "call"}, {"api_name": "app.core.middlewares.api_logger.api_logger", "line_number": 38, "usage_type": "call"}, {"api_name": "app.core.middlewares.api_logger.api_logger", "line_number": 56, "usage_type": "call"}, {"api_name": "app.core.utils.exceptions.APIException", "line_number": 57, "usage_type": "name"}, {"api_name": "app.core.middlewares.api_logger.api_logger", "line_number": 59, "usage_type": "call"}, {"api_name": "traceback.format_exc", "line_number": 67, "usage_type": "call"}, {"api_name": "starlette.status.HTTP_500_INTERNAL_SERVER_ERROR", "line_number": 68, "usage_type": "name"}, {"api_name": "starlette.responses.JSONResponse", "line_number": 73, "usage_type": "call"}, {"api_name": "app.core.middlewares.api_logger.api_logger", "line_number": 78, "usage_type": "call"}, {"api_name": "re.match", "line_number": 84, "usage_type": "call"}, {"api_name": "app.core.utils.exceptions.APIException", "line_number": 93, "usage_type": "name"}, {"api_name": "starlette.responses.JSONResponse", "line_number": 95, "usage_type": "call"}]}
+{"seq_id": "178375027", "text": "import sys, traceback\n\nimport discord\nfrom discord.ext import commands\n\nimport settings\n\ninitial_extensions = [\n \"bot-gen\",\n \"bot-help\",\n \"bot-errors\",\n\n \"bot-roles\",\n \"bot-money\",\n]\n\nbot = commands.Bot(command_prefix = \"-\", case_insensitive = True)\nbot.remove_command(\"help\")\n\nif __name__ == \"__main__\":\n for extension in initial_extensions:\n try:\n bot.load_extension(extension)\n except Exception as e:\n #print(f\"Failed to load extension {extension}.\", file = sys.stderr)\n traceback.print_exc()\n\n@bot.event\nasync def on_ready():\n print(bot.user.name)\n print(f\"\\nLogged in as: {bot.user.name} - {bot.user.id}\\ndiscord.py version: {discord.__version__}\\n\")\n await bot.change_presence(activity = discord.Game(name=\"with the matrix\"))\n print(\"Successfully logged in and booted...!\")\n\nbot.run(\"NjE3MjQwNTMxNjQ2NDE0ODQ4.XZ6-RA.25BAY_eiS1fNInIwTDaxiC_JIBw\", bot=True, reconnect=True)\n", "sub_path": "bot-DESKTOP-VJFKRT9.py", "file_name": "bot-DESKTOP-VJFKRT9.py", "file_ext": "py", "file_size_in_byte": 955, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "discord.ext.commands.Bot", "line_number": 17, "usage_type": "call"}, {"api_name": "discord.ext.commands", "line_number": 17, "usage_type": "name"}, {"api_name": "traceback.print_exc", "line_number": 26, "usage_type": "call"}, {"api_name": "discord.__version__", "line_number": 31, "usage_type": "attribute"}, {"api_name": "discord.Game", "line_number": 32, "usage_type": "call"}]}
+{"seq_id": "505136630", "text": "from binascii import hexlify, unhexlify\n\nimport structlog\nfrom eth_utils import (\n is_binary_address,\n to_checksum_address,\n to_normalized_address,\n to_canonical_address,\n)\nfrom web3.utils.filters import Filter\nfrom web3.exceptions import BadFunctionCallOutput\n\nfrom raiden.blockchain.abi import (\n CONTRACT_MANAGER,\n CONTRACT_REGISTRY,\n EVENT_TOKEN_ADDED,\n)\nfrom raiden.exceptions import (\n NoTokenManager,\n TransactionThrew,\n)\nfrom raiden.network.proxies.channel_manager import ChannelManager\nfrom raiden.network.rpc.client import check_address_has_code\nfrom raiden.network.rpc.smartcontract_proxy import ContractProxy\nfrom raiden.network.rpc.transactions import check_transaction_threw\nfrom raiden.utils import (\n pex,\n privatekey_to_address,\n typing,\n)\n\nlog = structlog.get_logger(__name__) # pylint: disable=invalid-name\n\ntry:\n from eth_tester.exceptions import TransactionFailed\nexcept ModuleNotFoundError:\n TransactionFailed = Exception()\n\n\nclass Registry:\n def __init__(\n self,\n jsonrpc_client,\n registry_address,\n ):\n # pylint: disable=too-many-arguments\n contract = jsonrpc_client.new_contract(\n CONTRACT_MANAGER.get_contract_abi(CONTRACT_REGISTRY),\n to_normalized_address(registry_address),\n )\n proxy = ContractProxy(jsonrpc_client, contract)\n\n if not is_binary_address(registry_address):\n raise ValueError('registry_address must be a valid address')\n\n check_address_has_code(jsonrpc_client, registry_address, 'Registry')\n\n CONTRACT_MANAGER.check_contract_version(\n proxy.contract.functions.contract_version().call(),\n CONTRACT_REGISTRY,\n )\n\n self.address = registry_address\n self.client = jsonrpc_client\n self.node_address = privatekey_to_address(self.client.privkey)\n self.proxy = proxy\n\n self.address_to_channelmanager = dict()\n self.token_to_channelmanager = dict()\n\n def manager_address_by_token(self, token_address):\n \"\"\" Return the channel manager address for the given token or None if\n there is no correspoding address.\n \"\"\"\n try:\n address = self.proxy.contract.functions.channelManagerByToken(\n to_checksum_address(token_address),\n ).call()\n except (BadFunctionCallOutput, TransactionFailed):\n check_address_has_code(self.client, self.address)\n return None\n\n return to_canonical_address(address)\n\n def add_token(self, token_address):\n if not is_binary_address(token_address):\n raise ValueError('token_address must be a valid address')\n\n log.info(\n 'add_token called',\n node=pex(self.node_address),\n token_address=pex(token_address),\n registry_address=pex(self.address),\n )\n\n transaction_hash = self.proxy.transact(\n 'addToken',\n self.address,\n token_address,\n )\n\n self.client.poll(unhexlify(transaction_hash))\n receipt_or_none = check_transaction_threw(self.client, transaction_hash)\n if receipt_or_none:\n log.info(\n 'add_token failed',\n node=pex(self.node_address),\n token_address=pex(token_address),\n registry_address=pex(self.address),\n )\n raise TransactionThrew('AddToken', receipt_or_none)\n\n manager_address = self.manager_address_by_token(token_address)\n\n if manager_address is None:\n log.info(\n 'add_token failed and check_transaction_threw didnt detect it',\n node=pex(self.node_address),\n token_address=pex(token_address),\n registry_address=pex(self.address),\n )\n\n raise RuntimeError('channelManagerByToken failed')\n\n log.info(\n 'add_token sucessful',\n node=pex(self.node_address),\n token_address=pex(token_address),\n registry_address=pex(self.address),\n manager_address=pex(manager_address),\n )\n\n return manager_address\n\n def token_addresses(self):\n addresses = self.proxy.contract.functions.tokenAddresses().call()\n return [\n to_canonical_address(address)\n for address in addresses\n ]\n\n def manager_addresses(self):\n addresses = self.proxy.contract.functions.channelManagerAddresses().call()\n return [\n to_canonical_address(address)\n for address in addresses\n ]\n\n def tokenadded_filter(\n self,\n from_block: typing.BlockSpecification = 0,\n to_block: typing.BlockSpecification = 'latest',\n ) -> Filter:\n topics = [CONTRACT_MANAGER.get_event_id(EVENT_TOKEN_ADDED)]\n\n registry_address_bin = self.proxy.contract_address\n return self.client.new_filter(\n registry_address_bin,\n topics=topics,\n from_block=from_block,\n to_block=to_block,\n )\n\n def manager(self, manager_address):\n \"\"\" Return a proxy to interact with a ChannelManagerContract. \"\"\"\n if not is_binary_address(manager_address):\n raise ValueError('manager_address must be a valid address')\n\n if manager_address not in self.address_to_channelmanager:\n manager = ChannelManager(\n self.client,\n manager_address,\n )\n\n token_address = manager.token_address()\n\n self.token_to_channelmanager[token_address] = manager\n self.address_to_channelmanager[manager_address] = manager\n\n return self.address_to_channelmanager[manager_address]\n\n def manager_by_token(self, token_address):\n \"\"\" Find the channel manager for `token_address` and return a proxy to\n interact with it.\n\n If the token is not already registered it raises `EthNodeCommunicationError`,\n since we try to instantiate a Channel manager with an empty address.\n \"\"\"\n if not is_binary_address(token_address):\n raise ValueError('token_address must be a valid address')\n\n if token_address not in self.token_to_channelmanager:\n check_address_has_code(self.client, token_address) # check that the token exists\n manager_address = self.manager_address_by_token(token_address)\n\n if manager_address is None:\n raise NoTokenManager(\n 'Manager for token 0x{} does not exist'.format(hexlify(token_address)),\n )\n\n manager = ChannelManager(\n self.client,\n manager_address,\n )\n\n self.token_to_channelmanager[token_address] = manager\n self.address_to_channelmanager[manager_address] = manager\n\n return self.token_to_channelmanager[token_address]\n", "sub_path": "raiden/network/proxies/registry.py", "file_name": "registry.py", "file_ext": "py", "file_size_in_byte": 6983, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "structlog.get_logger", "line_number": 32, "usage_type": "call"}, {"api_name": "eth_tester.exceptions.TransactionFailed", "line_number": 37, "usage_type": "name"}, {"api_name": "raiden.blockchain.abi.CONTRACT_MANAGER.get_contract_abi", "line_number": 48, "usage_type": "call"}, {"api_name": "raiden.blockchain.abi.CONTRACT_REGISTRY", "line_number": 48, "usage_type": "argument"}, {"api_name": "raiden.blockchain.abi.CONTRACT_MANAGER", "line_number": 48, "usage_type": "name"}, {"api_name": "eth_utils.to_normalized_address", "line_number": 49, "usage_type": "call"}, {"api_name": "raiden.network.rpc.smartcontract_proxy.ContractProxy", "line_number": 51, "usage_type": "call"}, {"api_name": "eth_utils.is_binary_address", "line_number": 53, "usage_type": "call"}, {"api_name": "raiden.network.rpc.client.check_address_has_code", "line_number": 56, "usage_type": "call"}, {"api_name": "raiden.blockchain.abi.CONTRACT_MANAGER.check_contract_version", "line_number": 58, "usage_type": "call"}, {"api_name": "raiden.blockchain.abi.CONTRACT_REGISTRY", "line_number": 60, "usage_type": "argument"}, {"api_name": "raiden.blockchain.abi.CONTRACT_MANAGER", "line_number": 58, "usage_type": "name"}, {"api_name": "raiden.utils.privatekey_to_address", "line_number": 65, "usage_type": "call"}, {"api_name": "eth_utils.to_checksum_address", "line_number": 77, "usage_type": "call"}, {"api_name": "web3.exceptions.BadFunctionCallOutput", "line_number": 79, "usage_type": "name"}, {"api_name": "eth_tester.exceptions.TransactionFailed", "line_number": 79, "usage_type": "name"}, {"api_name": "raiden.network.rpc.client.check_address_has_code", "line_number": 80, "usage_type": "call"}, {"api_name": "eth_utils.to_canonical_address", "line_number": 83, "usage_type": "call"}, {"api_name": "eth_utils.is_binary_address", "line_number": 86, "usage_type": "call"}, {"api_name": "raiden.utils.pex", "line_number": 91, "usage_type": "call"}, {"api_name": "raiden.utils.pex", "line_number": 92, "usage_type": "call"}, {"api_name": "raiden.utils.pex", "line_number": 93, "usage_type": "call"}, {"api_name": "binascii.unhexlify", "line_number": 102, "usage_type": "call"}, {"api_name": "raiden.network.rpc.transactions.check_transaction_threw", "line_number": 103, "usage_type": "call"}, {"api_name": "raiden.utils.pex", "line_number": 107, "usage_type": "call"}, {"api_name": "raiden.utils.pex", "line_number": 108, "usage_type": "call"}, {"api_name": "raiden.utils.pex", "line_number": 109, "usage_type": "call"}, {"api_name": "raiden.exceptions.TransactionThrew", "line_number": 111, "usage_type": "call"}, {"api_name": "raiden.utils.pex", "line_number": 118, "usage_type": "call"}, {"api_name": "raiden.utils.pex", "line_number": 119, "usage_type": "call"}, {"api_name": "raiden.utils.pex", "line_number": 120, "usage_type": "call"}, {"api_name": "raiden.utils.pex", "line_number": 127, "usage_type": "call"}, {"api_name": "raiden.utils.pex", "line_number": 128, "usage_type": "call"}, {"api_name": "raiden.utils.pex", "line_number": 129, "usage_type": "call"}, {"api_name": "raiden.utils.pex", "line_number": 130, "usage_type": "call"}, {"api_name": "eth_utils.to_canonical_address", "line_number": 138, "usage_type": "call"}, {"api_name": "eth_utils.to_canonical_address", "line_number": 145, "usage_type": "call"}, {"api_name": "raiden.utils.typing.BlockSpecification", "line_number": 151, "usage_type": "attribute"}, {"api_name": "raiden.utils.typing", "line_number": 151, "usage_type": "name"}, {"api_name": "raiden.utils.typing.BlockSpecification", "line_number": 152, "usage_type": "attribute"}, {"api_name": "raiden.utils.typing", "line_number": 152, "usage_type": "name"}, {"api_name": "raiden.blockchain.abi.CONTRACT_MANAGER.get_event_id", "line_number": 154, "usage_type": "call"}, {"api_name": "raiden.blockchain.abi.EVENT_TOKEN_ADDED", "line_number": 154, "usage_type": "argument"}, {"api_name": "raiden.blockchain.abi.CONTRACT_MANAGER", "line_number": 154, "usage_type": "name"}, {"api_name": "web3.utils.filters.Filter", "line_number": 153, "usage_type": "name"}, {"api_name": "eth_utils.is_binary_address", "line_number": 166, "usage_type": "call"}, {"api_name": "raiden.network.proxies.channel_manager.ChannelManager", "line_number": 170, "usage_type": "call"}, {"api_name": "eth_utils.is_binary_address", "line_number": 189, "usage_type": "call"}, {"api_name": "raiden.network.rpc.client.check_address_has_code", "line_number": 193, "usage_type": "call"}, {"api_name": "raiden.exceptions.NoTokenManager", "line_number": 197, "usage_type": "call"}, {"api_name": "binascii.hexlify", "line_number": 198, "usage_type": "call"}, {"api_name": "raiden.network.proxies.channel_manager.ChannelManager", "line_number": 201, "usage_type": "call"}]}
+{"seq_id": "475649473", "text": "from django.db import models\n\n# Create your models here.\n\nfrom bases.models import ClassModelo\n\n\nclass Category(ClassModelo):\n description = models.CharField(\n max_length=100,\n help_text='Category Description',\n unique=True\n )\n\n def __srt__(self):\n return '{}'.format(self.description)\n\n def save(self):\n self.description = self.description.upper()\n\n super(Category, self).save()\n \n class Meta:\n verbose_name_plural = 'Categories'\n\n\nclass SubCategory(ClassModelo):\n category = models.ForeignKey(Category, on_delete=models.CASCADE)\n description = models.CharField(\n max_length=100,\n help_text='Description Category',\n unique=True\n )\n\n def __str__(self):\n return '{}:{}'.format(self.category.description, self.description)\n\n def save(self):\n self.description = self.description.upper()\n\n super(SubCategory, self).save()\n\n class Meta:\n verbose_name_plural = 'Sub Categories'\n unique_together = ('category', 'description')\n", "sub_path": "app/inv/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 1060, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "bases.models.ClassModelo", "line_number": 8, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 9, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 9, "usage_type": "name"}, {"api_name": "bases.models.ClassModelo", "line_number": 27, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 28, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 28, "usage_type": "name"}, {"api_name": "django.db.models.CASCADE", "line_number": 28, "usage_type": "attribute"}, {"api_name": "django.db.models.CharField", "line_number": 29, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 29, "usage_type": "name"}]}
+{"seq_id": "13608599", "text": "from bs4 import BeautifulSoup\nfrom splinter import Browser\nfrom splinter.exceptions import ElementDoesNotExist\nfrom selenium import webdriver\nimport time\nimport requests\nimport pandas as pd\n\ndef init_browser():\n # @NOTE: Replace the path with your actual path to the chromedriver\n executable_path = {\"executable_path\": \"chromedriver\"}\n return Browser(\"chrome\", **executable_path, headless=False)\n\ndef scrape():\n mars = {}\n\n #-----------------------------------------------------------------------\n #Part 1: NASA Mars News\n url_news = 'https://mars.nasa.gov/news/?page=0&per_page=40&order=publish_date+desc%2Ccreated_at+desc&search=&category=19%2C165%2C184%2C204&blank_scope=Latest'\n\n browser_sele = webdriver.Chrome()\n browser_sele.get(url_news)\n soup_selenium = BeautifulSoup(browser_sele.page_source, \"html.parser\")\n\n mars[\"news_title\"] = soup_selenium.find('div', class_=\"content_title\").text.strip()\n time.sleep(2)\n mars[\"news_p\"] = soup_selenium.find('div', class_=\"article_teaser_body\").text.strip()\n\n print(\"---------------------------------------------------------------------------------------\")\n print(\"Part 1: NASA Mars News Complete! Next: Part 3: Mars Weather \")\n\n browser_sele.quit()\n\n #-----------------------------------------------------------------------\n #Part 3: Mars Weather\n url_twit = 'https://twitter.com/marswxreport?lang=en'\n response_tw = requests.get(url_twit)\n soup_tw = BeautifulSoup(response_tw.text, 'html.parser')\n last_twit = (soup_tw.find('div', class_=\"js-tweet-text-container\")).find('p')\n split = last_twit.get_text().split(last_twit.find('a').text.strip()) \n mars[\"mars_weather\"] = split[0].replace('\\n', ', ')\n print(\"---------------------------------------------------------------------------------------\")\n print(\"Part 3: Mars Weather Complete! Next: Part 4: Mars Facts\")\n \n #-----------------------------------------------------------------------\n #Part 4: Mars Facts\n url_facts = 'https://space-facts.com/mars/'\n tables = pd.read_html(url_facts)\n df = tables[0]\n df.columns = ['Description', 'Value']\n df.set_index('Description', inplace=True)\n html_table = df.to_html()\n html_table.replace('\\n', '')\n mars[\"mars_facts\"]= html_table\n print(\"---------------------------------------------------------------------------------------\")\n print(\"Part 4: Mars Facts Complete! Next: Part 2: JPL Mars Space Images - Featured Image\")\n\n #-----------------------------------------------------------------------\n #Part 2: JPL Mars Space Images - Featured Image\n\n browser = init_browser()\n url_pic = 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars'\n browser.visit(url_pic)\n\n browser.links.find_by_partial_text('FULL IMAGE')\n browser.click_link_by_partial_text('FULL IMAGE')\n time.sleep(3)\n\n html = browser.html\n soup_pic = BeautifulSoup(html, 'html.parser')\n\n featured_image_url = \"http://www.jpl.nasa.gov\" + soup_pic.find('img', class_='fancybox-image')['src']\n mars[\"featured_image_url\"] = featured_image_url\n print(\"---------------------------------------------------------------------------------------\")\n print(\"Part 2: JPL Mars Space Images - Featured Image Complete! Next: Part 5: Mars Hemispheres\")\n\n #-----------------------------------------------------------------------\n #Part 5 Mars Hemispheres\n url_hemisphere = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'\n browser.visit(url_hemisphere)\n\n html = browser.html\n soup = BeautifulSoup(html, 'html.parser')\n\n print(\"---------------------------------------------------------------------------------------\")\n print(\"Compiling Hemisphere List\")\n\n results_hemisphere = soup.find('div', class_='full-content')\n titles_hemisphere = results_hemisphere.find_all('h3')\n\n title_list = []\n for title in titles_hemisphere:\n clean_title = str.strip(title.text)\n title_list.append(clean_title)\n \n print(\"Hemisphere List Complete! Next: Scraping Hemisphere Pic Url\")\n \n hemisphere_image_urls = []\n for x in range(len(title_list)):\n \n try:\n url_hemisphere = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'\n browser.visit(url_hemisphere)\n time.sleep(1)\n \n browser.links.find_by_partial_text(title_list[x])\n browser.click_link_by_partial_text(title_list[x])\n \n html = browser.html\n soup_pic = BeautifulSoup(html, 'html.parser')\n \n eachpic_hemisphere = soup_pic.find('div', class_='downloads')\n eachpic_link = eachpic_hemisphere.find('a')['href']\n \n pics_dict = {}\n pics_dict[\"title\"] = title_list[x]\n pics_dict[\"img_url\"] = eachpic_link\n hemisphere_image_urls.append(pics_dict)\n \n time.sleep(2)\n \n except ElementDoesNotExist:\n print(\"Scraping Complete\")\n\n mars[\"hemisphere_image_urls\"] = hemisphere_image_urls \n print(\"Part 5: Mars Hemispheres Complete! Next: Compiling into one dictionary\")\n browser.quit()\n\n #-----------------------------------------------------------------------\n print(\"---------------------------------------------------------------------------------------\")\n print(\"Complete Mars Data\")\n print(mars)\n return mars\n", "sub_path": "HW12 WebScraping-Challenge/Flask - Scrape Render/scrape_mars.py", "file_name": "scrape_mars.py", "file_ext": "py", "file_size_in_byte": 5518, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "splinter.Browser", "line_number": 12, "usage_type": "call"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 21, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 21, "usage_type": "name"}, {"api_name": "bs4.BeautifulSoup", "line_number": 23, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 26, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 37, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 38, "usage_type": "call"}, {"api_name": "pandas.read_html", "line_number": 48, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 67, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 70, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 83, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 104, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 110, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 120, "usage_type": "call"}, {"api_name": "splinter.exceptions.ElementDoesNotExist", "line_number": 122, "usage_type": "name"}]}
+{"seq_id": "618561631", "text": "import json\n\nfrom collections import defaultdict, OrderedDict\n\nfrom bricklink import read_json\nfrom operator import itemgetter\n\n\n# Una query ad-hoc para ver como de costoso es generar este codigo vs tenerlo en mysql.\ndef count_set_pieces():\n filtered_sets = filter_sets(read_json('data/BrickLink/Sets.json'))\n\n inventoried_parts = defaultdict(lambda: 0)\n unknown_qty_count = 0\n non_parts_count = 0\n missing_inventory_count = 0\n\n for the_set in filtered_sets:\n set_id = the_set['ITEMID']\n try:\n with open('data/BrickLink/Inventories/{}.json'.format(set_id)) as set_inventory_json_file:\n set_inventory_json = json.load(set_inventory_json_file)\n\n for part in set_inventory_json:\n if not part['QTY'].isdigit():\n unknown_qty_count += 1\n elif part['ITEMTYPE'] != 'P':\n non_parts_count += 1\n else:\n qty = int(part['QTY'])\n part_id = part['ITEMID']\n inventoried_parts[part_id] += qty\n except FileNotFoundError as exc:\n missing_inventory_count += 1\n\n print(\"Number of part types: {}\".format(len(inventoried_parts)))\n print(\"Number of non-parts (mini-figures...): {}, Missing inventories: {}, Unknown quantities for {} parts\"\n .format(non_parts_count, missing_inventory_count, unknown_qty_count))\n\n inventoried_sorted_parts = OrderedDict(sorted(inventoried_parts.items(), key=itemgetter(1), reverse=True))\n parts = read_json('data/BrickLink/Parts.json')\n\n for key, value in inventoried_sorted_parts.items():\n\n if value <= 100:\n break\n\n part = next(part for part in parts if part['ITEMID'] == key)\n from html import unescape\n print(\"Part {}, Qty: {}, Name: {}\".format(key, value, unescape(part['ITEMNAME'])))\n\n\ndef filter_sets(the_sets):\n modern_sets = [the_set for the_set in the_sets\n if the_set['ITEMYEAR'].isdigit() and int(the_set['ITEMYEAR']) >= 1995]\n\n print(\"Number of modern sets found: {}\".format(len(modern_sets)))\n\n categories = read_json('data/BrickLink/Categories.json')\n\n def get_category_name(category_id):\n return next(category['CATEGORYNAME'] for category in categories if category['CATEGORY'] == category_id)\n\n return [the_set for the_set in modern_sets\n if \"duplo\" not in get_category_name(the_set['CATEGORY']).lower()]\n", "sub_path": "query_experiment.py", "file_name": "query_experiment.py", "file_ext": "py", "file_size_in_byte": 2506, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "bricklink.read_json", "line_number": 11, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 13, "usage_type": "call"}, {"api_name": "json.load", "line_number": 22, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 40, "usage_type": "call"}, {"api_name": "operator.itemgetter", "line_number": 40, "usage_type": "call"}, {"api_name": "bricklink.read_json", "line_number": 41, "usage_type": "call"}, {"api_name": "html.unescape", "line_number": 50, "usage_type": "call"}, {"api_name": "bricklink.read_json", "line_number": 59, "usage_type": "call"}]}
+{"seq_id": "542764533", "text": "# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy.shell import inspect_response\nimport json\nfrom urllib.parse import urlencode\nfrom urllib.parse import urljoin\nimport csv\nimport io\nimport logging\n\nclass CodeSpider(scrapy.Spider):\n name = 'code'\n \n allowed_domains = ['mercadopublico.cl']\n # Enter Login and Password\n rut = '22.087.581-4'\n passw= 'Licita.1234'\n \n \n \n \n \n def __init__(self, gs_id='', **kwargs):\n \n super().__init__(**kwargs)\n #Check if google id is provided, else use predefined\n if not gs_id:\n gs_id = '1AVcpYlYTBqepqycOUPp01Aub9NcT2xGfBbdep3x4-W4'\n \n logging.info(gs_id) \n # logging.info(gs_id)\n # Base url for downloading data from google sheets as csv\n self.input_url = 'https://docs.google.com/spreadsheets/d/{}/export?format=csv'.format(gs_id)\n # Decalre variables for later use\n self.detail_keys = []\n # Active product ( being edited at current time)\n self.active = []\n # List of all products to edit\n self.details = []\n self.headers = {\n 'accept': \"application/json, text/javascript, */*; q=0.01\",\n 'origin': \"https://www.mercadopublico.cl\",\n 'x-requested-with': \"XMLHttpRequest\",\n 'user-agent': \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36\",\n 'dnt': \"1\",\n 'content-type': \"application/x-www-form-urlencoded\",\n 'cache-control': \"no-cache\", \n }\n \n\n \n def start_requests(self):\n #Download Google sheets with input data\n url = self.input_url\n yield scrapy.Request(url)\n \n \n \n def parse(self, response):\n #Read Google sheet and create details list from its data.\n sio = io.StringIO( response.text, newline=None) #.encode('ascii','ignore').decode('ascii')\n reader = csv.reader(sio, dialect=csv.excel)\n \n \n for row in reader:\n self.details.append(row)\n self.detail_keys = self.details[0] \n self.details = self.details[1:] \n self.active = self.details.pop()\n \n # login here. Then select organization that is supposed to be used\n url = 'https://www.mercadopublico.cl/Home/Autenticacion/NuevoLogin'\n data = {'Rut': self.rut,\n 'contraseña': self.passw,\n 'tipoUsuario': 'nacional',\n 'idPais': '0'}\n body = urlencode(data) \n yield scrapy.Request(url, method = 'POST', body = body, headers = self.headers, callback = self.parsed)\n \n \n \n def parsed(self, response):\n # inspect_response(response,self)\n data = json.loads(response.text)\n id = data['sessionID']\n \n # Get organization\n url ='https://www.mercadopublico.cl/Home/Autenticacion/ObtenerOrganizaciones'\n \n data = {'rut': self.rut,\n 'pass': self.passw,\n 'session': id,\n 'tipo': 'login',}\n \n yield scrapy.Request(url, method = 'POST', body = urlencode(data), headers = self.headers, callback = self.select_entity)\n \n def select_entity(self, response):\n # inspect_response(response, self)\n # Getting entity value by entity name\n headers = {\n 'accept': \"*/*\",\n 'origin': \"https://www.mercadopublico.cl\",\n 'x-requested-with': \"XMLHttpRequest\",\n 'user-agent': \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36\",\n 'dnt': \"1\",\n 'content-type': \"application/json; charset=UTF-8\",\n 'cache-control': \"no-cache\",\n \n }\n \n entity = self.active[0]\n entity_value = response.xpath(\"//span[text()[ contains(.,'{}')]]/input/@value\".format(entity)).extract_first()\n url = 'https://www.mercadopublico.cl/Home/Autenticacion/LoginPorOrganizacion'\n id = str(response.xpath(\"//input[@id ='hdSession']/@value\").extract_first())\n body = json.dumps({\"CodigoEmpresa\":entity_value,\"sessionId\": id})\n yield scrapy.Request(url, method=\"POST\", body = body, callback = self.middle_menu, headers = headers)\n \n \n \n \n def middle_menu(self, response): \n \n # should click on middle menu\n url = 'http://www.mercadopublico.cl/CMII/Communication/comm.aspx?mode=seller'\n yield scrapy.Request(url, callback = self.convenio_marco)\n \n def convenio_marco(self, response):\n # inspect_response(response, self)\n # Click Administrator on specified agreement\n # Check if agreement description is available\n try:\n agreement_desc = self.active[7]\n url = response.xpath(\"//div[contains(.//h5,'{}')]\".format(agreement_desc))[0].xpath(\".//button/@onclick\").extract_first()\n # If not agreement description use agreement \n except:\n agreement = self.active[1]\n url = response.xpath(\"//div[contains(.//a,'{}')]\".format(agreement))[0].xpath(\".//button/@onclick\").extract_first()\n \n url = url.split(\"('\")[1][:-2]\n url = urljoin(response.url, url)\n yield scrapy.Request(url, callback = self.administrar)\n \n \n def administrar(self, response):\n # inspect_response(response, self)\n #Click on APlicat Uno Oferta button for OfertaEspecial to get to search bar\n url = response.xpath(\"//a[contains(@href, 'frmOfertaEspecial')]/@href\").extract_first()\n url = urljoin(response.url, url)\n \n i = []\n yield scrapy.Request(url, callback = self.search_bar, dont_filter = True)\n \n def search_bar(self, response):\n # inspect_response(response, self)\n \n i = self.active\n body = {'__EVENTARGUMENT': '',\n '__EVENTTARGET': '',\n '__SCROLLPOSITIONX': '0',\n '__SCROLLPOSITIONY': '0',\n \n 'ddlOfertaEspecial': '0',\n 'imgBotonBusca.x': '47',\n 'imgBotonBusca.y': '12',\n }\n # iterating through the list of items to be changed.\n \n body[ 'txtTextoBuscado'] = i[3]\n \n \n yield scrapy.FormRequest.from_response(response, formdata=body, callback=self.item_edited , dont_filter = True )\n \n def item_edited(self, response): \n \n i = self.active\n # inspect_response(response, self) \n \n body = {'CTRL_ListadoOfertasEspeciales1:dgrOfertasEspeciales:_ctl3:imgbtn_Editar.y' : '11',\n 'CTRL_ListadoOfertasEspeciales1:dgrOfertasEspeciales:_ctl3:imgbtn_Editar.x' : '12',\n '__EVENTARGUMENT': '',\n '__EVENTTARGET': '',\n '__SCROLLPOSITIONX': '0',\n '__SCROLLPOSITIONY': '0',\n 'ddlOfertaEspecial': '0',\n }\n body['txtTextoBuscado'] = i[3] \n yield scrapy.FormRequest.from_response(response, formdata=body, callback=self.item_found, dont_filter = True)\n \n def item_found(self, response):\n # inspect_response(response, self) \n cant_modify = response.xpath(\"//input[contains(@title,'no puede modificarla')]\")\n \n i = self.active\n description =i[3]\n # price = str(float(i[1])+1)\n price = i[4]\n startDate = i[5]\n endDate = i[6]\n \n body = {\n 'CTRL_ListadoOfertasEspeciales1:dgrOfertasEspeciales:_ctl3:imgbtn_Guardar.x': '1',\n 'CTRL_ListadoOfertasEspeciales1:dgrOfertasEspeciales:_ctl3:imgbtn_Guardar.y': '1',\n 'CTRL_ListadoOfertasEspeciales1:dgrOfertasEspeciales:_ctl3:txtPrecio_OfEsp': '',\n '__EVENTARGUMENT': '',\n '__EVENTTARGET': '',\n '__SCROLLPOSITIONX': '0',\n '__SCROLLPOSITIONY': '0',\n 'ddlOfertaEspecial': '0',\n }\n body['CTRL_ListadoOfertasEspeciales1:dgrOfertasEspeciales:_ctl3:txtPrecio_OfEsp'] = price\n body['CTRL_ListadoOfertasEspeciales1:dgrOfertasEspeciales:_ctl3:CalendarioPopUp1:txtNombre'] = startDate\n body[ 'CTRL_ListadoOfertasEspeciales1:dgrOfertasEspeciales:_ctl3:CalendarioPopUp1:valorID'] = startDate\n body['CTRL_ListadoOfertasEspeciales1:dgrOfertasEspeciales:_ctl3:CalendarioPopUp2:txtNombre'] = endDate\n body['CTRL_ListadoOfertasEspeciales1:dgrOfertasEspeciales:_ctl3:CalendarioPopUp2:valorID'] = endDate\n body['txtTextoBuscado'] =description \n \n yield scrapy.FormRequest.from_response(response, formdata=body, callback=self.edit_oferta, dont_filter = True)\n pass\n if cant_modify:\n print('Item cant not be modified')\n \n \n \n \n def edit_oferta(self, response):\n # inspect_response(response, self)\n \n alert = response.xpath(\"//script[contains(text(), 'alert')]/text()\").extract()\n active_old = self.active\n value_to_set = active_old[4]\n key = self.detail_keys\n # logging.info(key)\n logging.info(active_old)\n new_ofert = response.xpath(\"//td[@class ='ofertasInterior']/span[contains(@id,'Precio')]/text()\").extract_first()\n if not alert:\n # try:\n inspect_response(response, self)\n logging.info(active_old[4])\n logging.info(type(active_old[4]))\n logging.info( new_ofert)\n logging.info( type(new_ofert))\n if new_ofert:\n # remove spaces dots and comas from ofert values to compare them\n value_to_set = value_to_set.replace('.','').replace(',','').replace(' ','')\n new_ofert = new_ofert.replace('.','').replace(',','').replace(' ','')\n if value_to_set in new_ofert:\n alert = 'OK'\n elif value_to_set == new_ofert:\n alert = 'OK'\n elif value_to_set in new_ofert:\n alert = 'OK'\n else: alert = 'ERROR. New Ofert not equal to Expected value'\n else: alert = 'ERROR. No New Offert'\n \n yield { \n key[0] : active_old[0],\n key[1] : active_old[1],\n key[2] : active_old[2],\n key[3] : active_old[3],\n 'new_desc' : response.xpath(\"//a[contains(@href, 'NombreProducto')]/text()\").extract_first(), \n key[4] : active_old[4],\n 'new_ofert' : new_ofert,\n key[5] : active_old[5],\n 'new_date_start' : response.xpath(\"//td[@class ='ofertasInterior']/span[contains(@id,'Inicio')]/text()\").extract_first(),\n key[6] : active_old[6],\n 'new_date_end' : response.xpath(\"//td[@class ='ofertasInterior']/span[contains(@id,'Termino')]/text()\").extract_first(),\n 'alert' : alert,\n }\n \n # Check if any products left to edit\n if self.details:\n \n # Assign new product to active\n self.active = self.details.pop()\n active = self.active\n # Check if entity and agreement are the same for previous and next item.\n if active_old[0] == active[0] and active_old[1] == active[1]:\n \n body = {'__EVENTARGUMENT': '',\n '__EVENTTARGET': '',\n '__SCROLLPOSITIONX': '0',\n '__SCROLLPOSITIONY': '0',\n \n 'ddlOfertaEspecial': '0',\n 'imgBotonBusca.x': '47',\n 'imgBotonBusca.y': '12',\n }\n # iterating through the list of items to be changed.\n \n body[ 'txtTextoBuscado'] = active[3]\n \n \n yield scrapy.FormRequest.from_response(response, formdata=body, callback=self.item_edited , dont_filter = True )\n # Check if entity is different but agreement is the same for previous and next item.\n elif active_old[0] != active[0]:\n \n cookie = str(response.request.headers['Cookie']).split('; ')\n id = [i.split('=')[-1] for i in cookie if 'ASP.NET_SessionId=' in i][0]\n \n # Get organization\n url ='https://www.mercadopublico.cl/Home/Autenticacion/ObtenerOrganizaciones'\n \n data = {'rut': self.rut,\n 'pass': self.passw,\n 'session': id,\n 'tipo': 'login',}\n \n yield scrapy.Request(url, method = 'POST', body = urlencode(data), headers = self.headers, callback = self.select_entity)\n else: \n url = 'http://www.mercadopublico.cl/CMII/Communication/comm.aspx?mode=seller'\n yield scrapy.Request(url, callback = self.convenio_marco)", "sub_path": "mercado/spiders/code.py", "file_name": "code.py", "file_ext": "py", "file_size_in_byte": 13855, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "scrapy.Spider", "line_number": 11, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 30, "usage_type": "call"}, {"api_name": "scrapy.Request", "line_number": 55, "usage_type": "call"}, {"api_name": "io.StringIO", "line_number": 61, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 62, "usage_type": "call"}, {"api_name": "csv.excel", "line_number": 62, "usage_type": "attribute"}, {"api_name": "urllib.parse.urlencode", "line_number": 77, "usage_type": "call"}, {"api_name": "scrapy.Request", "line_number": 78, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 84, "usage_type": "call"}, {"api_name": "scrapy.Request", "line_number": 95, "usage_type": "call"}, {"api_name": "urllib.parse.urlencode", "line_number": 95, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 115, "usage_type": "call"}, {"api_name": "scrapy.Request", "line_number": 116, "usage_type": "call"}, {"api_name": "scrapy.Request", "line_number": 125, "usage_type": "call"}, {"api_name": "urllib.parse.urljoin", "line_number": 140, "usage_type": "call"}, {"api_name": "scrapy.Request", "line_number": 141, "usage_type": "call"}, {"api_name": "urllib.parse.urljoin", "line_number": 148, "usage_type": "call"}, {"api_name": "scrapy.Request", "line_number": 151, "usage_type": "call"}, {"api_name": "scrapy.FormRequest.from_response", "line_number": 171, "usage_type": "call"}, {"api_name": "scrapy.FormRequest", "line_number": 171, "usage_type": "attribute"}, {"api_name": "scrapy.FormRequest.from_response", "line_number": 187, "usage_type": "call"}, {"api_name": "scrapy.FormRequest", "line_number": 187, "usage_type": "attribute"}, {"api_name": "scrapy.FormRequest.from_response", "line_number": 217, "usage_type": "call"}, {"api_name": "scrapy.FormRequest", "line_number": 217, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 233, "usage_type": "call"}, {"api_name": "scrapy.shell.inspect_response", "line_number": 237, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 238, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 239, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 240, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 241, "usage_type": "call"}, {"api_name": "scrapy.FormRequest.from_response", "line_number": 293, "usage_type": "call"}, {"api_name": "scrapy.FormRequest", "line_number": 293, "usage_type": "attribute"}, {"api_name": "scrapy.Request", "line_number": 308, "usage_type": "call"}, {"api_name": "urllib.parse.urlencode", "line_number": 308, "usage_type": "call"}, {"api_name": "scrapy.Request", "line_number": 311, "usage_type": "call"}]}
+{"seq_id": "362651292", "text": "\"\"\" Module for handling the serialization of Cast- and CastCollection-like\nobjects to persistent files. \"\"\"\n\nimport six\nimport json\nimport copy\nimport datetime\nimport dateutil.parser\nimport numpy\nimport pandas\nfrom karta import Point, geojson\nfrom . import units\n\ndef castasdict(cast):\n scalars = [key for key in cast.properties]\n vectors = list(cast.data.keys())\n dscalar, dvector = {}, {}\n for key in scalars:\n if isinstance(cast.properties[key], datetime.datetime):\n dscalar[key] = cast.properties[key].isoformat(sep=\" \")\n else:\n dscalar[key] = cast.properties[key]\n for key in vectors:\n if isinstance(cast[key], numpy.ndarray):\n dvector[key] = cast[key].tolist()\n elif isinstance(cast[key], pandas.Series):\n dvector[key] = cast[key].values.tolist()\n else:\n dvector[key] = list(cast[key])\n d = dict(type=cast._type, scalars=dscalar, vectors=dvector,\n coords=cast.coords, zunits=str(cast.zunits), zname=str(cast.zname))\n return d\n\ndef findunit(unitname):\n for name in units.__dict__:\n if str(units.__dict__[name]) == unitname:\n return units.__dict__[name]\n raise NameError(\"'{0}' not recognized as a unit\".format(unitname))\n\ndef dictascast(d, obj):\n \"\"\" Read a file-like stream and construct an object with a Cast-like\n interface. \"\"\"\n d_ = d.copy()\n _ = d_.pop(\"type\")\n coords = d_[\"scalars\"].pop(\"coordinates\")\n zunits = findunit(d_.pop(\"zunits\", \"meter\"))\n zname = d_.pop(\"zname\", \"z\")\n z = d_[\"vectors\"].pop(zname)\n prop = d[\"scalars\"]\n for (key, value) in prop.items():\n if \"date\" in key or \"time\" in key and isinstance(prop[key], str):\n try:\n prop[key] = dateutil.parser.parse(value)\n except (TypeError, ValueError):\n pass\n prop.update(d_[\"vectors\"])\n cast = obj(z, coords=coords, zunits=zunits, zname=zname, **prop)\n return cast\n\ndef dictascastcollection(d, castobj):\n \"\"\" Read a file-like stream and return a list of Cast-like objects.\n \"\"\"\n casts = [dictascast(cast, castobj) for cast in d[\"casts\"]]\n return casts\n\ndef writecast(f, cast, binary=True):\n \"\"\" Write Cast data to a file-like stream. \"\"\"\n d = castasdict(cast)\n if binary:\n s = json.dumps(d, indent=2)\n # f.write(bytes(s, \"utf-8\"))\n f.write(six.b(s))\n else:\n json.dump(d, f, indent=2)\n return\n\ndef writecastcollection(f, cc, binary=True):\n \"\"\" Write CastCollection to a file-like stream. \"\"\"\n casts = [castasdict(cast) for cast in cc]\n d = dict(type=\"castcollection\", casts=casts)\n if binary:\n s = json.dumps(d, indent=2)\n # f.write(bytes(s, \"utf-8\"))\n f.write(six.b(s))\n else:\n json.dump(d, f, indent=2)\n return\n\ndef castcollection_as_geojson(cc):\n castpoints = (Point(c.coords, properties={\"id\":i})\n for i, c in enumerate(cc))\n geojsonstring = geojson.printFeatureCollection(castpoints)\n return geojsonstring\n\n", "sub_path": "narwhal/fileio.py", "file_name": "fileio.py", "file_ext": "py", "file_size_in_byte": 3055, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "datetime.datetime", "line_number": 19, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 24, "usage_type": "attribute"}, {"api_name": "pandas.Series", "line_number": 26, "usage_type": "attribute"}, {"api_name": "dateutil.parser.parser.parse", "line_number": 53, "usage_type": "call"}, {"api_name": "dateutil.parser.parser", "line_number": 53, "usage_type": "attribute"}, {"api_name": "dateutil.parser", "line_number": 53, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 70, "usage_type": "call"}, {"api_name": "six.b", "line_number": 72, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 74, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 82, "usage_type": "call"}, {"api_name": "six.b", "line_number": 84, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 86, "usage_type": "call"}, {"api_name": "karta.Point", "line_number": 90, "usage_type": "call"}, {"api_name": "karta.geojson.printFeatureCollection", "line_number": 92, "usage_type": "call"}, {"api_name": "karta.geojson", "line_number": 92, "usage_type": "name"}]}
+{"seq_id": "172381681", "text": "from django.shortcuts import render\r\n\r\nfrom rest_framework import status\r\nfrom rest_framework.decorators import api_view, permission_classes\r\nfrom rest_framework.permissions import AllowAny\r\nfrom rest_framework.response import Response\r\n#from django.views.decorators.csrf import csrf_exempt\r\n\r\nfrom .models import AnnoteModel\r\n\r\nimport json\r\n\r\n#@csrf_exempt\r\n@api_view(['GET', 'PATCH'])\r\n@permission_classes((AllowAny, ))\r\ndef image_metadata(request):\r\n \"\"\"\r\n Return image metadata.\r\n \"\"\"\r\n if request.method == 'GET':\r\n try:\r\n image_metadata = AnnoteModel.objects.get(pk=1)\r\n return Response(image_metadata.content)\r\n except AnnoteModel.DoesNotExist:\r\n return Response({})\r\n\r\n elif request.method == 'PATCH':\r\n print(type(request.data['content']))\r\n try:\r\n image_metadata = AnnoteModel.objects.get(pk=1)\r\n except AnnoteModel.DoesNotExist:\r\n image_metadata = AnnoteModel()\r\n image_metadata.content = request.data['content']\r\n image_metadata.save()\r\n return Response(image_metadata.content, status=status.HTTP_201_CREATED)\r\n\r\n#@csrf_exempt\r\n@api_view(['POST'])\r\n@permission_classes((AllowAny, ))\r\ndef handle_annotation(request):\r\n #print ('------------ fsdfa: {}'.format(request.body))\r\n if request.method == 'POST':\r\n #print(request.FILES)\r\n dic = json.loads(request.data['annotate'])\r\n print(dic)\r\n for i in dic.keys():\r\n filename = i\r\n count=len(dic[filename]['regions'])\r\n for i in range(count):\r\n i = str(i)\r\n attempt = AnnoteModel()\r\n #attempt.shape = dic[filename]['regions'][i]['shape_attributes']['name']\r\n attempt.width = dic[filename]['regions'][i]['shape_attributes']['width']\r\n attempt.height = dic[filename]['regions'][i]['shape_attributes']['height']\r\n attempt.xcoordinate = dic[filename]['regions'][i]['shape_attributes']['x']\r\n attempt.ycoordinate = dic[filename]['regions'][i]['shape_attributes']['y']\r\n attempt.filename = filename\r\n attempt.image = request.FILES['image']\r\n attempt.attribute=request.POST.get('region')\r\n attempt.garbage = request.POST.get('garbage')\r\n #attempt.attribute = dic[filename]['regions'][i]['region_attributes']['name']\r\n attempt.save()\r\n\r\n #print ('---- JSON DATA ----\\nDATA: {}',dic)\r\n #print(json_data)\r\n\r\n return Response({})\r\n\r\ndef index(request):\r\n return render(request, 'index.html')\r\n\r\ndef SaveAnnotate(request):\r\n return HttpResponse(\":)\")\r\n\r\n# def parseJSON(dic,request):\r\n# for i in dic.keys():\r\n# filename = i\r\n# count=len(dic[filename]['regions'])\r\n# for i in range(count):\r\n# i = str(i)\r\n# attempt = AnnoteModel()\r\n# attempt.shape = dic[filename]['regions'][i]['shape_attributes']['name']\r\n# attempt.width = dic[filename]['regions'][i]['shape_attributes']['width']\r\n# attempt.height = dic[filename]['regions'][i]['shape_attributes']['height']\r\n# attempt.xcoordinate = dic[filename]['regions'][i]['shape_attributes']['x']\r\n# attempt.ycoordinate = dic[filename]['regions'][i]['shape_attributes']['y']\r\n# attempt.filename = filename\r\n# attempt.image = request.data['imagefile']\r\n# attempt.save()\r\n\r\n", "sub_path": "annote/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 3407, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "models.AnnoteModel.objects.get", "line_number": 22, "usage_type": "call"}, {"api_name": "models.AnnoteModel.objects", "line_number": 22, "usage_type": "attribute"}, {"api_name": "models.AnnoteModel", "line_number": 22, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 23, "usage_type": "call"}, {"api_name": "models.AnnoteModel.DoesNotExist", "line_number": 24, "usage_type": "attribute"}, {"api_name": "models.AnnoteModel", "line_number": 24, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 25, "usage_type": "call"}, {"api_name": "models.AnnoteModel.objects.get", "line_number": 30, "usage_type": "call"}, {"api_name": "models.AnnoteModel.objects", "line_number": 30, "usage_type": "attribute"}, {"api_name": "models.AnnoteModel", "line_number": 30, "usage_type": "name"}, {"api_name": "models.AnnoteModel.DoesNotExist", "line_number": 31, "usage_type": "attribute"}, {"api_name": "models.AnnoteModel", "line_number": 31, "usage_type": "name"}, {"api_name": "models.AnnoteModel", "line_number": 32, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 35, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_201_CREATED", "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": 14, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 15, "usage_type": "call"}, {"api_name": "rest_framework.permissions.AllowAny", "line_number": 15, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 44, "usage_type": "call"}, {"api_name": "models.AnnoteModel", "line_number": 51, "usage_type": "call"}, {"api_name": "rest_framework.response.Response", "line_number": 67, "usage_type": "call"}, {"api_name": "rest_framework.decorators.api_view", "line_number": 38, "usage_type": "call"}, {"api_name": "rest_framework.decorators.permission_classes", "line_number": 39, "usage_type": "call"}, {"api_name": "rest_framework.permissions.AllowAny", "line_number": 39, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 70, "usage_type": "call"}]}
+{"seq_id": "559718345", "text": "'''\nThis file does the GUI stuff, and syncxml.py does the work.\nI don't have a full rig set up for 'compiling' PyQt and Anki, so I only debug some non-GUI behavior,\nby using local_launch instead. For debugging within Anki itself, try Ctrl+Shift+; as shown here:\nhttp://ankisrs.net/docs/addons.html#debugging \n\n@author: Jonathan Coombs, copyright sil.org 2012-2014\n'''\n\n# Force Python 3 syntax\nfrom __future__ import print_function, absolute_import, division , unicode_literals\nimport os\nimport shutil\n\nfrom . import logg as L\nfrom . import syncxml as SX\nfrom . import anki_util as A\nfrom . import xml_util as X\nfrom . import flex_util as F\n\n# 'Constants'\nCFGMSG = \"Sync from XML is not yet configured. You can do so from the Tools menu, or by manually creating a custom config file.\\n\"\nIMPMSG = \"Please do NOT use Import for data you wish to sync. Instead, sync from the Tools menu.\\n\"\nTEST_PATH = \"C:\\\\Users\\\\user57\\\\Documents\\\\dict4anki 2\\\\cgg.lift\" # what to use for testing if nothing else is found\nTEST_FWDATA = \"\" # making this non-empty makes the non-UI test run answer Yes and pick this as the FLEx project\n\nif A.IN_ANKI:\n from aqt import mw\n from aqt.qt import *\n from aqt.utils import showInfo, askUserDialog, getFile\n from anki.notes import Note\n # from anki.utils import isMac #obsolete now, I think\n # from PyQt4.QtGui import QMessageBox #done for us already?\n QUESTION = QMessageBox.Question\n CRITICAL = QMessageBox.Critical\nelse:\n # crash-prevention dummies\n QUESTION = 0\n CRITICAL = 0\n\ndef msgbox(m):\n text = '{}: \\n\\n{}'.format(SX.ADDON_NAME2, m)\n L.debug(\"\\n_____ Messagebox _____\\n\" + text + \"\\n----------\")\n if A.IN_ANKI:\n no_hourglass()\n showInfo(text)\n\ndef dialogbox(text, buttons, icon=4, log=True):\n if log:\n L.debug(\"\\n_____ Dialog _____\\n\" + text + \"\\n----------\")\n if A.IN_ANKI: \n no_hourglass()\n b = askUserDialog(text, buttons)\n if icon: b.setIcon(icon)\n x = b.run()\n else:\n x = buttons[0] # first button is default when testing\n return x\n\ndef hourglass():\n if A.IN_ANKI:\n mw.app.setOverrideCursor(QCursor(Qt.WaitCursor)) # display an hourglass cursor\ndef no_hourglass():\n if A.IN_ANKI:\n mw.app.restoreOverrideCursor()\n \n\ndef try_sync(cfpath=SX.CONFIG_FILE):\n L.debug('Preparing to launch sync...')\n L.debug(\"Using config file: {}\".format(cfpath))\n mm = ''\n if A.IN_ANKI:\n L.debug('===== Launching sync from within Anki... =====')\n hourglass()\n mm = SX.sync(cfpath)\n else:\n L.debug('===== Launching sync locally... =====')\n (all_src_records, num_src) = SX.sync(cfpath)\n e = L.error_count()\n w = L.warn_count()\n mm = 'errors: {}; warnings: {}'.format(e, w)\n mm += '\\nDone reading from source file ({} records). That is all we can do for now (cannot access Anki from here), so quitting here.'.format(num_src)\n\n msgbox(mm)\n # TODO: Prompt to auto-delete now-superfluous records. Check...\n # mmm = \"\"\"The target deck in Anki ({}) has existing data and/or media files in it. Delete or leave these?\"\"\"\n # x = dialogbox(mmm, ['Yes', 'No', 'Cancel'], QUESTION)\n # if (x == 'Cancel'): return\n\n\ndef on_sync_clicked():\n if A.IN_ANKI: A.anki_user_profile = mw.pm.profileFolder() \n L.init(SX.LOG_FP, L.VERBOSITY)\n try:\n cfpath = SX.get_config_path() \n if not os.path.exists(cfpath):\n # must create config before syncing\n L.w(\"Can't sync yet. Launching wizard to create the necessary config file: {}\".format(cfpath))\n if wizard():\n try_sync()\n else:\n # A standard config file already exists. Sync.\n try_sync()\n finally:\n no_hourglass()\n launch_paths_maybe()\n # L.close_file() # Otherwise, you can't read the log until you've close Anki's error window.\n \n \ndef on_reconfigure_clicked():\n A.anki_user_profile = mw.pm.profileFolder() \n L.init(SX.LOG_FP, L.VERBOSITY)\n try:\n if reconfigure():\n try_sync()\n else:\n L.w(\"Reconfiguration cancelled.\")\n # msgbox(\"Reconfiguration cancelled.\", close_log=True);\n finally:\n no_hourglass()\n launch_paths_maybe()\n # L.close_file()\n\ndef reconfigure(target=\"\"):\n \"\"\"Tries to reconfigure. Returns True if a sync should follow immediately.\"\"\"\n L.debug('Preparing to reconfigure...')\n cfmainpath = SX.get_config_path()\n cfnewpath = SX.rename_config_to()\n if cfnewpath:\n msg = \"Your existing configuration will be renamed to {}; Continue?\".format(cfnewpath)\n x = dialogbox(msg, ['Ok', 'Cancel'], CRITICAL)\n if (x == 'Cancel'): \n return False\n os.rename(cfmainpath, cfnewpath)\n result = wizard(target)\n return result\n\ndef ensure_models(models):\n \"\"\"If we're in Anki and the given models (i.e. note types) don't all exist,\n create them by importing the sample APKG file, then deleting all\n records in the resulting deck. \n ASSUMPTION: the sample APKG contains all needed models.\n WARNING: this could blow away user data in one unlikely scenario: user creates a lift_dictionary deck\n manually, or imports the APKG, and then manually enters data.\"\"\"\n def all_models_ok(ms):\n for m in ms:\n if (not A.anki_model_exists(m)):\n L.w(\"Target data model '{}' does not yet exist. Will attempt to get it by importing the default APKG file.\".format(m))\n return False\n return True\n \n if A.IN_ANKI:\n if not all_models_ok(models):\n no_hourglass()\n try:\n # Import the APKG.\n fp = A.get_filepath(A.APKG_PATH)\n delete_failure = A.import_apkg_model(fp, True)\n L.w(\"Done importing APKG file.\")\n mw.col.models.flush()\n mw.reset(True)\n mw.reset()\n if delete_failure:\n L.warn(delete_failure) # not a big deal\n msgbox(delete_failure)\n else:\n L.w(\"Successfully deleted existing records.\")\n except Exception as e:\n # We were unable to automatically import the APKG\n L.error(e)\n L.warn(A.NO_MODEL_MSG)\n msgbox(A.NO_MODEL_MSG + \"\\nError message: {}\".format(e))\n return False\n return all_models_ok(models) # verify\n return True\n\n\ndef wizard(target=\"\"):\n \"\"\"Assumption: The main config file does not exist. Auto-configure. \n Returns True if successful and ready to sync.\n target: this parameter is for testing; it overrides the logic for finding a LIFT file.\"\"\"\n L.debug('Launching the auto-config wizard')\n\n cfmainpath = SX.get_config_path()\n cfdefpath = SX.get_config_path(SX.CONFIG_DEFAULT_FILE)\n\n if not os.path.exists(cfdefpath): # if no default config exists either...\n msg = \"Cannot find and copy the default config file:\\n {}\\nCannot continue.\".format(cfdefpath)\n x = dialogbox(msg, ['ok'], CRITICAL)\n return False\n \n src_dir = SX.get_home_dir_plus(os.path.join(SX.get_docs_dir_name(), SX.SRC_DIR_LIFT), False) # use True if creating dict4anki\n\n flex_dir = F.flex_dir()\n flex_msg = ''\n if flex_dir:\n flex_msg = \" For quickest setup, give it the same name as one of the projects here:\\n {}\\n\".format(flex_dir)\n\n \n msg = \"Would you like to bring in your own* LIFT data? If so, either...\\n\" \\\n \"A) FLEx users, export a LIFT file here (or to a direct subfolder of it):\\n\" \\\n \" {} \\n{}\" \\\n \"B) WeSay (or FLEx) users can just click LIFT and choose a LIFT file.\\n\\n\" \\\n \"A copy of the default configuration file will be auto-configured for you,\\n\" \\\n \" which may take a few seconds. After configuration, the LIFT file to be synced\\n\" \\\n \" must always be located in that same place.\\n\\n\" \\\n \"Or, click Sample to sync from the sample file instead.\\n\\n\" \\\n \"*Audio will only be auto-detected if your main writing systems are 2- or 3-letter codes.\"\n msg = msg.format(src_dir, flex_msg)\n # L.debug(\"Dialog: {}\\n\".format(msg))\n x = dialogbox(msg, ['LIFT', 'Sample', 'Cancel'], QUESTION)\n if (x == 'Cancel'): return False\n\n hourglass()\n \n # Make sure Anki has the default deck and models already there; else import the APKG file.\n if not ensure_models([X.MODEL1, X.MODEL2]):\n return False\n if (x == 'Sample'):\n # TODO idea: preprocess = (('vern', 'klw'),('other', 'id')) , hard-coding here.\n # After that, the default config file wouldn't need to be hard-coded to specific languages anymore.\n # Note that klw should cover klw-Zxxx-x-audio too, etc.\n try:\n msg = SX.sync(SX.CONFIG_DEFAULT_FILE) # , preprocess)\n msgbox(msg)\n # launch_paths_maybe()\n return False\n except:\n # launch_paths(suppressExceptions=True)\n raise\n finally: \n no_hourglass()\n\n hourglass()\n\n # prepare to copy default config to make a new config (via a temp file first)\n shutil.copy(cfdefpath, cfmainpath + '.tmp') # will overwrite silently if need be\n \n lift = '' # was: lift = SX.get_first_lift_file(src_dir) # check the dict4anki folder\n if not lift: # fall back to anything in a direct subfolder of Documents\\WeSay (Linux: ~/WeSay)\n tmp = SX.get_home_dir_plus(os.path.join(SX.get_docs_dir_name(), SX.SRC_DIR_WESAY))\n lift = SX.get_first_lift_file(tmp)\n if not lift: # fall back to anything in a direct subfolder of Documents (Windows: %USERPROFILE%\\My Documents; Linux: ~/)\n # src_dir = os.path.split(src_dir)[0] # remove \"/dict4anki/\"\n lift = SX.get_first_lift_file(SX.get_home_dir_plus(SX.get_docs_dir_name()))\n if lift:\n src_dir = os.path.split(lift)[0]\n if A.IN_ANKI:\n no_hourglass()\n # pop up a File Open dialog using ankilib's convenience method\n lift = getFile(mw, \"Open LIFT file\", None, filter=\"*.lift\", dir=src_dir, key=\"\") # \"*.lift\"\n L.debug(\"User chose this LIFT file: {}\".format(lift))\n elif (not lift) and os.path.exists(TEST_PATH): \n lift = TEST_PATH # hard-coded test\n if target:\n lift = target # for testing, a passed parameter overrides all of the above\n\n L.debug(\"Using this LIFT file: {}\".format(lift))\n if not lift: \n # Still no LIFT file. Fail.\n msg = \"No file chosen. Auto-configuration cancelled for now.\" \n x = dialogbox(msg, ['ok'], CRITICAL)\n return False\n \n m = \"LIFT file: \\n {}\\n\".format(lift)\n flex_audio, flex_image = None, None\n\n # Check for WeSay. E.g. if Catalan.lift has a Catalan.WeSayConfig next to it, assume it's a WeSay project\n # Would it be better to make sure it's in the official WeSay directory?\n p, f = os.path.split(lift)\n f = os.path.splitext(f)[0]\n is_wesay = os.path.exists(os.path.join (p, f + \".WeSayConfig\")) \n\n if (not is_wesay) and flex_dir:\n L.debug(\"Checking for projects in this flex_dir: {}\".format(flex_dir))\n tmp = F.flex_media(lift, flex_dir)\n L.debug(\"Found tmp: {}\".format(tmp))\n if tmp: \n flex_audio, flex_image = tmp\n\n if flex_audio:\n msg = \"{}Also found a FLEx project with the same name as your LIFT file and it probably has these media folders:\\n\" \\\n \" {}\\n {}\\n\" \\\n \"Shall we sync media files directly from there, so that before each \\n\" \\\n \"sync the only thing you'll have to export from FLEx will be the LIFT data?\\n\" \\\n \"(If No, the 'audio' and 'pictures' folders in the LIFT file's location will be used.)\".format(m, flex_audio, flex_image)\n answer = dialogbox(msg, ['Yes', 'No'], QUESTION)\n if not A.IN_ANKI:\n # answer = 'No' #Or, put the No button first, then delete this\n pass\n if answer != 'Yes':\n flex_audio, flex_image = None, None # dump them\n elif not is_wesay:\n msg = \"{}Could not find a FLEx project with the same name as your LIFT file.\\n\" \\\n \"Do you wish to select a FLEx project that does/will contain your media files? \\n\" \\\n \"WeSay users: choose No. FLEx users: choose Yes unless you want to export \\n\" \\\n \" the media files along with the LIFT before each sync.\".format(m)\n answer = dialogbox(msg, ['Yes', 'No', 'Cancel'], QUESTION)\n if (answer == 'Cancel'): return False\n fwdata = TEST_FWDATA\n if (answer == 'Yes') and (A.IN_ANKI):\n # pop up a File Open dialog using ankilib's convenience method\n fwdata = getFile(mw, \"Select FLEx project\", None, filter=\"*.fwdata\", key=\"\", dir=flex_dir)\n if fwdata:\n tmp = F.flex_media(fwdata)\n if tmp: flex_audio, flex_image = tmp\n \n # Note: working with a temp copy of config, so as to not create an official config until we're sure we've succeeded.\n try: \n xset = X.XmlSettings(cfmainpath + '.tmp', lift, flex_audio, flex_image)\n except:\n launch_paths(suppressExceptions=True)\n raise\n\n if os.path.getsize(lift) > 1000000:\n msg = m + \"Your file is large, so analyzing it may take a while. Please click Ok and then wait.\"\n answer = dialogbox(msg, ['Ok', 'Cancel'], QUESTION)\n if answer == 'Cancel' : return\n\n # status bar (no longer supported by Anki?)\n# from aqt.main import setStatus as set_status\n# mw.setStatus(\"Analyzing the LIFT file...\", timeout=3000) \n\n # Find and Replace WS's in the new config file\n hourglass()\n to_replace = xset.find_vern_nat()\n L.w(\"For LIFT file\\n ({}) we will now find/replace writing systems in our settings as follows: \\n{}\".format(lift, X.lang_table(to_replace)))\n\n # Using regex (on cfmainpath + '.tmp') to replace WSes in our new config file ...\n xset.save() \n tmp = xset.file_path\n X.replace_all(tmp, to_replace)\n xset = None # since it is now outdated \n # TODO: xset.dispose() # this would help with safety if implemented\n\n # do a dry run: use the new config file to load the LIFT file...\n try:\n xset = X.XmlSettings(tmp, lift, flex_audio, flex_image) # we need those last two parameters or we'll lose any FLEx path we had\n except:\n launch_paths(suppressExceptions=True)\n raise\n \n xdl = X.XmlDataLoader() # No try block, since presumably the user knows where the data file is.\n _recs, empties = xdl.load_src_file(xset.get_attr(), xset.entry, sync_media=False, dry_run=True)\n _recs, empties2 = xdl.load_src_file(xset.get_attr(), xset.example, sync_media=False, dry_run=True)\n # empties.append(empties2)\n\n # ... so we can disable any xpaths that don't match any data.\n if empties:\n L.w(\"The following entry fields yielded no data and will now be disabled so as to not generate warnings: {}\".format(empties))\n xset.entry.disable_fields(empties)\n if empties2:\n L.w(\"The following example fields yielded no data and will now be disabled so as to not generate warnings: {}\".format(empties))\n xset.example.disable_fields(empties2)\n\n # If no example sentences, we already disabled auto-disabled that section.\n if xset.example.get_attr()['enabled'] == 'true':\n # It's still enabled, which means it has data. \n msg = m + \"Found dictionary Examples containing data; when imported, each will show up on the main entry's flashcard.\\n\" \\\n \"Will you also need a separate flashcard for each Example?\"\n x = dialogbox(msg, ['No', 'Yes', 'Cancel'], QUESTION)\n if (x == \"Cancel\"):\n return False\n if (x != 'Yes'): \n xset.example.disable()\n\n hourglass()\n xset.save()\n\n # rename the default config file (remove the .tmp)\n shutil.move(cfmainpath + '.tmp', cfmainpath) # will overwrite silently if need be, but see our initial assumption\n L.debug(\"Configuration file saved.\")\n m2 = \"\\nReplaced writing systems in our new configuration as follows: \\n{}\".format(X.lang_table(to_replace))\n m3, m5 = '', ''\n if flex_audio:\n m3 = \"\\nConfigured to copy media files from these locations: \\n {}\\n {}\\n\".format(flex_audio, flex_image)\n m4 = \"\\nConfiguration file saved. Click Yes to sync now, or No if you wish to review/tweak the configuration first.\\n\"\n if L.error_count() or L.warn_count():\n m5 = \"\\nThere were errors or warnings during auto-config. Please review the log.\"\n msg = m + m2 + m3 + m4 + m5\n # TODO: \" or want to run a Sync Preview.\"\n L.w(msg)\n # msgbox(msg)\n x = dialogbox(msg, ['Yes', 'No'], QUESTION)\n if (x == 'No'): \n return False # successful config, but don't sync right now\n return True\n \ndef launch_paths(suppressExceptions=False):\n \"\"\" Open the addon folder (ignoring any errors), \n and open the log file (not ignoring errors, unless suppress).\n Typically called when there's a problem, to show the user where to go fix it.\n \"\"\"\n\n tmp = os.path.abspath(os.curdir)\n folder = os.path.split(SX.LOG_FP)[0]\n try:\n launch_file(folder) # Launch the folder containing the log file\n except: \n pass # ignore\n \n try:\n L.close_file()\n launch_file(SX.LOG_FP) # Launch the log file (e.g. in Notepad)\n except:\n if not suppress:\n raise\n \ndef launch_paths_maybe():\n \"\"\" If there are errors/warnings, open the addon folder and the log file. \"\"\"\n if L.error_count() or L.warn_count():\n launch_paths()\n else:\n L.close_file()\n\ndef launch_file(filepath):\n \"\"\"See: http://stackoverflow.com/questions/434597/open-document-with-default-application-in-python\n Also note this alternative. Quote:\n I tried this code and it worked fine in Windows 7 and Ubuntu Natty:\n import webbrowser\n webbrowser.open(\"path_to_file\")\n \"\"\"\n if SX.WINDOWS:\n os.startfile(filepath)\n elif SX.MAC:\n import subprocess\n subprocess.call(('open', filepath))\n elif SX.LINUX:\n import subprocess\n subprocess.call(('xdg-open', filepath)) \n\nif A.IN_ANKI:\n mw.form.menuTools.addSeparator()\n # create a new menu item in Anki\n action = QAction(SX.ADDON_NAME, mw)\n # set it to call our function when it's clicked\n mw.connect(action, SIGNAL(\"triggered()\"), on_sync_clicked)\n # and add it to the tools menu\n mw.form.menuTools.addAction(action)\n \n action = QAction('(re)configure ' + SX.ADDON_SHORT_NAME, mw)\n mw.connect(action, SIGNAL(\"triggered()\"), on_reconfigure_clicked)\n mw.form.menuTools.addAction(action)\n\ncpath = SX.get_config_path()\nif A.IN_ANKI and (not os.path.exists(cpath)):\n showInfo(CFGMSG + \"\\n\" + IMPMSG)\n\n# TODO: have the config file indicate whether to sync automatically whenever Anki starts (e.g. for WeSay)\n# But, there's a problem: mw.col is None at this point in Anki's loading process, so we \n# need a different way to get the collection object if we have to get it NOW. \n", "sub_path": "syncxml/SyncFromXML.py", "file_name": "SyncFromXML.py", "file_ext": "py", "file_size_in_byte": 19166, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "aqt.utils.showInfo", "line_number": 46, "usage_type": "call"}, {"api_name": "aqt.utils.askUserDialog", "line_number": 53, "usage_type": "call"}, {"api_name": "aqt.mw.app.setOverrideCursor", "line_number": 62, "usage_type": "call"}, {"api_name": "aqt.mw.app", "line_number": 62, "usage_type": "attribute"}, {"api_name": "aqt.mw", "line_number": 62, "usage_type": "name"}, {"api_name": "aqt.mw.app.restoreOverrideCursor", "line_number": 65, "usage_type": "call"}, {"api_name": "aqt.mw.app", "line_number": 65, "usage_type": "attribute"}, {"api_name": "aqt.mw", "line_number": 65, "usage_type": "name"}, {"api_name": "aqt.mw.pm.profileFolder", "line_number": 92, "usage_type": "call"}, {"api_name": "aqt.mw.pm", "line_number": 92, "usage_type": "attribute"}, {"api_name": "aqt.mw", "line_number": 92, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 96, "usage_type": "call"}, {"api_name": "os.path", "line_number": 96, "usage_type": "attribute"}, {"api_name": "aqt.mw.pm.profileFolder", "line_number": 111, "usage_type": "call"}, {"api_name": "aqt.mw.pm", "line_number": 111, "usage_type": "attribute"}, {"api_name": "aqt.mw", "line_number": 111, "usage_type": "name"}, {"api_name": "os.rename", "line_number": 134, "usage_type": "call"}, {"api_name": "aqt.mw.col.models.flush", "line_number": 160, "usage_type": "call"}, {"api_name": "aqt.mw.col", "line_number": 160, "usage_type": "attribute"}, {"api_name": "aqt.mw", "line_number": 160, "usage_type": "name"}, {"api_name": "aqt.mw.reset", "line_number": 161, "usage_type": "call"}, {"api_name": "aqt.mw", "line_number": 161, "usage_type": "name"}, {"api_name": "aqt.mw.reset", "line_number": 162, "usage_type": "call"}, {"api_name": "aqt.mw", "line_number": 162, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 187, "usage_type": "call"}, {"api_name": "os.path", "line_number": 187, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 192, "usage_type": "call"}, {"api_name": "os.path", "line_number": 192, "usage_type": "attribute"}, {"api_name": "shutil.copy", "line_number": 237, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 241, "usage_type": "call"}, {"api_name": "os.path", "line_number": 241, "usage_type": "attribute"}, {"api_name": "os.path.split", "line_number": 247, "usage_type": "call"}, {"api_name": "os.path", "line_number": 247, "usage_type": "attribute"}, {"api_name": "aqt.utils.getFile", "line_number": 251, "usage_type": "call"}, {"api_name": "aqt.mw", "line_number": 251, "usage_type": "argument"}, {"api_name": "os.path.exists", "line_number": 253, "usage_type": "call"}, {"api_name": "os.path", "line_number": 253, "usage_type": "attribute"}, {"api_name": "os.path.split", "line_number": 270, "usage_type": "call"}, {"api_name": "os.path", "line_number": 270, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 271, "usage_type": "call"}, {"api_name": "os.path", "line_number": 271, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 272, "usage_type": "call"}, {"api_name": "os.path", "line_number": 272, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 272, "usage_type": "call"}, {"api_name": "aqt.utils.getFile", "line_number": 303, "usage_type": "call"}, {"api_name": "aqt.mw", "line_number": 303, "usage_type": "argument"}, {"api_name": "os.path.getsize", "line_number": 315, "usage_type": "call"}, {"api_name": "os.path", "line_number": 315, "usage_type": "attribute"}, {"api_name": "shutil.move", "line_number": 371, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 395, "usage_type": "call"}, {"api_name": "os.path", "line_number": 395, "usage_type": "attribute"}, {"api_name": "os.curdir", "line_number": 395, "usage_type": "attribute"}, {"api_name": "os.path.split", "line_number": 396, "usage_type": "call"}, {"api_name": "os.path", "line_number": 396, "usage_type": "attribute"}, {"api_name": "os.startfile", "line_number": 424, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 427, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 430, "usage_type": "call"}, {"api_name": "aqt.mw.form.menuTools.addSeparator", "line_number": 433, "usage_type": "call"}, {"api_name": "aqt.mw.form", "line_number": 433, "usage_type": "attribute"}, {"api_name": "aqt.mw", "line_number": 433, "usage_type": "name"}, {"api_name": "aqt.mw", "line_number": 435, "usage_type": "argument"}, {"api_name": "aqt.mw.connect", "line_number": 437, "usage_type": "call"}, {"api_name": "aqt.mw", "line_number": 437, "usage_type": "name"}, {"api_name": "aqt.mw.form.menuTools.addAction", "line_number": 439, "usage_type": "call"}, {"api_name": "aqt.mw.form", "line_number": 439, "usage_type": "attribute"}, {"api_name": "aqt.mw", "line_number": 439, "usage_type": "name"}, {"api_name": "aqt.mw", "line_number": 441, "usage_type": "argument"}, {"api_name": "aqt.mw.connect", "line_number": 442, "usage_type": "call"}, {"api_name": "aqt.mw", "line_number": 442, "usage_type": "name"}, {"api_name": "aqt.mw.form.menuTools.addAction", "line_number": 443, "usage_type": "call"}, {"api_name": "aqt.mw.form", "line_number": 443, "usage_type": "attribute"}, {"api_name": "aqt.mw", "line_number": 443, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 446, "usage_type": "call"}, {"api_name": "os.path", "line_number": 446, "usage_type": "attribute"}, {"api_name": "aqt.utils.showInfo", "line_number": 447, "usage_type": "call"}]}
+{"seq_id": "363664983", "text": "# Magic statements.\n\nimport warnings\nwarnings.filterwarnings('ignore')\nwarnings.simplefilter('ignore')\n\nfrom pprint import pprint\nimport time\n\n# Import graph libraries.\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MultipleLocator, AutoMinorLocator\n\n# Import main modules, packages, and third party libraries.\nimport numpy as np; from numpy import nan\nimport pandas as pd\nimport seaborn as sns; sns.set()\n\n# Import scikit-learn classes: datasets.\nfrom sklearn.datasets import fetch_20newsgroups\nfrom sklearn.datasets import load_digits\nfrom sklearn.datasets import load_iris\n\n# Import scikit-learn classes: preprocessing step utility functions.\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.decomposition import PCA # Unsupervised Machine Learning tasks: feature reduction, dimensionality reduction\nfrom sklearn.mixture import GaussianMixture # Unsupervised Machine Learning tasks: clustering\nfrom sklearn.manifold import Isomap # Unsupervised Machine Learning tasks: feature reduction, dimensionality reduction\n\n# Import scikit-learn classes: models (Estimators).\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.linear_model import Ridge\n\n# Import scikit-learn classes: preprocessing.\nfrom sklearn.preprocessing import PolynomialFeatures\n# from sklearn.preprocessing import Imputer\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.utils import shuffle\n\nfrom sklearn.neighbors import KNeighborsClassifier\n\n# Import scikit-learn classes: Hyperparameters Validation utility functions.\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import LeavePOut\nfrom sklearn.model_selection import LeaveOneOut\n\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.model_selection import StratifiedShuffleSplit\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import KFold\n\n# Import scikit-learn classes: model's evaluation step utility functions.\nfrom sklearn.metrics import accuracy_score \nfrom sklearn.metrics import confusion_matrix\n\n\ndef decorator_run_pipeline_cv(\n a_func\n ):\n \n def wrapper_decorator(\n model=None, train=None,\n test=None, random_state=0, cv=None,\n ):\n assert model is not None, 'model is None'\n assert train is not None, 'train is None'\n assert test is not None, 'test is None'\n \n print('[*] Running pipeline...')\n\n a_func(model, train, test, random_state, cv)\n \n print('[*] Pipeline done.')\n pass\n\n return wrapper_decorator\n\n@decorator_run_pipeline_cv\ndef run_pipeline(model, train, test, random_state=0, cv=None):\n \n # Shuffle data used for training.\n Xtrain, ytrain = train.data, train.target\n Xtrain, ytrain = shuffle(Xtrain, ytrain, random_state=random_state)\n\n # Shuffle data used for test phase, if any.\n Xtest, ytest = test.data, test.target\n Xtest, ytest = shuffle(Xtest, ytest, random_state=random_state)\n\n # check whether to perform cv, having provided as input argument\n # passed to this function a quantity representing:\n # - either, number of folds in which training set will be splitted\n # - or, a cross-validation scheme, techique, pattern, represented\n # by means of a Scikit-Learn class object.\n if cv is not None:\n print('[*] CV running...')\n scores = cross_val_score(model, Xtrain, ytrain , cv=cv)\n print(scores)\n print(scores.mean())\n print('[*] CV done.')\n \n # Fit the model to training data\n model.fit(Xtrain, ytrain)\n labels = model.predict(Xtest)\n \n if test is not None:\n mat = confusion_matrix(ytest, labels)\n sns.heatmap(mat.T, square=True,\n annot=True, fmt='d',\n cbar=False,\n xticklabels=train.target_names, yticklabels=train.target_names, )\n plt.xlabel('true label')\n plt.ylabel('predicted label')\n\n print('K-Neighbors Classifier accuracy score:', accuracy_score(ytest, labels))\n print(f\"K-Neighbors Classifier accuracy score (percentage): {accuracy_score(ytest, labels)*100:.2f}%\")\n \n def predict_category(s, train=train, model=model):\n pred = model.predict([s])\n \n return ', '.join([ str(pred), str(train.target_names[pred[0]]) ])\n \n print(predict_category('sending a payload to the ISS'))\n print(predict_category('discussing islam versus atheism'))\n print(predict_category('determinig screen resolution and size'))\n return model\n\ndef decorator_inner_vs_outer_cv(\n a_func\n ):\n def wrapper_decorator(\n estimator,\n Xtrain, ytrain,\n param_grid,\n Xtest, ytest,\n num_trials=30,\n random_state=0,\n n_splits_i=4,\n n_splits_o=4,\n verbose=0,\n ):\n\n assert estimator is not None, 'cls is None'\n assert param_grid is not None, 'param_grid is None'\n\n print('[*] inner_vs_outer_cv running...')\n a_func(\n estimator,\n Xtrain, ytrain,\n param_grid,\n Xtest, ytest,\n test=None,\n num_trials=30,\n random_state=0,\n n_splits_i=n_splits_i,\n n_splits_o=n_splits_o,\n verbose=0\n )\n print('[*] inner_vs_outer_cv done.')\n pass\n return wrapper_decorator\n\n@decorator_inner_vs_outer_cv\ndef inner_vs_outer_cv(\n estimator,\n Xtrain, ytrain,\n param_grid,\n Xtest, ytest,\n test=None,\n num_trials=30,\n random_state=0,\n n_splits_i=4,\n n_splits_o=4,\n verbose=0):\n \n Xtrain, ytrain = shuffle(Xtrain, ytrain, random_state=random_state)\n\n if Xtest is not None and ytest is not None:\n Xtest, ytest = shuffle(Xtest, ytest, random_state=random_state)\n\n # Arrays to store scores\n non_nested_scores = np.zeros(num_trials)\n nested_scores = np.zeros(num_trials)\n \n best_models = list()\n cv_results = list()\n best_params = list()\n\n # Loop for each trial\n for i in range(num_trials):\n # Choose cross-validation techniques for the inner and outer loops,\n # independently of the dataset.\n # E.g \"GroupKFold\", \"LeaveOneOut\", \"LeaveOneGroupOut\", etc.\n inner_cv = StratifiedKFold(n_splits=n_splits_i, random_state=i, shuffle=False) # KFold(n_splits=4, shuffle=True, random_state=i)\n outer_cv = StratifiedKFold(n_splits=n_splits_o, random_state=i, shuffle=False) # KFold(n_splits=4, shuffle=True, random_state=i)\n\n # Non_nested parameter search and scoring\n clf = GridSearchCV(estimator=estimator, param_grid=param_grid, cv=inner_cv)\n clf.fit(Xtrain, ytrain)\n non_nested_scores[i] = clf.best_score_\n \n best_models.append(clf.best_estimator_)\n cv_results.append(clf.cv_results_)\n best_params.append(clf.best_params_)\n\n # Nested CV with parameter optimization\n nested_score = cross_val_score(clf, X=Xtrain, y=ytrain, cv=outer_cv)\n nested_scores[i] = nested_score.mean()\n\n score_difference = non_nested_scores - nested_scores\n\n print(\"Average difference of {:6f} with std. dev. of {:6f}.\"\n .format(score_difference.mean(), score_difference.std()))\n \n \n plot_scores_nested_vs_non_nested(\n non_nested_scores,\n nested_scores,\n score_difference,\n num_trials=num_trials)\n return best_models, cv_results, best_params\n\ndef plot_scores_nested_vs_non_nested(non_nested_scores, nested_scores, score_difference, num_trials):\n # Plot scores on each trial for nested and non-nested CV\n plt.figure()\n plt.subplot(211)\n non_nested_scores_line, = plt.plot(non_nested_scores, color='r')\n nested_line, = plt.plot(nested_scores, color='b')\n plt.ylabel(\"score\", fontsize=\"14\")\n plt.legend([non_nested_scores_line, nested_line],\n [\"Non-Nested CV\", \"Nested CV\"],\n bbox_to_anchor=(0, .4, .5, 0))\n plt.title(\"Non-Nested and Nested Cross Validation on Iris Dataset\",\n x=.5, y=1.1, fontsize=\"15\")\n\n # Plot bar chart of the difference.\n plt.subplot(212)\n difference_plot = plt.bar(range(num_trials), score_difference)\n plt.xlabel(\"Individual Trial #\")\n plt.legend([difference_plot],\n [\"Non-Nested CV - Nested CV Score\"],\n bbox_to_anchor=(0, 1, .8, 0))\n plt.ylabel(\"score difference\", fontsize=\"14\")\n\n plt.show()\n pass\n\ndef plot_cm(ytest, y_model):\n mat = confusion_matrix(ytest, y_model)\n\n sns.heatmap(mat, square=True, annot=True, cbar=False)\n plt.xlabel('predicted value')\n plt.ylabel('true value')\n plt.show()\n pass\n ", "sub_path": "Python_Data_Science_Handbook/chapter_5/Pittsburgh_Bridges_Dataset/utils/grid_search_cv_utils.py", "file_name": "grid_search_cv_utils.py", "file_ext": "py", "file_size_in_byte": 8780, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "warnings.filterwarnings", "line_number": 4, "usage_type": "call"}, {"api_name": "warnings.simplefilter", "line_number": 5, "usage_type": "call"}, {"api_name": "seaborn.set", "line_number": 17, "usage_type": "call"}, {"api_name": "sklearn.utils.shuffle", "line_number": 87, "usage_type": "call"}, {"api_name": "sklearn.utils.shuffle", "line_number": 91, "usage_type": "call"}, {"api_name": "sklearn.model_selection.cross_val_score", "line_number": 100, "usage_type": "call"}, {"api_name": "sklearn.metrics.confusion_matrix", "line_number": 110, "usage_type": "call"}, {"api_name": "seaborn.heatmap", "line_number": 111, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 115, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 115, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 116, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 116, "usage_type": "name"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 118, "usage_type": "call"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 119, "usage_type": "call"}, {"api_name": "sklearn.utils.shuffle", "line_number": 179, "usage_type": "call"}, {"api_name": "sklearn.utils.shuffle", "line_number": 182, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 185, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 186, "usage_type": "call"}, {"api_name": "sklearn.model_selection.StratifiedKFold", "line_number": 197, "usage_type": "call"}, {"api_name": "sklearn.model_selection.StratifiedKFold", "line_number": 198, "usage_type": "call"}, {"api_name": "sklearn.model_selection.GridSearchCV", "line_number": 201, "usage_type": "call"}, {"api_name": "sklearn.model_selection.cross_val_score", "line_number": 210, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 228, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 228, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 229, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 229, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 230, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 230, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 231, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 231, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 232, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 232, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 233, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 233, "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.subplot", "line_number": 240, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 240, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 241, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 241, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 242, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 242, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 243, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 243, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 246, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 246, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 248, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 248, "usage_type": "name"}, {"api_name": "sklearn.metrics.confusion_matrix", "line_number": 252, "usage_type": "call"}, {"api_name": "seaborn.heatmap", "line_number": 254, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 255, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 255, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 256, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 256, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 257, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 257, "usage_type": "name"}]}
+{"seq_id": "28338040", "text": "'''\r\nface++ 眼镜定位, 镜框贴图 , 多图\r\n'''\r\nfrom __future__ import division\r\n\r\nimport requests\r\nfrom json import JSONDecoder\r\nimport cv2\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nfrom PIL import Image\r\nfrom scipy import misc\r\nimport os\r\nfrom Dir_make import mk_dir\r\nimport time\r\nimport math\r\n\r\n# 初始化\r\n# 原始镜框信息\r\nglass_filepath = 'D:/Anaconda3/Lib/site-packages/facenet/glass.png'\r\n# 原始镜框定位点\r\n# 定位点\r\nglass_left = {'x': 80, 'y': 43}\r\nglass_right = {'x': 220, 'y': 43}\r\n# 眼镜对应间距\r\nglass_point_distance = glass_right['x'] - glass_left['x']\r\n\r\n\r\ndef faceplusplus_face_detect_api_s(filepath, class_name):\r\n num_images = len(filepath)\r\n glass_point_store_list = []\r\n face_glass_path_list = []\r\n for i in range(num_images):\r\n # 图片路径\r\n # filepath = \"D:/Anaconda3/Lib/site-packages/facenet/data/test_image/1.png\"\r\n\r\n # 原图显示\r\n clean_img = cv2.imread(filepath[i])\r\n # cv2.imshow('clean_image', clean_img)\r\n # cv2.waitKey(1)\r\n\r\n # 人眼检测\r\n left_eye_center, right_eye_center, angle = eye_detect(filepath[i])\r\n if str(left_eye_center) == 'False':\r\n continue\r\n else:\r\n print(str(left_eye_center))\r\n print(str(right_eye_center))\r\n '''\r\n # 标注瞳孔\r\n point_img_left_eye = cv2.circle(clean_img, (left_eye_center['x'], left_eye_center['y']), 2, (0, 0, 255),\r\n -1) # circle(图像,圆心,半径,颜色,填充)\r\n point_img = cv2.circle(point_img_left_eye, (right_eye_center['x'], right_eye_center['y']), 2, (0, 0, 255), -1)\r\n\r\n cv2.imshow('point_image', point_img)\r\n cv2.imwrite('point_image.png', point_img)\r\n cv2.waitKey(1)\r\n '''\r\n # 缩放比例计算,新镜框定位点\r\n new_glass_left, new_glass_right = scale(left_eye_center, right_eye_center)\r\n\r\n # 贴图, 并获取镜框坐标\r\n store_point, face = wear_glass_1(filepath[i], new_glass_left, left_eye_center, angle)\r\n\r\n glass_point_store_list.append(store_point)\r\n # 数组转化为Image类\r\n face_glass = Image.fromarray(face)\r\n\r\n # 保存路径生成\r\n\r\n pre_dir = 'D:/Anaconda3/Lib/site-packages/facenet/data/face_glass_image/'\r\n mk_dir(pre_dir + class_name[i])\r\n\r\n start_index = filepath[i].find(class_name[i] + '_')\r\n\r\n face_glass_path = 'D:/Anaconda3/Lib/site-packages/facenet/data/face_glass_image/' + class_name[i] + '/' + class_name[i] + filepath[i][start_index: -4] + '_glass.png'\r\n print(face_glass_path)\r\n face_glass_path_list.append(face_glass_path)\r\n face_glass.save(face_glass_path, 'png')\r\n\r\n return glass_point_store_list, face_glass_path, pre_dir\r\n\r\n\r\ndef eye_detect(filepath):\r\n '''\r\n 调用Face++ 人眼定位\r\n '''\r\n\r\n http_url = \"https://api-cn.faceplusplus.com/facepp/v3/detect\"\r\n key = \"dHTpFppve9bV3ZqkvJadC74fQql3paRp\"\r\n secret = \"19R5whMXkjXyFCPEivqHPCrelkxfxByi\"\r\n\r\n data = {\"api_key\": key, \"api_secret\": secret, \"return_landmark\": \"1\"}\r\n files = {\"image_file\": open(filepath, \"rb\")}\r\n # print(files)\r\n response = requests.post(http_url, data=data, files=files)\r\n\r\n req_con = response.content.decode('utf-8')\r\n req_dict = JSONDecoder().decode(req_con)\r\n\r\n #print(req_dict)\r\n # print(req_dict['faces'])\r\n #print(req_dict['faces'][0])\r\n #print(req_dict['faces'][0]['landmark'])\r\n\r\n '''\r\n # API调用失败策略\r\n if 'faces' not in req_dict:\r\n landmark_inf = False\r\n left_eye_center = False\r\n right_eye_center = False\r\n angle = False\r\n return left_eye_center, right_eye_center, angle\r\n else:\r\n landmark_inf = req_dict['faces'][0]['landmark']\r\n left_eye_center = landmark_inf['left_eye_center']\r\n right_eye_center = landmark_inf['right_eye_center']\r\n #print('%s: %s' % ('left_eye_center', str(left_eye_center)))\r\n #print('%s: %s' % ('right_eye_center', str(right_eye_center)))\r\n '''\r\n # 远程调用防中断\r\n while 'faces' not in req_dict:\r\n response = requests.post(http_url, data=data, files=files)\r\n\r\n req_con = response.content.decode('utf-8')\r\n req_dict = JSONDecoder().decode(req_con)\r\n\r\n landmark_inf = req_dict['faces'][0]['landmark']\r\n left_eye_center = landmark_inf['left_eye_center']\r\n right_eye_center = landmark_inf['right_eye_center']\r\n\r\n # 求倾斜角度\r\n delta_x = left_eye_center['x'] - right_eye_center['x']\r\n delta_y = left_eye_center['y'] - right_eye_center['y']\r\n tan_ = delta_y / delta_x\r\n print('%s: %f' % ('tan', tan_))\r\n angle = math.atan(tan_)\r\n\r\n return left_eye_center, right_eye_center, angle\r\n\r\n\r\ndef scale(left_eye_center, right_eye_center):\r\n '''\r\n 获取缩放后的镜框定位点\r\n\r\n :param left_eye_center:\r\n :param right_eye_center:\r\n :param glass_point_distance:\r\n :return:\r\n '''\r\n # 瞳孔间距\r\n real_eye_distance = right_eye_center['x'] - left_eye_center['x']\r\n # 放缩比例\r\n k = real_eye_distance / glass_point_distance\r\n print('%s: %f' % ('k', k))\r\n\r\n # 镜框缩放\r\n glass = Image.open(glass_filepath)\r\n w, h = glass.size\r\n # glass_new = misc.imresize(glass, k)\r\n glass.thumbnail((int(w * h), int(h * k)))\r\n glass.save('glass_new.png', 'png')\r\n\r\n # 新镜框定位点\r\n new_glass_left = {}\r\n new_glass_right = {}\r\n\r\n # 定位点缩放\r\n new_glass_left['x'] = int(glass_left['x'] * k)\r\n new_glass_left['y'] = int(glass_left['y'] * k)\r\n new_glass_right['x'] = int(glass_right['x'] * k)\r\n new_glass_right['y'] = int(glass_right['y'] * k)\r\n\r\n return new_glass_left, new_glass_right\r\n\r\n\r\ndef wear_glass_1(filepath, new_glass_left, left_eye_center, angle):\r\n '''\r\n 眼镜贴图方法一:\r\n 根据左眼和镜框左定位点重合,进行像素替换\r\n\r\n :param new_glass_left:\r\n :return:\r\n '''\r\n # 存放镜框位置坐标\r\n store_point = [] # [i, j]\r\n pkg_point = []\r\n '''\r\n begin_point = {}\r\n begin_point['x'] = left_eye_center['x'] - new_glass_left['x']\r\n begin_point['y'] = left_eye_center['y'] - new_glass_left['y']\r\n '''\r\n face = np.array(Image.open(filepath))\r\n\r\n new_glass = np.array(Image.open('glass_new.png'))\r\n h, w, dim = new_glass.shape\r\n H, W, Dim = face.shape\r\n\r\n cos_ = math.cos(angle)\r\n sin_ = math.sin(angle)\r\n\r\n start_time = time.time()\r\n\r\n for i in range(w):\r\n for j in range(h):\r\n if (sum(new_glass[j][i]) <= 510): # 若为镜框点\r\n pkg_point.append([j, i])\r\n\r\n for i in range(W):\r\n for j in range(H):\r\n vec_x_0 = i - left_eye_center['x']\r\n vec_y_0 = j - left_eye_center['y']\r\n vec_x = int(vec_x_0 * cos_ + vec_y_0 * sin_)\r\n vec_y = int(vec_x_0 * (-sin_) + vec_y_0 * cos_)\r\n if [(new_glass_left['y'] + vec_y), (new_glass_left['x'] + vec_x)] in pkg_point:\r\n for a in range(-1, 2):\r\n for b in range(-1, 2):\r\n if 0<=j+b<=159 and 0<=i+a<=159 and (a*b == 0):\r\n face[j+b][i+a] = [0, 0, 0]\r\n if [j+b, i+a] not in store_point:\r\n store_point.append([j+b, i+a])\r\n end_time = time.time()\r\n print(end_time - start_time)\r\n print('%s: %f %s' % ('about', len(store_point) / (16 * 16), '%'))\r\n return store_point, face\r\n\r\n\r\n'''\r\nif __name__ == '__faceplusplus_face_detect_api__':\r\n faceplusplus_face_detect_api()\r\n'''", "sub_path": "Faceplusplus_face_detect_API_s.py", "file_name": "Faceplusplus_face_detect_API_s.py", "file_ext": "py", "file_size_in_byte": 7658, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "cv2.imread", "line_number": 38, "usage_type": "call"}, {"api_name": "PIL.Image.fromarray", "line_number": 67, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 67, "usage_type": "name"}, {"api_name": "Dir_make.mk_dir", "line_number": 72, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 96, "usage_type": "call"}, {"api_name": "json.JSONDecoder", "line_number": 99, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 123, "usage_type": "call"}, {"api_name": "json.JSONDecoder", "line_number": 126, "usage_type": "call"}, {"api_name": "math.atan", "line_number": 137, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 158, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 158, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 193, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 193, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 193, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 195, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 195, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 195, "usage_type": "name"}, {"api_name": "math.cos", "line_number": 199, "usage_type": "call"}, {"api_name": "math.sin", "line_number": 200, "usage_type": "call"}, {"api_name": "time.time", "line_number": 202, "usage_type": "call"}, {"api_name": "time.time", "line_number": 222, "usage_type": "call"}]}
+{"seq_id": "625198205", "text": "# Yhlin\nimport os\nimport tensorflow as tf\nimport argparse\nimport time\nimport json\nimport glob\nimport shutil\nfrom dataset_factory import get_custom_dataset, CUSTOM_DATASET_INFO\nfrom resnet_model import ResNet, get_block_sizes\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\n\ndef get_optimizer(optim_name, lr):\n if optim_name == 'adam':\n return tf.train.AdamOptimizer(lr)\n elif optim_name == 'rmsprop':\n return tf.train.RMSPropOptimizer(lr)\n elif optim_name == 'momentum':\n return tf.train.MomentumOptimizer(lr, momentum=0.9)\n else:\n return tf.train.GradientDescentOptimizer(lr)\n\n\ndef get_learning_rate(global_step, batch_size, num_images,\n boundary_epochs, decay_rates,\n base_lr=0.1, warmup=False, decay=False):\n batches_per_epoch = num_images / batch_size\n if decay:\n boundaries = [int(batches_per_epoch * epoch) for epoch in\n boundary_epochs]\n vals = [base_lr * rate for rate in decay_rates]\n lr = tf.train.piecewise_constant(global_step, boundaries, vals)\n else:\n lr = tf.convert_to_tensor(base_lr, tf.float32)\n if warmup:\n warmup_steps = int(batches_per_epoch * 5)\n warmup_lr = (base_lr * tf.cast(global_step, tf.float32) /\n tf.cast(warmup_steps, tf.float32))\n return tf.cond(pred=global_step < warmup_steps,\n true_fn=lambda: warmup_lr,\n false_fn=lambda: lr)\n return lr\n\n\ndef reset_last_ckpt_dir(ckpt_dir):\n count = 1\n ckpt_dir += '_0'\n while os.path.exists(ckpt_dir):\n index = ckpt_dir.rfind('_')\n ckpt_dir = ckpt_dir[:index] + '_{}'.format(count)\n count += 1\n count -= 1\n index = ckpt_dir.rfind('_')\n ckpt_dir = ckpt_dir[:index] + '_{}'.format(count)\n shutil.rmtree(ckpt_dir)\n return ckpt_dir\n\n\ndef prepare_ckpt_dir(ckpt_dir):\n count = 1\n ckpt_dir += '_0'\n while os.path.exists(ckpt_dir):\n index = ckpt_dir.rfind('_')\n ckpt_dir = ckpt_dir[:index] + '_{}'.format(count)\n count += 1\n return ckpt_dir\n\n\ndef main(args):\n ckpt_dir = args.ckpt_dir\n num_epochs = args.num_epochs\n batch_size = args.batch_size\n data_dir = args.data_dir\n boundaries = [int(x) for x in args.boundaries.split(',')]\n decay_rates = [float(x) for x in args.decay_rates.split(',')]\n\n training = tf.placeholder(tf.bool, shape=[], name='training')\n\n # Dataset\n train_dataset = get_custom_dataset(True,\n data_dir=data_dir,\n batch_size=batch_size)\n val_dataset = get_custom_dataset(False, data_dir=data_dir,\n batch_size=batch_size)\n iterator = tf.data.Iterator.from_structure(train_dataset.output_types,\n train_dataset.output_shapes)\n features, labels = iterator.get_next()\n train_ds_init_op = iterator.make_initializer(train_dataset)\n val_ds_init_op = iterator.make_initializer(val_dataset)\n\n # Model\n resnet_size = 50\n model = ResNet(resnet_size=resnet_size,\n num_classes=CUSTOM_DATASET_INFO.num_classes,\n num_filters=64,\n kernel_size=7,\n conv_stride=2,\n first_pool_size=3,\n first_pool_stride=2,\n block_sizes=get_block_sizes(resnet_size),\n block_strides=[1, 2, 2, 2],\n resnet_version=2,\n data_format='channels_last',\n dtype=tf.float32)\n logits = model(features, training)\n loss = tf.losses.sparse_softmax_cross_entropy(\n logits=logits, labels=labels)\n\n pred = tf.argmax(input=logits, axis=1, name='classes')\n acc, acc_update_op = tf.metrics.accuracy(labels=labels,\n predictions=pred)\n metric_vars = tf.get_collection(tf.GraphKeys.METRIC_VARIABLES)\n metric_vars_init_op = tf.variables_initializer(metric_vars,\n name='metric_vars_init')\n\n global_step = tf.train.get_or_create_global_step()\n lr = get_learning_rate(global_step, batch_size,\n CUSTOM_DATASET_INFO.train,\n boundary_epochs=boundaries,\n decay_rates=decay_rates,\n base_lr=args.lr,\n warmup=args.warmup,\n decay=args.decay)\n\n tf.identity(lr, name='learning_rate')\n\n optimizer = get_optimizer(args.optim_name, lr)\n minimize_op = optimizer.minimize(loss, global_step=global_step)\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n train_op = tf.group(minimize_op, update_ops)\n\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n\n saver = tf.train.Saver()\n best_acc_history = {}\n best_acc = 0\n with tf.Session(config=config) as sess:\n sess.run(tf.global_variables_initializer())\n last_ckpt = tf.train.latest_checkpoint(ckpt_dir)\n if last_ckpt is not None:\n saver.restore(sess, last_ckpt)\n print('Restore from checkpoint: ', str(last_ckpt.split('-')[-1]))\n\n global_step_value = None\n for epoch in range(num_epochs):\n # Train\n sess.run(metric_vars_init_op)\n sess.run(train_ds_init_op)\n step = 0\n total_loss = 0\n start_time = time.time()\n lr_value = 0\n while True:\n try:\n _, _, loss_value, global_step_value, lr_value = sess.run(\n [train_op, acc_update_op, loss, global_step, lr],\n feed_dict={training: True}\n )\n total_loss += loss_value\n step += 1\n except tf.errors.OutOfRangeError:\n break\n\n acc_value = sess.run(acc)\n msg = 'Epoch: {}\\n'.format(epoch)\n msg += ' Train: Loss {:.4f} Acc {:.4f} global step {}'.format(\n total_loss / step, acc_value, global_step_value)\n msg += ' lr {:.6f}'.format(lr_value)\n msg += '({:.2f}s)'.format(time.time() - start_time)\n print(msg)\n saver.save(sess, os.path.join(ckpt_dir, 'model'),\n global_step=global_step_value)\n\n # Eval\n sess.run(metric_vars_init_op)\n sess.run(val_ds_init_op)\n step = 0\n total_loss = 0\n while True:\n try:\n loss_value, _ = sess.run(\n [loss, acc_update_op],\n feed_dict={training: False})\n total_loss += loss_value\n step += 1\n except tf.errors.OutOfRangeError:\n break\n acc_value = sess.run(acc)\n print(' Valid: Loss {:.4f} Acc {:.4f} '.format(\n total_loss / step, acc_value))\n last_ckpt = tf.train.latest_checkpoint(ckpt_dir)\n if acc_value > best_acc:\n best_acc = acc_value\n best_step = last_ckpt.split('-')[-1]\n best_acc_history[best_step] = '{:.4f}'.format(best_acc)\n print(' Gets a better result. Save it.')\n for filename in glob.glob(last_ckpt + '.*'):\n basename = os.path.basename(filename)\n if not os.path.exists(\n os.path.join(args.ckpt_dir, 'save')):\n os.makedirs(\n os.path.join(args.ckpt_dir, 'save'))\n shutil.copyfile(\n filename,\n os.path.join(args.ckpt_dir, 'save', basename))\n\n with open(os.path.join(args.ckpt_dir, 'save', 'acc.json'),\n 'w', encoding='utf-8') as fp:\n json.dump(best_acc_history, fp)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--num_epochs', type=int, default=80)\n parser.add_argument('--batch_size', type=int, default=32)\n parser.add_argument('--gpus', default='1')\n parser.add_argument('--lr', type=float, default=0.00625)\n parser.add_argument('--ckpt_dir', default='...')\n parser.add_argument('--data_dir',\n default='...')\n parser.add_argument('--warmup', action='store_true', default=False)\n parser.add_argument('--decay', action='store_true', default=False)\n parser.add_argument('--boundaries', default='10,20,30,40')\n parser.add_argument('--decay_rates', default='1,0.1,0.01,0.001,0.0001')\n parser.add_argument('--optim_name', type=str, default='momentum')\n parser.add_argument('--go_on', action='store_true', default=False)\n parser.add_argument('--reset', action='store_true', default=False)\n args = parser.parse_args()\n os.environ['CUDA_VISIBLE_DEVICES'] = args.gpus\n\n if args.reset:\n assert not args.go_on\n args.ckpt_dir = reset_last_ckpt_dir(args.ckpt_dir)\n\n\n\n if not args.go_on:\n args.ckpt_dir = prepare_ckpt_dir(args.ckpt_dir)\n\n args_dict = {}\n for k, v in sorted(vars(args).items()):\n args_dict[k] = str(v)\n if not os.path.exists(args.ckpt_dir):\n os.makedirs(args.ckpt_dir)\n with open(os.path.join(args.ckpt_dir, 'cfg.json'),\n 'w', encoding='utf-8') as fp:\n json.dump(args_dict, fp, indent=4)\n\n main(args)\n", "sub_path": "train.py", "file_name": "train.py", "file_ext": "py", "file_size_in_byte": 9628, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "os.environ", "line_number": 12, "usage_type": "attribute"}, {"api_name": "tensorflow.train.AdamOptimizer", "line_number": 17, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 17, "usage_type": "attribute"}, {"api_name": "tensorflow.train.RMSPropOptimizer", "line_number": 19, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 19, "usage_type": "attribute"}, {"api_name": "tensorflow.train.MomentumOptimizer", "line_number": 21, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 21, "usage_type": "attribute"}, {"api_name": "tensorflow.train.GradientDescentOptimizer", "line_number": 23, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 23, "usage_type": "attribute"}, {"api_name": "tensorflow.train.piecewise_constant", "line_number": 34, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 34, "usage_type": "attribute"}, {"api_name": "tensorflow.convert_to_tensor", "line_number": 36, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 36, "usage_type": "attribute"}, {"api_name": "tensorflow.cast", "line_number": 39, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 39, "usage_type": "attribute"}, {"api_name": "tensorflow.cast", "line_number": 40, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 40, "usage_type": "attribute"}, {"api_name": "tensorflow.cond", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path", "line_number": 50, "usage_type": "attribute"}, {"api_name": "shutil.rmtree", "line_number": 57, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 64, "usage_type": "call"}, {"api_name": "os.path", "line_number": 64, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 79, "usage_type": "call"}, {"api_name": "tensorflow.bool", "line_number": 79, "usage_type": "attribute"}, {"api_name": "dataset_factory.get_custom_dataset", "line_number": 82, "usage_type": "call"}, {"api_name": "dataset_factory.get_custom_dataset", "line_number": 85, "usage_type": "call"}, {"api_name": "tensorflow.data.Iterator.from_structure", "line_number": 87, "usage_type": "call"}, {"api_name": "tensorflow.data", "line_number": 87, "usage_type": "attribute"}, {"api_name": "resnet_model.ResNet", "line_number": 95, "usage_type": "call"}, {"api_name": "dataset_factory.CUSTOM_DATASET_INFO.num_classes", "line_number": 96, "usage_type": "attribute"}, {"api_name": "dataset_factory.CUSTOM_DATASET_INFO", "line_number": 96, "usage_type": "name"}, {"api_name": "resnet_model.get_block_sizes", "line_number": 102, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 106, "usage_type": "attribute"}, {"api_name": "tensorflow.losses.sparse_softmax_cross_entropy", "line_number": 108, "usage_type": "call"}, {"api_name": "tensorflow.losses", "line_number": 108, "usage_type": "attribute"}, {"api_name": "tensorflow.argmax", "line_number": 111, "usage_type": "call"}, {"api_name": "tensorflow.metrics.accuracy", "line_number": 112, "usage_type": "call"}, {"api_name": "tensorflow.metrics", "line_number": 112, "usage_type": "attribute"}, {"api_name": "tensorflow.get_collection", "line_number": 114, "usage_type": "call"}, {"api_name": "tensorflow.GraphKeys", "line_number": 114, "usage_type": "attribute"}, {"api_name": "tensorflow.variables_initializer", "line_number": 115, "usage_type": "call"}, {"api_name": "tensorflow.train.get_or_create_global_step", "line_number": 118, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 118, "usage_type": "attribute"}, {"api_name": "dataset_factory.CUSTOM_DATASET_INFO.train", "line_number": 120, "usage_type": "attribute"}, {"api_name": "dataset_factory.CUSTOM_DATASET_INFO", "line_number": 120, "usage_type": "name"}, {"api_name": "tensorflow.identity", "line_number": 127, "usage_type": "call"}, {"api_name": "tensorflow.get_collection", "line_number": 131, "usage_type": "call"}, {"api_name": "tensorflow.GraphKeys", "line_number": 131, "usage_type": "attribute"}, {"api_name": "tensorflow.group", "line_number": 132, "usage_type": "call"}, {"api_name": "tensorflow.ConfigProto", "line_number": 134, "usage_type": "call"}, {"api_name": "tensorflow.train.Saver", "line_number": 137, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 137, "usage_type": "attribute"}, {"api_name": "tensorflow.Session", "line_number": 140, "usage_type": "call"}, {"api_name": "tensorflow.global_variables_initializer", "line_number": 141, "usage_type": "call"}, {"api_name": "tensorflow.train.latest_checkpoint", "line_number": 142, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 142, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 154, "usage_type": "call"}, {"api_name": "tensorflow.errors", "line_number": 164, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 172, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 174, "usage_type": "call"}, {"api_name": "os.path", "line_number": 174, "usage_type": "attribute"}, {"api_name": "tensorflow.errors", "line_number": 189, "usage_type": "attribute"}, {"api_name": "tensorflow.train.latest_checkpoint", "line_number": 194, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 194, "usage_type": "attribute"}, {"api_name": "glob.glob", "line_number": 200, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 201, "usage_type": "call"}, {"api_name": "os.path", "line_number": 201, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 202, "usage_type": "call"}, {"api_name": "os.path", "line_number": 202, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 203, "usage_type": "call"}, {"api_name": "os.path", "line_number": 203, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 204, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 205, "usage_type": "call"}, {"api_name": "os.path", "line_number": 205, "usage_type": "attribute"}, {"api_name": "shutil.copyfile", "line_number": 206, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 208, "usage_type": "call"}, {"api_name": "os.path", "line_number": 208, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 210, "usage_type": "call"}, {"api_name": "os.path", "line_number": 210, "usage_type": "attribute"}, {"api_name": "json.dump", "line_number": 212, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 216, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 232, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 246, "usage_type": "call"}, {"api_name": "os.path", "line_number": 246, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 247, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 248, "usage_type": "call"}, {"api_name": "os.path", "line_number": 248, "usage_type": "attribute"}, {"api_name": "json.dump", "line_number": 250, "usage_type": "call"}]}
+{"seq_id": "210792947", "text": "import numpy as np\nimport problem1\nimport statsmodels.api as sm\nimport matplotlib.pyplot as plt\n\ndef calcLambda(E, v):\n return v*E / ((1.+v)*(1.-2.*v))\n\ndef calcMiu(E, v):\n return E / (2.*(1.+v))\n\ndef calcBeta(H, equivalent_stress, Miu):\n return 9.*Miu**2 / (equivalent_stress**2 * (H + 3.*Miu))\n\ndef calcStressArr(nodeX, nodeY, nodes, originalGrids, dsArr, esArr):\n grids = problem1.generateGrids(nodeX, nodeY, nodes)\n stressArr = []\n for grid, originalGrid, ds, es in zip(grids, originalGrids, dsArr, esArr):\n a = problem1.calcArea(grid)\n B = problem1.calcBmatrix(a, grid)\n du = grid - originalGrid\n strain_t = B * du.reshape((du.size, 1))\n stress_t = D * strain_t\n if es > yield_stress:\n beta = calcBeta(H, es, Miu)\n else:\n beta = 0.\n sigma33 = (Lambda - beta*ds[3]*ds[0]) * strain_t[0] +\\\n (Lambda - beta*ds[3]*ds[1]) * strain_t[1] +\\\n (-beta*ds[3]*ds[2]) * strain_t[2]\n stress_t = np.array(stress_t).reshape(stress_t.size//3, 3).flatten()\n sigma33 = np.array(sigma33).reshape(sigma33.size, 1).flatten()\n stressArr.append(list(stress_t) + list(sigma33))\n return np.array(stressArr).reshape(len(stressArr), 4, 1)\n\ndef calcDpMatrix(deviatoric_stress, equivalent_stress):\n beta = calcBeta(H, equivalent_stress, Miu)\n d11 = Lambda + 2.*Miu - beta*deviatoric_stress[0]**2\n d12 = Lambda - beta*deviatoric_stress[0]*deviatoric_stress[1]\n d13 = -beta * deviatoric_stress[0] * deviatoric_stress[2]\n d22 = Lambda + 2.*Miu - beta*deviatoric_stress[1]**2\n d23 = -beta * deviatoric_stress[1] * deviatoric_stress[2]\n d33 = Miu - beta * deviatoric_stress[2]**2\n Dp = np.matrix([\n [d11[0], d12[0], d13[0]],\n [d12[0], d22[0], d23[0]],\n [d13[0], d23[0], d33[0]]])\n return Dp\n\ndef calcKmatrix(stressArr, D, nodeX, nodeY, gridSize, grids):\n def calcDeviatoricStress(stress):\n mean_stress = (stress[0] + stress[1] + stress[3]) / 3\n deviatoric_stress = [\n stress[0] - mean_stress,\n stress[1] - mean_stress,\n stress[2],\n stress[3] - mean_stress\n ]\n return np.array(deviatoric_stress)\n \n def calcEquivalentStress(deviatoric_stress):\n equivalent_stress = np.sqrt(1.5 * (\n deviatoric_stress[0]**2 +\n deviatoric_stress[1]**2 +\n 2. * deviatoric_stress[2]**2 +\n deviatoric_stress[3]**2)\n )\n return equivalent_stress\n\n nodeNum = nodeX * nodeY\n K = np.matrix(np.zeros((nodeNum*2, nodeNum*2), dtype=np.float64))\n dsArr = []\n esArr = []\n for grid, stress in zip(grids, stressArr):\n _nodes = [problem1.calcNodeNo(node, nodeY, gridSize) for node in grid]\n a = problem1.calcArea(grid)\n b = problem1.calcBmatrix(a, grid)\n\n deviatoric_stress = calcDeviatoricStress(stress)\n equivalent_stress = calcEquivalentStress(deviatoric_stress)\n dsArr.append(deviatoric_stress)\n esArr.append(equivalent_stress)\n\n if equivalent_stress > yield_stress:\n Dp = calcDpMatrix(deviatoric_stress, equivalent_stress)\n k = a * b.transpose() * Dp * b\n else:\n k = a * b.transpose() * D * b\n for i, nodeNoX in enumerate(_nodes):\n x = i * 2\n nodeNoX *= 2\n for j, nodeNoY in enumerate(_nodes):\n y = j * 2\n nodeNoY *= 2\n K[nodeNoX:nodeNoX+2, nodeNoY:nodeNoY+2] += k[x:x+2, y:y+2]\n return K, np.array(dsArr), np.array(esArr)\n\ndef tensile_test(u, stressArr, D, gridSize, nodeX, nodeY, nodes):\n grids = problem1.generateGrids(nodeX, nodeY, nodes)\n K, dsArr, esArr = calcKmatrix(stressArr, D, nodeX, nodeY, gridSize, grids)\n\n f = np.zeros_like(u)\n f -= K * u\n f_ = f[nodeX*2:]\n f_ = np.delete(f_, range(nodeX*(nodeY-2)*2+1, nodeX*(nodeY-1)*2, 2), axis=0)\n\n K_ = K[nodeX*2:, nodeY*2:]\n K_ = np.delete(K_, range(nodeX*(nodeY-2)*2+1, nodeX*(nodeY-1)*2, 2), axis=0)\n K_ = np.delete(K_, range(nodeX*(nodeY-2)*2+1, nodeX*(nodeY-1)*2, 2), axis=1)\n\n u_ = np.linalg.solve(K_, f_)\n u[nodeX*2:nodeX*(nodeY-1)*2] += u_[:-nodeX]\n u[-nodeX*2::2] += u_[-nodeX:]\n\n nodes += u.reshape(u.shape[0]//2, 2)\n\n f = K * u\n\n stressArr = calcStressArr(nodeX, nodeY, nodes, originalGrids, dsArr, esArr)\n return np.sum(f[-nodeX*2+1::2]), stressArr, nodes\n\nif __name__ == '__main__':\n E = 1.06e5 # Young's modulus\n v = .25 # Poisson's ratio\n yield_stress = 300.\n H = E / 20 # hardening modulus\n\n D = problem1.calcDmatrix(E, v)\n Lambda = calcLambda(E, v)\n Miu = calcMiu(E, v)\n\n #boundary\n x0 = 0.; xn = 1.\n y0 = 0.; yn = 1.\n length = yn - y0\n gridSize = .1\n\n nodeX, nodeY, nodes = problem1.generateNodes(x0, xn, y0, yn, gridSize)\n nodeNum = nodeX * nodeY\n originalGrids = problem1.generateGrids(nodeX, nodeY, nodes)\n stressArr = np.zeros((len(originalGrids), 4, 1))\n \n stress_axis = [0.]\n strain_axis = [0.]\n equivalent_stress = 0.\n strain_increment = .0001\n\n u = np.matrix(np.zeros((nodeNum*2, 1), dtype=np.float64))\n u[-nodeX*2+1::2] = strain_increment\n\n for counter in range(1, 45):\n stress_increment, stressArr, nodes = tensile_test(\n u, stressArr, D, gridSize, nodeX, nodeY, nodes)\n stress_axis.append(stress_axis[-1] + stress_increment)\n strain_axis.append((strain_increment*counter) / length)\n\n plt.xlabel('strain')\n plt.ylabel('stress (MPa)')\n plt.plot(strain_axis, stress_axis, 'o')\n plt.show()\n", "sub_path": "report/aoyagi/problem2.py", "file_name": "problem2.py", "file_ext": "py", "file_size_in_byte": 5651, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "problem1.generateGrids", "line_number": 16, "usage_type": "call"}, {"api_name": "problem1.calcArea", "line_number": 19, "usage_type": "call"}, {"api_name": "problem1.calcBmatrix", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.matrix", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.matrix", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 71, "usage_type": "attribute"}, {"api_name": "problem1.calcNodeNo", "line_number": 75, "usage_type": "call"}, {"api_name": "problem1.calcArea", "line_number": 76, "usage_type": "call"}, {"api_name": "problem1.calcBmatrix", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 96, "usage_type": "call"}, {"api_name": "problem1.generateGrids", "line_number": 99, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 102, "usage_type": "call"}, {"api_name": "numpy.delete", "line_number": 105, "usage_type": "call"}, {"api_name": "numpy.delete", "line_number": 108, "usage_type": "call"}, {"api_name": "numpy.delete", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.linalg.solve", "line_number": 111, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 111, "usage_type": "attribute"}, {"api_name": "numpy.sum", "line_number": 120, "usage_type": "call"}, {"api_name": "problem1.calcDmatrix", "line_number": 128, "usage_type": "call"}, {"api_name": "problem1.generateNodes", "line_number": 138, "usage_type": "call"}, {"api_name": "problem1.generateGrids", "line_number": 140, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 141, "usage_type": "call"}, {"api_name": "numpy.matrix", "line_number": 148, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 148, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 148, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 157, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 157, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 158, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 158, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "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"}]}
+{"seq_id": "532416875", "text": "from functools import wraps\nfrom itertools import chain\n\nfrom lunavl.sdk.estimators.face_estimators.fisheye import Fisheye\nfrom lunavl.sdk.faceengine.setting_provider import DetectorType\nfrom lunavl.sdk.image_utils.image import VLImage\nfrom tests.base import BaseTestClass\nfrom tests.resources import FISHEYE, FROWNING\n\n\ndef warpedSubTests(test):\n @wraps(test)\n def wrappedFunc(*func_args, **func_kwargs):\n for warped in [True, False]:\n with func_args[0].subTest(warped=warped):\n test(*func_args, **func_kwargs, warped=warped)\n\n return wrappedFunc\n\n\nclass TestFisheyeEffect(BaseTestClass):\n \"\"\"\n Test fisheye estimation.\n \"\"\"\n\n @classmethod\n def setup_class(cls):\n super().setup_class()\n cls.detector = cls.faceEngine.createFaceDetector(DetectorType.FACE_DET_V3)\n cls.warper = cls.faceEngine.createFaceWarper()\n cls.fisheyeEstimator = cls.faceEngine.createFisheyeEstimator()\n\n def test_estimate_fisheye_correctness(self):\n \"\"\"\n Test fisheye estimator correctness\n \"\"\"\n estimation = self.estimate(FISHEYE)\n assert estimation.status\n assert 0 <= estimation.score <= 1\n\n def estimate(self, image: str = FROWNING, warped: bool = True) -> Fisheye:\n \"\"\"Estimate fisheye on image\"\"\"\n faceDetection = self.detector.detectOne(VLImage.load(filename=image))\n if warped:\n warp = self.warper.warp(faceDetection)\n estimation = self.fisheyeEstimator.estimate(warp.warpedImage)\n else:\n estimation = self.fisheyeEstimator.estimate(faceDetection)\n assert isinstance(estimation, Fisheye)\n return estimation\n\n def estimateBatch(self, images, warped) -> list[Fisheye]:\n \"\"\"Estimate fisheye on image\"\"\"\n imageDetections = self.detector.detect([VLImage.load(filename=name) for name in images])\n if warped:\n warps = [self.warper.warp(res[0]) for res in imageDetections]\n estimations = self.fisheyeEstimator.estimateBatch(warps)\n else:\n estimations = self.fisheyeEstimator.estimateBatch(list(chain(*imageDetections)))\n assert all(isinstance(estimation, Fisheye) for estimation in estimations)\n return estimations\n\n @warpedSubTests\n def test_estimate_fisheye(self, warped):\n \"\"\"\n Simple fisheye estimation\n \"\"\"\n estimation = self.estimate(FROWNING, warped=warped)\n assert not estimation.status\n assert 0 <= estimation.score <= 1\n\n @warpedSubTests\n def test_fisheye_as_dict(self, warped):\n \"\"\"\n Test method Fisheye.asDict\n \"\"\"\n estimation = self.estimate(FROWNING, warped=warped)\n assert {\n \"status\": estimation.status,\n \"score\": estimation.score,\n } == estimation.asDict()\n\n @warpedSubTests\n def test_estimate_fisheye_batch(self, warped):\n \"\"\"\n Batch fisheye estimation test\n \"\"\"\n estimations = self.estimateBatch([FROWNING, FISHEYE], warped=warped)\n assert not estimations[0].status\n assert estimations[1].status\n", "sub_path": "tests/test_fisheye.py", "file_name": "test_fisheye.py", "file_ext": "py", "file_size_in_byte": 3140, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "functools.wraps", "line_number": 12, "usage_type": "call"}, {"api_name": "tests.base.BaseTestClass", "line_number": 21, "usage_type": "name"}, {"api_name": "lunavl.sdk.faceengine.setting_provider.DetectorType.FACE_DET_V3", "line_number": 29, "usage_type": "attribute"}, {"api_name": "lunavl.sdk.faceengine.setting_provider.DetectorType", "line_number": 29, "usage_type": "name"}, {"api_name": "tests.resources.FISHEYE", "line_number": 37, "usage_type": "argument"}, {"api_name": "tests.resources.FROWNING", "line_number": 41, "usage_type": "name"}, {"api_name": "lunavl.sdk.image_utils.image.VLImage.load", "line_number": 43, "usage_type": "call"}, {"api_name": "lunavl.sdk.image_utils.image.VLImage", "line_number": 43, "usage_type": "name"}, {"api_name": "lunavl.sdk.estimators.face_estimators.fisheye.Fisheye", "line_number": 49, "usage_type": "argument"}, {"api_name": "lunavl.sdk.estimators.face_estimators.fisheye.Fisheye", "line_number": 41, "usage_type": "name"}, {"api_name": "lunavl.sdk.image_utils.image.VLImage.load", "line_number": 54, "usage_type": "call"}, {"api_name": "lunavl.sdk.image_utils.image.VLImage", "line_number": 54, "usage_type": "name"}, {"api_name": "itertools.chain", "line_number": 59, "usage_type": "call"}, {"api_name": "lunavl.sdk.estimators.face_estimators.fisheye.Fisheye", "line_number": 60, "usage_type": "argument"}, {"api_name": "lunavl.sdk.estimators.face_estimators.fisheye.Fisheye", "line_number": 52, "usage_type": "name"}, {"api_name": "tests.resources.FROWNING", "line_number": 68, "usage_type": "argument"}, {"api_name": "tests.resources.FROWNING", "line_number": 77, "usage_type": "argument"}, {"api_name": "tests.resources.FROWNING", "line_number": 88, "usage_type": "name"}, {"api_name": "tests.resources.FISHEYE", "line_number": 88, "usage_type": "name"}]}
+{"seq_id": "496799772", "text": "from datetime import datetime\n\nimport colander\nimport pytz\n\nfrom ichnaea.api.exceptions import ParseError\nfrom ichnaea.api.submit.schema_v0 import SUBMIT_V0_SCHEMA\nfrom ichnaea.api.submit.tests.base import BaseSubmitTest\nfrom ichnaea.models import Radio\nfrom ichnaea.tests.base import (\n CeleryAppTestCase,\n TestCase,\n)\nfrom ichnaea.tests.factories import (\n CellShardFactory,\n WifiShardFactory,\n)\nfrom ichnaea import util\n\n\nclass TestSubmitSchema(TestCase):\n\n schema = SUBMIT_V0_SCHEMA\n\n def test_empty(self):\n with self.assertRaises(colander.Invalid):\n self.schema.deserialize({})\n\n def test_empty_wifi_entry(self):\n wifi = WifiShardFactory.build()\n data = self.schema.deserialize({'items': [\n {'lat': wifi.lat, 'lon': wifi.lon, 'wifi': [{}]},\n ]})\n self.assertEqual(data, {'items': []})\n\n def test_minimal(self):\n wifi = WifiShardFactory.build()\n data = self.schema.deserialize(\n {'items': [{'lat': wifi.lat, 'lon': wifi.lon,\n 'wifi': [{'key': 'ab'}]}]})\n self.assertTrue('items' in data)\n self.assertEqual(len(data['items']), 1)\n\n\nclass TestView(BaseSubmitTest, CeleryAppTestCase):\n\n url = '/v1/submit'\n metric_path = 'path:v1.submit'\n status = 204\n radio_id = 'radio'\n cells_id = 'cell'\n\n def _one_cell_query(self, radio=True):\n cell = CellShardFactory.build()\n query = {'lat': cell.lat, 'lon': cell.lon,\n 'cell': [{'mcc': cell.mcc, 'mnc': cell.mnc,\n 'lac': cell.lac, 'cid': cell.cid}]}\n if radio:\n query['cell'][0]['radio'] = cell.radio.name\n return (cell, query)\n\n def test_cell(self):\n now = util.utcnow()\n today = now.replace(hour=0, minute=0, second=0)\n cell = CellShardFactory.build(radio=Radio.umts)\n res = self._post([{\n 'lat': cell.lat,\n 'lon': cell.lon,\n 'time': today.strftime('%Y-%m-%d'),\n 'accuracy': 10.6,\n 'altitude': 123.1,\n 'altitude_accuracy': 7.0,\n 'radio': cell.radio.name,\n 'cell': [{\n 'radio': 'umts', 'mcc': cell.mcc,\n 'mnc': cell.mnc, 'lac': cell.lac, 'cid': cell.cid}],\n }], api_key='test')\n self.assertEqual(res.body, b'')\n\n self._assert_queue_size(1)\n item = self.queue.dequeue(self.queue.queue_key())[0]\n self.assertEqual(item['api_key'], 'test')\n report = item['report']\n timestamp = datetime.utcfromtimestamp(report['timestamp'] / 1000.0)\n timestamp = timestamp.replace(microsecond=0, tzinfo=pytz.UTC)\n self.assertEqual(timestamp, today)\n position = report['position']\n self.assertEqual(position['latitude'], cell.lat)\n self.assertEqual(position['longitude'], cell.lon)\n self.assertEqual(position['accuracy'], 10.6)\n self.assertEqual(position['altitude'], 123.1)\n self.assertEqual(position['altitudeAccuracy'], 7.0)\n cells = report['cellTowers']\n self.assertEqual(cells[0]['radioType'], 'wcdma')\n self.assertEqual(cells[0]['mobileCountryCode'], cell.mcc)\n self.assertEqual(cells[0]['mobileNetworkCode'], cell.mnc)\n self.assertEqual(cells[0]['locationAreaCode'], cell.lac)\n self.assertEqual(cells[0]['cellId'], cell.cid)\n\n def test_wifi(self):\n wifi = WifiShardFactory.build()\n self._post([{\n 'lat': wifi.lat,\n 'lon': wifi.lon,\n 'accuracy': 17.1,\n 'wifi': [{'key': wifi.mac.upper(),\n 'frequency': 2437,\n 'signal': -70,\n 'signalToNoiseRatio': 5,\n 'ssid': 'my-wifi',\n }]\n }])\n\n self._assert_queue_size(1)\n item = self.queue.dequeue(self.queue.queue_key())[0]\n self.assertEqual(item['api_key'], None)\n report = item['report']\n position = report['position']\n self.assertEqual(position['latitude'], wifi.lat)\n self.assertEqual(position['longitude'], wifi.lon)\n self.assertEqual(position['accuracy'], 17.1)\n self.assertFalse('altitude' in position)\n self.assertFalse('altitudeAccuracy' in position)\n wifis = report['wifiAccessPoints']\n self.assertEqual(wifis[0]['macAddress'], wifi.mac.upper())\n self.assertFalse('channel' in wifis[0])\n self.assertEqual(wifis[0]['frequency'], 2437)\n self.assertEqual(wifis[0]['signalStrength'], -70)\n self.assertEqual(wifis[0]['signalToNoiseRatio'], 5)\n self.assertEqual(wifis[0]['ssid'], 'my-wifi')\n\n def test_batches(self):\n batch = 110\n wifis = WifiShardFactory.build_batch(batch)\n items = [{'lat': wifi.lat,\n 'lon': wifi.lon,\n 'wifi': [{'key': wifi.mac}]}\n for wifi in wifis]\n\n # add a bad one, this will just be skipped\n items.append({'lat': 10.0, 'lon': 10.0, 'whatever': 'xx'})\n self._post(items)\n self._assert_queue_size(batch)\n\n def test_error(self):\n wifi = WifiShardFactory.build()\n res = self.app.post_json(\n '/v1/submit',\n [{'lat': wifi.lat, 'lon': wifi.lon, 'cell': []}],\n status=400)\n self.assertEqual(res.json, ParseError.json_body())\n self.check_raven(['ParseError'])\n\n def test_error_missing_latlon(self):\n wifi = WifiShardFactory.build()\n self._post([\n {'lat': wifi.lat,\n 'lon': wifi.lon,\n 'accuracy': 17.0,\n 'wifi': [{'key': wifi.mac}],\n },\n {'wifi': [{'key': wifi.mac}],\n 'accuracy': 16.0},\n ])\n self._assert_queue_size(2)\n", "sub_path": "ichnaea/api/submit/tests/test_submit_v0.py", "file_name": "test_submit_v0.py", "file_ext": "py", "file_size_in_byte": 5815, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "ichnaea.tests.base.TestCase", "line_number": 21, "usage_type": "name"}, {"api_name": "ichnaea.api.submit.schema_v0.SUBMIT_V0_SCHEMA", "line_number": 23, "usage_type": "name"}, {"api_name": "colander.Invalid", "line_number": 26, "usage_type": "attribute"}, {"api_name": "ichnaea.tests.factories.WifiShardFactory.build", "line_number": 30, "usage_type": "call"}, {"api_name": "ichnaea.tests.factories.WifiShardFactory", "line_number": 30, "usage_type": "name"}, {"api_name": "ichnaea.tests.factories.WifiShardFactory.build", "line_number": 37, "usage_type": "call"}, {"api_name": "ichnaea.tests.factories.WifiShardFactory", "line_number": 37, "usage_type": "name"}, {"api_name": "ichnaea.api.submit.tests.base.BaseSubmitTest", "line_number": 45, "usage_type": "name"}, {"api_name": "ichnaea.tests.base.CeleryAppTestCase", "line_number": 45, "usage_type": "name"}, {"api_name": "ichnaea.tests.factories.CellShardFactory.build", "line_number": 54, "usage_type": "call"}, {"api_name": "ichnaea.tests.factories.CellShardFactory", "line_number": 54, "usage_type": "name"}, {"api_name": "ichnaea.util.utcnow", "line_number": 63, "usage_type": "call"}, {"api_name": "ichnaea.util", "line_number": 63, "usage_type": "name"}, {"api_name": "ichnaea.tests.factories.CellShardFactory.build", "line_number": 65, "usage_type": "call"}, {"api_name": "ichnaea.tests.factories.CellShardFactory", "line_number": 65, "usage_type": "name"}, {"api_name": "ichnaea.models.Radio.umts", "line_number": 65, "usage_type": "attribute"}, {"api_name": "ichnaea.models.Radio", "line_number": 65, "usage_type": "name"}, {"api_name": "datetime.datetime.utcfromtimestamp", "line_number": 84, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 84, "usage_type": "name"}, {"api_name": "pytz.UTC", "line_number": 85, "usage_type": "attribute"}, {"api_name": "ichnaea.tests.factories.WifiShardFactory.build", "line_number": 101, "usage_type": "call"}, {"api_name": "ichnaea.tests.factories.WifiShardFactory", "line_number": 101, "usage_type": "name"}, {"api_name": "ichnaea.tests.factories.WifiShardFactory.build_batch", "line_number": 134, "usage_type": "call"}, {"api_name": "ichnaea.tests.factories.WifiShardFactory", "line_number": 134, "usage_type": "name"}, {"api_name": "ichnaea.tests.factories.WifiShardFactory.build", "line_number": 146, "usage_type": "call"}, {"api_name": "ichnaea.tests.factories.WifiShardFactory", "line_number": 146, "usage_type": "name"}, {"api_name": "ichnaea.api.exceptions.ParseError.json_body", "line_number": 151, "usage_type": "call"}, {"api_name": "ichnaea.api.exceptions.ParseError", "line_number": 151, "usage_type": "name"}, {"api_name": "ichnaea.tests.factories.WifiShardFactory.build", "line_number": 155, "usage_type": "call"}, {"api_name": "ichnaea.tests.factories.WifiShardFactory", "line_number": 155, "usage_type": "name"}]}
+{"seq_id": "104333630", "text": "import numpy as np\nimport heapq\nimport itertools\nfrom scipy.sparse import csr_matrix\nfrom .dataiterator import DataIterator\nfrom backend import batch_random_choice\nfrom utils import typeassert\nfrom utils import timer\n\n\ndef random_choice(a, size=None, replace=True, p=None, exclusion=None):\n if exclusion is not None:\n if p is None:\n p = np.ones_like(a)\n else:\n p = np.array(p, copy=True)\n p = np.ndarray.flatten(p)\n p[exclusion] = 0\n p = p / np.sum(p)\n sample = np.random.choice(a, size=size, replace=replace, p=p)\n return sample\n\n\n@typeassert(matrix=csr_matrix)\ndef csr_to_user_dict(matrix):\n \"\"\"convert a scipy.sparse.csr_matrix to a dict,\n where the key is row number, and value is the\n non-empty index in each row.\n \"\"\"\n idx_value_dict = {}\n for idx, value in enumerate(matrix):\n if any(value.indices):\n idx_value_dict[idx] = value.indices.copy()\n return idx_value_dict\n\n\n# # TODO rewrite with cython or cpp\n# # @timer\n# @typeassert(matrix=csr_matrix, neg_num=int, fold_neg=bool)\n# def csr_to_pairwise(matrix, neg_num=1, fold_neg=False):\n# user_num, item_num = matrix.shape\n# all_items = np.arange(item_num)\n# user_list, pos_list, neg_list = [], [], []\n# for idx, value in enumerate(matrix):\n# if any(value.indices):\n# pos_items = value.indices.copy()\n# pos_len = len(pos_items)\n# if neg_num > 0: # sample negative items\n# neg_len = neg_num*pos_len\n# neg_item = random_choice(all_items, size=neg_len, exclusion=pos_items)\n# if not fold_neg: # unfold negative items\n# user_list.extend([idx]*neg_len)\n# pos_items = np.reshape(np.tile(pos_items, neg_num), newshape=[-1])\n# pos_list.extend(pos_items)\n# neg_list.extend(np.reshape(neg_item, newshape=[-1]))\n# else: # fold negative items\n# user_list.extend([idx]*pos_len)\n# pos_list.extend(pos_items)\n# neg_item = np.reshape(neg_item, newshape=[pos_len, neg_num]).tolist()\n# neg_list.extend(neg_item)\n# else: # do not sample negative items\n# user_list.extend([idx] * pos_len)\n# pos_list.extend(pos_items)\n#\n# return user_list, pos_list, neg_list\n\n\n@typeassert(matrix=csr_matrix, neg_num=int, fold_neg=bool)\ndef csr_to_pairwise(matrix, neg_num=1, fold_neg=False):\n all_user_list, all_pos_list, all_neg_list = [], [], []\n user_num, item_num = matrix.shape\n all_users = list(range(user_num))\n all_items = np.arange(item_num)\n all_users = DataIterator(all_users, batch_size=1024, shuffle=False, drop_last=False)\n if neg_num > 0: # sample negative items\n for bat_users in all_users:\n pos_items_list = [matrix[user].indices for user in bat_users]\n samples_size = [len(pos)*neg_num for pos in pos_items_list]\n neg_items_list = batch_random_choice(all_items, samples_size, replace=True, exclusion=pos_items_list)\n for idx, user in enumerate(bat_users):\n if not fold_neg: # unfold negative items\n all_user_list.extend([user]*samples_size[idx])\n pos_items = np.tile(pos_items_list[idx], neg_num).reshape([-1])\n all_pos_list.extend(pos_items)\n all_neg_list.extend(neg_items_list[idx].reshape([-1]))\n else: # fold negative items\n pos_len = len(pos_items_list[idx])\n all_user_list.extend([user]*pos_len)\n all_pos_list.extend(pos_items_list[idx].reshape([-1]))\n all_neg_list.extend(neg_items_list[idx].reshape([-1, neg_num]))\n else: # do not sample negative items\n for idx, value in enumerate(matrix):\n pos_items = value.indices\n pos_len = len(pos_items)\n all_user_list.extend([idx] * pos_len)\n all_pos_list.extend(pos_items)\n\n return all_user_list, all_pos_list, all_neg_list\n\n\n# TODO check\n@typeassert(matrix=csr_matrix)\ndef csr_to_pointwise(matrix, neg_num=1):\n user_num, item_num = matrix.shape\n all_items = np.arange(item_num)\n user_list, item_list, label_list = [], [], []\n for idx, value in enumerate(matrix):\n if any(value.indices):\n pos_items = value.indices.copy()\n pos_len = len(pos_items)\n if neg_num == 0:\n user_list.extend([idx]*pos_len)\n item_list.extend(pos_items.tolist())\n label_list.extend(len(pos_items)*[1.0])\n elif neg_num > 0:\n neg_len = neg_num*pos_len\n neg_items = random_choice(all_items, size=neg_len, exclusion=pos_items).tolist()\n\n user_list.extend([idx]*(neg_len+pos_len))\n item_list.extend(pos_items.tolist())\n label_list.extend(pos_len*[1.0])\n item_list.extend(neg_items)\n label_list.extend(neg_len*[0.0])\n else:\n raise ValueError(\"The parameter 'neg_num' is invalid!\")\n\n return user_list, item_list, label_list\n\n\ndef padding(input, value=0, max_len=None):\n if max_len is None:\n max_len = max([len(x) for x in input])\n output = np.full([len(input), max_len], value, dtype=int)\n for idx, x in enumerate(input):\n copy_len = max_len if len(x) > max_len else len(x)\n output[idx][:copy_len] = x[:copy_len]\n return output.tolist()\n\n\ndef argmax_top_k(a, top_k=50):\n ele_idx = heapq.nlargest(top_k, zip(a, itertools.count()))\n return np.array([idx for ele, idx in ele_idx], dtype=np.intc)\n\n", "sub_path": "utils/tools.py", "file_name": "tools.py", "file_ext": "py", "file_size_in_byte": 5782, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "numpy.ones_like", "line_number": 14, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.ndarray.flatten", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 17, "usage_type": "attribute"}, {"api_name": "numpy.sum", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.random.choice", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 20, "usage_type": "attribute"}, {"api_name": "utils.typeassert", "line_number": 24, "usage_type": "call"}, {"api_name": "scipy.sparse.csr_matrix", "line_number": 24, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 73, "usage_type": "call"}, {"api_name": "dataiterator.DataIterator", "line_number": 74, "usage_type": "call"}, {"api_name": "backend.batch_random_choice", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.tile", "line_number": 83, "usage_type": "call"}, {"api_name": "utils.typeassert", "line_number": 68, "usage_type": "call"}, {"api_name": "scipy.sparse.csr_matrix", "line_number": 68, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 105, "usage_type": "call"}, {"api_name": "utils.typeassert", "line_number": 102, "usage_type": "call"}, {"api_name": "scipy.sparse.csr_matrix", "line_number": 102, "usage_type": "name"}, {"api_name": "numpy.full", "line_number": 133, "usage_type": "call"}, {"api_name": "heapq.nlargest", "line_number": 141, "usage_type": "call"}, {"api_name": "itertools.count", "line_number": 141, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 142, "usage_type": "call"}, {"api_name": "numpy.intc", "line_number": 142, "usage_type": "attribute"}]}
+{"seq_id": "164246450", "text": "import json\nimport yaml\n\nfrom flask import request\nfrom flask_restplus import Namespace, Resource\n\nimport helpers.transformations as enhanced\n\nfrom db import dsl\nfrom providers import *\nfrom app.models import Payload\n\n\napi = Namespace('actions', description='Actions Endpoints')\n\n\nclass Actions(Resource):\n\n def post(self, action, uuid):\n \"\"\"Post Actions\"\"\"\n\n payload = Payload.where('uuid', uuid).first()\n\n if payload:\n content = json.loads(payload.payload)\n\n params = enhanced.map(\n dsl.file.integrations.get('actions').get(action),\n lambda t: enhanced.translate(\n t,\n payload=content.get('payload', {}),\n changes=request.get_json()\n )\n )\n\n provider = params.get('provider')\n response = globals()[provider.capitalize()](**params).run()\n\n return response\n\n\n return {}\n\n\napi.add_resource(\n Actions,\n '//',\n methods=['POST'])\n", "sub_path": "app/controllers/actions.py", "file_name": "actions.py", "file_ext": "py", "file_size_in_byte": 1061, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "flask_restplus.Namespace", "line_number": 14, "usage_type": "call"}, {"api_name": "flask_restplus.Resource", "line_number": 17, "usage_type": "name"}, {"api_name": "app.models.Payload.where", "line_number": 22, "usage_type": "call"}, {"api_name": "app.models.Payload", "line_number": 22, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 25, "usage_type": "call"}, {"api_name": "helpers.transformations.map", "line_number": 27, "usage_type": "call"}, {"api_name": "helpers.transformations", "line_number": 27, "usage_type": "name"}, {"api_name": "db.dsl.file.integrations.get", "line_number": 28, "usage_type": "call"}, {"api_name": "db.dsl.file", "line_number": 28, "usage_type": "attribute"}, {"api_name": "db.dsl", "line_number": 28, "usage_type": "name"}, {"api_name": "helpers.transformations.translate", "line_number": 29, "usage_type": "call"}, {"api_name": "helpers.transformations", "line_number": 29, "usage_type": "name"}, {"api_name": "flask.request.get_json", "line_number": 32, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 32, "usage_type": "name"}]}
+{"seq_id": "518835647", "text": "import sys\nimport json\nimport copy\nimport argparse\nfrom datetime import datetime\nfrom helper import time_string\nfrom helper import daterange\nfrom helper import date_string\nfrom helper import eprint\nfrom test_completion import get_test_completion as get_test_scores\nfrom start_end import commit_data\n\n\ndef jsonify(test_data):\n \"\"\"Formats data for /classProgress endpoint\n\n Converts information in **data** into an appropriately formatted json \n for the /classProgress endpoint \n\n **Args**:\n **data** (dict): A dictionary of the following format: ::\n\n {\n \"name1\": {\n \"Test1\": (\"P\" or \"F\"),\n ...\n },\n ...\n }\n\n **Return**:\n dict: A dictionary of histogram data split into 20% bins: ::\n\n {\n \"0-20%\": int,\n \"20-40%\": int,\n \"40-60%\": int,\n \"60-80%\": int,\n \"80-100%\": int\n }\n\n where each percentage bin contains a value 0 <= int <= 100\n\n \"\"\"\n histogram_data = {\"0-20%\": 0, \"20-40%\": 0, \"40-60%\": 0, \"60-80%\": 0, \"80-100%\": 0}\n for student in test_data:\n info = test_data[student]\n if info[\"total\"] <= 20:\n histogram_data[\"0-20%\"] += 1\n elif info[\"total\"] <= 40:\n histogram_data[\"20-40%\"] += 1\n elif info[\"total\"] <= 60:\n histogram_data[\"40-60%\"] += 1\n elif info[\"total\"] <= 80:\n histogram_data[\"60-80%\"] += 1\n elif info[\"total\"] <= 100:\n histogram_data[\"80-100%\"] += 1\n return json.dumps(histogram_data)\n\n\ndef merge_data(visible, hidden):\n \"\"\"Sums the values in **visible** and **hidden** for each bin\"\"\"\n visible = json.loads(visible)\n hidden = json.loads(hidden)\n for key in visible:\n visible[key] += hidden[key]\n return json.dumps(visible)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"visible\", help=\"path to visible test score file\")\n parser.add_argument(\"hidden\", help=\"path to hidden test score file\")\n\n args = parser.parse_args()\n\n visible_test_score_file = open(args.visible, \"r\")\n hidden_test_score_file = open(args.hidden, \"r\")\n\n visible_data = get_test_scores(visible_test_score_file)\n hidden_data = get_test_scores(hidden_test_score_file)\n # print(visible_data)\n\n formatted_visible = jsonify(visible_data)\n formatted_hidden = jsonify(hidden_data)\n api_json = merge_data(formatted_visible, formatted_hidden)\n print(api_json)\n", "sub_path": "python/get_class_progress.py", "file_name": "get_class_progress.py", "file_ext": "py", "file_size_in_byte": 2579, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "json.dumps", "line_number": 58, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 63, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 64, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 67, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 71, "usage_type": "call"}, {"api_name": "test_completion.get_test_completion", "line_number": 80, "usage_type": "call"}, {"api_name": "test_completion.get_test_completion", "line_number": 81, "usage_type": "call"}]}
+{"seq_id": "544539502", "text": "import logging\nfrom datetime import datetime\n\nfrom telegram.ext import Updater, CommandHandler, CallbackQueryHandler\nfrom telegram import InlineKeyboardButton, InlineKeyboardMarkup\nfrom app.config import API_KEY, PROXY\nfrom app import rzd\nfrom app.model import Subscribes\n\nlogging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s',\n level=logging.INFO,\n filename='bot.log'\n )\nCHATS_TRAINS = {}\n\n\ndef get_train_button(train):\n return '(%s) %s %s' % (\n train.number, train.departure_time.strftime(\"%H:%M %d.%m\"), train.arrival_time.strftime(\"%H:%M %d.%m\"))\n\n\ndef get_train_info(train):\n result = '(%s) %s \\nОтправление: %s\\nПрибытие: %s\\n\\n' % (\n train.number, train.title, train.departure_time.strftime(\"%H:%M %d.%m.%Y\"),\n train.arrival_time.strftime(\"%H:%M %d.%m.%Y\"))\n return result + '\\n'.join([str(seat) for seat in dict(train.seats).values()])\n\n\ndef get_train(route_from, route_to, route_date):\n with rzd.RzdFetcher() as fetcher:\n train_list = fetcher.trains(\n route_from.upper(),\n route_to.upper(),\n rzd.TimeRange(\n datetime(route_date.year, route_date.month,\n route_date.day,\n 0, 0),\n datetime(route_date.year, route_date.month,\n route_date.day, 23, 59),\n )\n )\n return train_list\n\n\ndef build_menu(buttons,\n n_cols,\n header_buttons=None,\n footer_buttons=None):\n menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)]\n if header_buttons:\n menu.insert(0, header_buttons)\n if footer_buttons:\n menu.append(footer_buttons)\n return menu\n\n\ndef get_route(bot, update):\n text = update.message.text.split()\n logging.info(text)\n if len(text) == 1:\n update.message.reply_text('Введите значение после команды')\n rout_from = text[1]\n route_to = text[2]\n route_date = datetime.strptime(text[3], \"%d-%m-%y\")\n trains = get_train(rout_from, route_to, route_date)\n CHATS_TRAINS[update.message.chat.id] = {train.number: train for train in trains}\n button_list = [InlineKeyboardButton(get_train_button(train), callback_data=train.number)\n for train in trains\n ]\n reply_markup = InlineKeyboardMarkup(build_menu(button_list, n_cols=1))\n bot.send_message(update.message.chat.id, \"Список поездов\", reply_markup=reply_markup)\n # except Exception as e:\n # logging.info(e)\n # update.message.reply_text('не правильно введена команда')\n\n\ndef get_route2(bot, update):\n text = update.message.text.split()\n logging.info(text)\n try:\n if len(text) == 1:\n update.message.reply_text('Введите значение после команды')\n rout_from = text[1]\n route_to = text[2]\n route_date = datetime.strptime(text[3], \"%d-%m-%y\")\n trains = get_train(rout_from, route_to, route_date)\n CHATS_TRAINS[update.message.chat.id] = {train.number: train for train in trains}\n message = '\\n'.join([str(train) for train in trains])\n button_list = [InlineKeyboardButton(train.number, callback_data=train.number)\n for train in trains\n ]\n reply_markup = InlineKeyboardMarkup(build_menu(button_list, n_cols=1))\n bot.send_message(update.message.chat.id, \"Список поездов: \\n{}\".format(message), reply_markup=reply_markup)\n except Exception as e:\n logging.info(e)\n update.message.reply_text(\n 'не правильно введена команда\\nвведите команду в формате\\nотправление прибытие дата\\nдата в формате дд-мм-гг')\n\n\ndef callbackHandler(bot, call):\n logging.info(call)\n logging.info(CHATS_TRAINS)\n if call.callback_query:\n if call.callback_query.data:\n if CHATS_TRAINS[call.callback_query.message.chat.id] and call.callback_query.data in CHATS_TRAINS[\n call.callback_query.message.chat.id].keys():\n bot.send_message(chat_id=call.callback_query.message.chat.id, text=get_train_info(\n CHATS_TRAINS[call.callback_query.message.chat.id][call.callback_query.data]))\n\n # bot.edit_message_text(chat_id=call.callback_query.message.chat.id,\n # message_id=call.callback_query.message.message_id, text=call.callback_query.data)\n\n\ndef subscribe(bot, update):\n text = update.message.text.split()\n logging.info(text)\n if len(text) == 1:\n update.message.reply_text('Введите значение после команды')\n route_from = text[1]\n route_to = text[2]\n route_date = datetime.strptime(text[3], \"%d-%m-%y\")\n _subscribe = Subscribes(chat_id=update.message.chat.id, route_from=route_from, route_to=route_to, route_date=route_date)\n\n\ndef main():\n mybot = Updater(API_KEY, request_kwargs=PROXY)\n\n logging.info('Бот запускается')\n dp = mybot.dispatcher\n dp.add_handler(CommandHandler('route', get_route))\n dp.add_handler(CommandHandler('subscribe', subscribe))\n dp.add_handler(CallbackQueryHandler(callbackHandler))\n\n mybot.start_polling()\n mybot.idle()\n\n\nif __name__ == '__main__':\n main()\n", "sub_path": "app/bot.py", "file_name": "bot.py", "file_ext": "py", "file_size_in_byte": 5510, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "logging.basicConfig", "line_number": 10, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 11, "usage_type": "attribute"}, {"api_name": "app.rzd.RzdFetcher", "line_number": 30, "usage_type": "call"}, {"api_name": "app.rzd", "line_number": 30, "usage_type": "name"}, {"api_name": "app.rzd.TimeRange", "line_number": 34, "usage_type": "call"}, {"api_name": "app.rzd", "line_number": 34, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 35, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 38, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 59, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 64, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 64, "usage_type": "name"}, {"api_name": "telegram.InlineKeyboardButton", "line_number": 67, "usage_type": "call"}, {"api_name": "telegram.InlineKeyboardMarkup", "line_number": 70, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 79, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 85, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 85, "usage_type": "name"}, {"api_name": "telegram.InlineKeyboardButton", "line_number": 89, "usage_type": "call"}, {"api_name": "telegram.InlineKeyboardMarkup", "line_number": 92, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 95, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 101, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 102, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 116, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 121, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 121, "usage_type": "name"}, {"api_name": "app.model.Subscribes", "line_number": 122, "usage_type": "call"}, {"api_name": "telegram.ext.Updater", "line_number": 126, "usage_type": "call"}, {"api_name": "app.config.API_KEY", "line_number": 126, "usage_type": "argument"}, {"api_name": "app.config.PROXY", "line_number": 126, "usage_type": "name"}, {"api_name": "logging.info", "line_number": 128, "usage_type": "call"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 130, "usage_type": "call"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 131, "usage_type": "call"}, {"api_name": "telegram.ext.CallbackQueryHandler", "line_number": 132, "usage_type": "call"}]}
+{"seq_id": "99193920", "text": "from PySide2 import QtCore\nfrom PySide2 import QtGui\nfrom PySide2 import QtWidgets\nfrom shiboken2 import wrapInstance\n\nimport maya.cmds as cmds\nimport maya.mel as mel\nimport maya.OpenMayaUI as omui\n\n\ndef maya_main_window():\n \"\"\"\n Return the Maya main window widget as a Python object\n \"\"\"\n main_window_ptr = omui.MQtUtil.mainWindow()\n return wrapInstance(long(main_window_ptr), QtWidgets.QWidget)\n\n\nclass TimelineOverlay(QtWidgets.QWidget):\n\n KEYFRAME_COLOR = QtGui.QColor(QtCore.Qt.green)\n\n def __init__(self):\n self.time_control = mel.eval(\"$tempVar = $gPlayBackSlider\")\n time_control_ptr = omui.MQtUtil.findControl(self.time_control)\n time_control_widget = wrapInstance(long(time_control_ptr), QtWidgets.QWidget)\n\n super(TimelineOverlay, self).__init__(time_control_widget)\n\n self.frame_times = [1, 6, 8, 10, 19, 30, 39, 50, 51, 52, 53, 54, 120]\n\n self.set_context_menu_enabled(False)\n\n def add_frame(self):\n current_time = cmds.currentTime(q=True)\n if current_time not in self.frame_times:\n self.frame_times.append(current_time)\n self.update()\n\n def add_frames(self):\n print(\"TODO: Add Frames\")\n\n def remove_frame(self):\n current_time = cmds.currentTime(q=True)\n if current_time in self.frame_times:\n self.frame_times.remove(current_time)\n self.update()\n\n def remove_frames(self):\n print(\"TODO: Remove Frames\")\n\n def set_context_menu_enabled(self, enabled):\n self.context_menu_enabled = enabled\n\n if enabled:\n print(\"TODO: Add Context Menu\")\n\n def paintEvent(self, paint_event):\n parent = self.parentWidget()\n if parent:\n self.setGeometry(parent.geometry())\n\n range_start = cmds.playbackOptions(q=True, minTime=True)\n range_end = cmds.playbackOptions(q=True, maxTime=True)\n displayed_frame_count = range_end - range_start + 1\n\n padding = self.width() * 0.005\n frame_width = (self.width() * 0.99) / displayed_frame_count\n\n frame_height = 0.333 * self.height()\n frame_y = self.height() - frame_height\n\n painter = QtGui.QPainter(self)\n\n pen = painter.pen()\n pen.setWidth(1)\n pen.setColor(TimelineOverlay.KEYFRAME_COLOR)\n painter.setPen(pen)\n\n fill_color = QtGui.QColor(TimelineOverlay.KEYFRAME_COLOR)\n fill_color.setAlpha(63)\n\n for frame_time in self.frame_times:\n frame_x = padding + ((frame_time - range_start) * frame_width) + 0.5\n\n painter.fillRect(frame_x, frame_y, frame_width, frame_height, fill_color)\n painter.drawRect(frame_x, frame_y, frame_width, frame_height)\n\n\n\nif __name__ == \"__main__\":\n try:\n TimelineOverlayDialog.delete_overlays() # pylint: disable=E0601\n except:\n pass\n\n\nclass TimelineOverlayDialog(QtWidgets.QDialog):\n\n WINDOW_TITLE = \"Timeline Overlay\"\n\n timeline_overlay = None\n\n @classmethod\n def delete_overlays(cls):\n if TimelineOverlayDialog.timeline_overlay:\n TimelineOverlayDialog.timeline_overlay.setParent(None)\n TimelineOverlayDialog.timeline_overlay.deleteLater()\n TimelineOverlayDialog.timeline_overlay = None\n\n def __init__(self, parent=maya_main_window()):\n super(TimelineOverlayDialog, self).__init__(parent)\n\n self.setWindowTitle(self.WINDOW_TITLE)\n if cmds.about(ntOS=True):\n self.setWindowFlags(self.windowFlags() ^ QtCore.Qt.WindowContextHelpButtonHint)\n elif cmds.about(macOS=True):\n self.setWindowFlags(QtCore.Qt.Tool)\n\n self.setMinimumSize(280, 160)\n\n self.create_widgets()\n self.create_layout()\n self.create_connections()\n\n self.set_overlay_visible(True)\n\n def create_widgets(self):\n self.overlay_visible_cb = QtWidgets.QCheckBox(\"Show Overlay\")\n\n self.context_menu_cb = QtWidgets.QCheckBox(\"Context Menu Enabled\")\n self.context_menu_cb.setChecked(True)\n\n self.add_frame_btn = QtWidgets.QPushButton(\"Add Frame\")\n self.remove_frame_btn = QtWidgets.QPushButton(\"Remove Frame\")\n\n self.close_btn = QtWidgets.QPushButton(\"Close\")\n\n def create_layout(self):\n frame_layout = QtWidgets.QHBoxLayout()\n frame_layout.setSpacing(4)\n frame_layout.addWidget(self.add_frame_btn)\n frame_layout.addWidget(self.remove_frame_btn)\n frame_layout.addStretch()\n\n overlay_layout = QtWidgets.QVBoxLayout()\n overlay_layout.addWidget(self.overlay_visible_cb)\n overlay_layout.addWidget(self.context_menu_cb)\n overlay_layout.addLayout(frame_layout)\n\n options_grp = QtWidgets.QGroupBox(\"Overlay Options\")\n options_grp.setLayout(overlay_layout)\n\n btn_layout = QtWidgets.QHBoxLayout()\n btn_layout.addStretch()\n btn_layout.addWidget(self.close_btn)\n\n main_layout = QtWidgets.QVBoxLayout(self)\n main_layout.setContentsMargins(2, 2, 2, 2)\n main_layout.addWidget(options_grp)\n main_layout.addStretch()\n main_layout.addLayout(btn_layout)\n\n def create_connections(self):\n self.overlay_visible_cb.toggled.connect(self.set_overlay_visible)\n\n self.close_btn.clicked.connect(self.close)\n\n def set_overlay_visible(self, visible):\n if visible:\n if not TimelineOverlayDialog.timeline_overlay:\n TimelineOverlayDialog.timeline_overlay = TimelineOverlay()\n TimelineOverlayDialog.timeline_overlay.set_context_menu_enabled(self.context_menu_cb.isChecked())\n\n self.context_menu_cb.toggled.connect(TimelineOverlayDialog.timeline_overlay.set_context_menu_enabled)\n self.add_frame_btn.clicked.connect(TimelineOverlayDialog.timeline_overlay.add_frame)\n self.remove_frame_btn.clicked.connect(TimelineOverlayDialog.timeline_overlay.remove_frame)\n\n\n if TimelineOverlayDialog.timeline_overlay:\n TimelineOverlayDialog.timeline_overlay.setVisible(visible)\n\n self.overlay_visible_cb.setChecked(visible)\n\n\n\nif __name__ == \"__main__\":\n\n try:\n overlay_dialog.close() # pylint: disable=E0601\n overlay_dialog.deleteLater()\n except:\n pass\n\n overlay_dialog = TimelineOverlayDialog()\n overlay_dialog.show()\n", "sub_path": "CZ_Tutorials/010_PySide2 for Maya (Vol. 3)/22-pyside2_for_maya_vol_3-custom_maya_overlays_part_4/timeline_overlay_dialog_start.py", "file_name": "timeline_overlay_dialog_start.py", "file_ext": "py", "file_size_in_byte": 6422, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "maya.OpenMayaUI.MQtUtil.mainWindow", "line_number": 15, "usage_type": "call"}, {"api_name": "maya.OpenMayaUI.MQtUtil", "line_number": 15, "usage_type": "attribute"}, {"api_name": "maya.OpenMayaUI", "line_number": 15, "usage_type": "name"}, {"api_name": "shiboken2.wrapInstance", "line_number": 16, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QWidget", "line_number": 16, "usage_type": "attribute"}, {"api_name": "PySide2.QtWidgets", "line_number": 16, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QWidget", "line_number": 19, "usage_type": "attribute"}, {"api_name": "PySide2.QtWidgets", "line_number": 19, "usage_type": "name"}, {"api_name": "PySide2.QtGui.QColor", "line_number": 21, "usage_type": "call"}, {"api_name": "PySide2.QtGui", "line_number": 21, "usage_type": "name"}, {"api_name": "PySide2.QtCore.Qt", "line_number": 21, "usage_type": "attribute"}, {"api_name": "PySide2.QtCore", "line_number": 21, "usage_type": "name"}, {"api_name": "maya.mel.eval", "line_number": 24, "usage_type": "call"}, {"api_name": "maya.mel", "line_number": 24, "usage_type": "name"}, {"api_name": "maya.OpenMayaUI.MQtUtil.findControl", "line_number": 25, "usage_type": "call"}, {"api_name": "maya.OpenMayaUI.MQtUtil", "line_number": 25, "usage_type": "attribute"}, {"api_name": "maya.OpenMayaUI", "line_number": 25, "usage_type": "name"}, {"api_name": "shiboken2.wrapInstance", "line_number": 26, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets.QWidget", "line_number": 26, "usage_type": "attribute"}, {"api_name": "PySide2.QtWidgets", "line_number": 26, "usage_type": "name"}, {"api_name": "maya.cmds.currentTime", "line_number": 35, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 35, "usage_type": "name"}, {"api_name": "maya.cmds.currentTime", "line_number": 44, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 44, "usage_type": "name"}, {"api_name": "maya.cmds.playbackOptions", "line_number": 63, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 63, "usage_type": "name"}, {"api_name": "maya.cmds.playbackOptions", "line_number": 64, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 64, "usage_type": "name"}, {"api_name": "PySide2.QtGui.QPainter", "line_number": 73, "usage_type": "call"}, {"api_name": "PySide2.QtGui", "line_number": 73, "usage_type": "name"}, {"api_name": "PySide2.QtGui.QColor", "line_number": 80, "usage_type": "call"}, {"api_name": "PySide2.QtGui", "line_number": 80, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QDialog", "line_number": 98, "usage_type": "attribute"}, {"api_name": "PySide2.QtWidgets", "line_number": 98, "usage_type": "name"}, {"api_name": "maya.cmds.about", "line_number": 115, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 115, "usage_type": "name"}, {"api_name": "PySide2.QtCore.Qt", "line_number": 116, "usage_type": "attribute"}, {"api_name": "PySide2.QtCore", "line_number": 116, "usage_type": "name"}, {"api_name": "maya.cmds.about", "line_number": 117, "usage_type": "call"}, {"api_name": "maya.cmds", "line_number": 117, "usage_type": "name"}, {"api_name": "PySide2.QtCore.Qt", "line_number": 118, "usage_type": "attribute"}, {"api_name": "PySide2.QtCore", "line_number": 118, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QCheckBox", "line_number": 129, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 129, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QCheckBox", "line_number": 131, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 131, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QPushButton", "line_number": 134, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 134, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QPushButton", "line_number": 135, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 135, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QPushButton", "line_number": 137, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 137, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QHBoxLayout", "line_number": 140, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 140, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QVBoxLayout", "line_number": 146, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 146, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QGroupBox", "line_number": 151, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 151, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QHBoxLayout", "line_number": 154, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 154, "usage_type": "name"}, {"api_name": "PySide2.QtWidgets.QVBoxLayout", "line_number": 158, "usage_type": "call"}, {"api_name": "PySide2.QtWidgets", "line_number": 158, "usage_type": "name"}]}
+{"seq_id": "555712479", "text": "# -*- coding: utf-8 -*-\n#\n# Copyright 2017 Xilosopher\n#\n# Author: Moro JoJo\n\n\nimport os\nimport json\nfrom utils.logger import framework_log\n\n\ndef get_config_path():\n os_path = os.getcwd()\n return os_path + '/config/config.json'\n\n\ndef load_config(config_path):\n if config_path is None:\n return {}\n if not os.path.exists(config_path):\n framework_log.error(\"config.json not found in {config_path}\").format(config_path)\n return False\n with open(config_path) as json_file:\n config = json.load(json_file)\n return config\n\n", "sub_path": "utils/config.py", "file_name": "config.py", "file_ext": "py", "file_size_in_byte": 564, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "os.getcwd", "line_number": 14, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path", "line_number": 21, "usage_type": "attribute"}, {"api_name": "utils.logger.framework_log.error", "line_number": 22, "usage_type": "call"}, {"api_name": "utils.logger.framework_log", "line_number": 22, "usage_type": "name"}, {"api_name": "json.load", "line_number": 25, "usage_type": "call"}]}
+{"seq_id": "545900791", "text": "#!/usr/bin/env python\n# coding=utf-8\nimport numpy as np\n\nfrom ..utils import NAG, GD\nfrom .centralized_optimizer import CentralizedOptimizer\n\nclass ADMM(CentralizedOptimizer):\n '''ADMM for consensus optimization described in http://www.princeton.edu/~yc5/ele522_optimization/lectures/ADMM.pdf'''\n\n def __init__(self, p, n_iters=100, rho=0.1, x_0=None, W=None, local_n_iters=100, delta=None, local_optimizer='NAG', verbose=False):\n super().__init__(p, n_iters, x_0, W, verbose)\n self.rho = rho\n self.local_optimizer = local_optimizer\n self.local_n_iters = local_n_iters\n self.Lambda = np.random.rand(self.dim, self.n_agent)\n self.delta = delta\n\n def update(self):\n self.n_comm[self.t] += 2*self.n_agent\n\n x = np.random.rand(self.dim, self.n_agent)\n z = self.x # Using notations from the tutorial\n\n for i in range(self.n_agent):\n\n def _grad(tmp):\n return self.grad(tmp, i) + self.rho / 2 * (tmp - z) + self.Lambda[:, i] / 2\n\n if self.local_optimizer == \"NAG\":\n x[:, i], _ = NAG(_grad, self.x.copy(), self.L + self.rho, self.sigma + self.rho, self.local_n_iters)\n else:\n if self.delta is not None:\n x[:, i], _ = GD(_grad, self.x.copy(), self.delta, self.local_n_iters)\n else:\n x[:, i], _ = GD(_grad, self.x.copy(), 2/(self.L + self.rho + self.sigma + self.rho), self.local_n_iters)\n\n z = (x + self.Lambda).mean(axis=1)\n for i in range(self.n_agent):\n self.Lambda[:, i] += self.rho * (x[:, i] - self.x)\n self.x = z # Update\n", "sub_path": "optimizers/centralized/ADMM.py", "file_name": "ADMM.py", "file_ext": "py", "file_size_in_byte": 1662, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "centralized_optimizer.CentralizedOptimizer", "line_number": 8, "usage_type": "name"}, {"api_name": "numpy.random.rand", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 16, "usage_type": "attribute"}, {"api_name": "numpy.random.rand", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 22, "usage_type": "attribute"}, {"api_name": "utils.NAG", "line_number": 31, "usage_type": "call"}, {"api_name": "utils.GD", "line_number": 34, "usage_type": "call"}, {"api_name": "utils.GD", "line_number": 36, "usage_type": "call"}]}
+{"seq_id": "491341691", "text": "import importlib\nimport sys\nimport time\nimport numpy as np\nimportlib.reload(sys)\n\nfrom sklearn.grid_search import GridSearchCV \n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.externals import joblib\n\n\nx_test = []\ny_test = []\n\nff=open('/home/rxx/quant/stock/temp1/20170221','r')\nline1=ff.readline()\nwhile line1:\n\ttoken1=line1.strip().split(' ')\n\ttemp1 = []\n\tfor i in range(1,210):\n\t\ttemp1.append(token1[i])\n\tx_test.append(temp1)\n\tif token1[210] >= '0':\n\t\ty_test.append(1)\n\telse:\n\t\ty_test.append(0)\n\tline1=ff.readline()\nprint (\"data done~\")\n\nclf=joblib.load(\"train_model.m\")\nprediction = clf.predict(x_test)\nprint (\"Accuracy:\\t\", (y_test == clf.predict(x_test)).mean())\n\nprint(prediction == y_test)\nprint(clf.feature_importances_)\nprint('all done')", "sub_path": "数据处理/randomforest_5.py", "file_name": "randomforest_5.py", "file_ext": "py", "file_size_in_byte": 766, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "importlib.reload", "line_number": 5, "usage_type": "call"}, {"api_name": "sklearn.externals.joblib.load", "line_number": 31, "usage_type": "call"}, {"api_name": "sklearn.externals.joblib", "line_number": 31, "usage_type": "name"}]}
+{"seq_id": "44016589", "text": "import freenect\nimport cv2\nimport numpy as np\nimport imutils\nfrom cameradata.utils.perspTransform import four_point_transform\nfrom cameradata.utils.get_pts_gui import get_points\nfrom time import sleep\nfrom operator import itemgetter\n\n\ndef get_video(pts):\n array, _ = freenect.sync_get_video()\n array = cv2.cvtColor(array, cv2.COLOR_RGB2BGR)\n return four_point_transform(array, pts)\n\n\ndef get_depth(pts):\n array, _ = freenect.sync_get_depth()\n array = array.astype(np.uint8)\n return four_point_transform(array, pts)\n\n\ndef get_ball_reference(pts_depth, pts_rgb):\n \"\"\"Frame with no balls and no cue\"\"\"\n img_depth = get_depth(pts_depth)\n img = get_video(pts_rgb)\n return img_depth, img\n\n\ndef get_ball_diff(pts, Ra):\n return cv2.absdiff(get_depth(pts), Ra)\n\n\ndef get_ball_contours(pts, Ra):\n ballFrame = get_ball_diff(pts, Ra)\n # cv2.imshow(\"2\", imutils.resize(ballFrame, height=320))\n\n Bw = 29\n Tb = (13 / 16) * Bw\n ballBin = np.zeros(ballFrame.shape, np.uint8)\n ballBin[ballFrame > Tb] = 255\n # cv2.imshow(\"3\", imutils.resize(ballBin, height=320))\n\n # ballSmooth = cv2.medianBlur(ballBin, 5)\n ballErode = cv2.erode(ballBin, np.ones((7, 7), np.uint8))\n # cv2.imshow(\"4\", imutils.resize(ballErode, height=320))\n\n _, contours, hierarchy = cv2.findContours(ballErode, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n return contours\n\n\ndef draw_contour_circles(img, contours):\n n = 0\n for i in range(len(contours)):\n if cv2.contourArea(contours[i]) > 110:\n (x, y), radius = cv2.minEnclosingCircle(contours[i])\n center = (int(x), int(y))\n radius = int(radius)\n img = cv2.drawContours(img, contours, i, 255, 1)\n img = cv2.circle(img, center, radius + 3, 255, 1)\n img = cv2.rectangle(img, (int(x - 1), int(y - 1)), (int(x + 1), int(y + 1)), 255)\n n += 1\n return img\n\n\ndef get_white_ball(img_rgb, img_depth, contours):\n img_rgb = cv2.resize(img_rgb, (img_depth.shape[1], img_depth.shape[0]))\n # Initialize empty list\n # global max_cnt_index, max_cnt\n lst_intensities = []\n\n # For each list of contour points...\n\n for i in range(len(contours)):\n if cv2.contourArea(contours[i]) > 110:\n # Create a mask image that contains the contour filled in\n cimg = np.zeros_like(img_rgb)\n cimg = cv2.resize(cimg, (img_depth.shape[1], img_depth.shape[0]))\n cv2.drawContours(cimg, contours, i, color=255, thickness=-1)\n\n # Access the image pixels and create a 1D numpy array then add to list\n pts = np.where(cimg == 255)\n lst_intensities.append((i, img_rgb[pts[0], pts[1]]))\n\n # print(lst_intensities)\n\n sum_val = []\n Sum = 0\n for i, cnt in lst_intensities:\n for val in cnt:\n # print(val)\n Sum += sum(val)\n sum_val.append((i, Sum))\n Sum = 0\n #print(sum_val)\n\n max_cnt_index = None\n max_cnt = None\n if len(sum_val) > 0:\n max_cnt_index = max(sum_val, key=itemgetter(1))[0]\n cv2.drawContours(img_rgb, contours, max_cnt_index, color=(255, 120, 0), thickness=-1)\n max_cnt = contours[max_cnt_index]\n\n return max_cnt_index, max_cnt, img_rgb\n\n\npts_depth = get_points(1)\npts_rgb = get_points(0)\nRa, Ra_rgb = get_ball_reference(pts_depth, pts_rgb)\n# cv2.imshow(\"1\", imutils.resize(Ra, height=320))\nsleep(0)\n\nwhile 1:\n contours = get_ball_contours(pts_depth, Ra)\n\n img_depth = get_depth(pts_depth)\n img_rgb = get_video(pts_rgb)\n\n img_rgb = cv2.resize(img_rgb, (img_depth.shape[1], img_depth.shape[0]))\n # image1 = cv2.drawContours(image1, contours, -1, 255, 2)\n\n img_depth = draw_contour_circles(img_depth, contours)\n img_rgb = draw_contour_circles(img_rgb, contours)\n\n cv2.imshow(\"5\", imutils.resize(img_depth, height=320))\n\n max_cnt_idx, max_cnt, img_rgb = get_white_ball(img_rgb, img_depth, contours)\n\n cv2.imshow(\"6\", imutils.resize(img_rgb, height=320))\n\n k = cv2.waitKey(5) & 0xFF\n if k == 27:\n break\ncv2.destroyAllWindows()\n", "sub_path": "cameradata/ball_detect/ball_detect.py", "file_name": "ball_detect.py", "file_ext": "py", "file_size_in_byte": 4082, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "freenect.sync_get_video", "line_number": 12, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 13, "usage_type": "call"}, {"api_name": "cv2.COLOR_RGB2BGR", "line_number": 13, "usage_type": "attribute"}, {"api_name": "cameradata.utils.perspTransform.four_point_transform", "line_number": 14, "usage_type": "call"}, {"api_name": "freenect.sync_get_depth", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 19, "usage_type": "attribute"}, {"api_name": "cameradata.utils.perspTransform.four_point_transform", "line_number": 20, "usage_type": "call"}, {"api_name": "cv2.absdiff", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 40, "usage_type": "attribute"}, {"api_name": "cv2.erode", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 45, "usage_type": "attribute"}, {"api_name": "cv2.findContours", "line_number": 48, "usage_type": "call"}, {"api_name": "cv2.RETR_TREE", "line_number": 48, "usage_type": "attribute"}, {"api_name": "cv2.CHAIN_APPROX_SIMPLE", "line_number": 48, "usage_type": "attribute"}, {"api_name": "cv2.contourArea", "line_number": 55, "usage_type": "call"}, {"api_name": "cv2.minEnclosingCircle", "line_number": 56, "usage_type": "call"}, {"api_name": "cv2.drawContours", "line_number": 59, "usage_type": "call"}, {"api_name": "cv2.circle", "line_number": 60, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 61, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 67, "usage_type": "call"}, {"api_name": "cv2.contourArea", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 77, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 78, "usage_type": "call"}, {"api_name": "cv2.drawContours", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 82, "usage_type": "call"}, {"api_name": "operator.itemgetter", "line_number": 100, "usage_type": "call"}, {"api_name": "cv2.drawContours", "line_number": 101, "usage_type": "call"}, {"api_name": "cameradata.utils.get_pts_gui.get_points", "line_number": 107, "usage_type": "call"}, {"api_name": "cameradata.utils.get_pts_gui.get_points", "line_number": 108, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 111, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 119, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 125, "usage_type": "call"}, {"api_name": "imutils.resize", "line_number": 125, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 129, "usage_type": "call"}, {"api_name": "imutils.resize", "line_number": 129, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 131, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 134, "usage_type": "call"}]}
+{"seq_id": "245615139", "text": "import csv\nimport shutil\nfrom splinter import Browser\nimport time\nimport os\nimport sys\nsys.path.append('../')\nimport gsheet\n\n# https://docs.google.com/spreadsheets/d/19_IaGTfPGtGxLoO-Rlc-Ear6A0R0vL0WtZqe5EIskr0/edit#gid=1338425418\n# \"auto realestate report\"\nspreadsheetId = \"19_IaGTfPGtGxLoO-Rlc-Ear6A0R0vL0WtZqe5EIskr0\"\n\ncategories = [\n 'Rent Income',\n 'Mortgage',\n 'Association Fees',\n 'Repairs',\n 'Management Fees',\n 'Commissions',\n 'Taxes',\n 'Utilities',\n 'Insurance',\n 'Cleaning and Maintenance',\n 'Other Income']\n\ncategory_redfines = {'Repairs Income': 'Repairs', 'Utility Income': 'Utilities',\n 'Insurance': 'Insurance',\n 'Cleaning and Maint Income': 'Maintenance'}\n\nignore_categories = ['Owner Draw', 'Owner Contribution']\n\nseries = {\"5650 E Sahara Ave 2063\": \"B\",\n \"8073 Palace Monaco Ave\": \"B\",\n \"10550 W Alexander Rd 1130\": \"A\",\n \"50 E Serene Ave 212\": \"D\"}\nnickname = {\"5650 E Sahara Ave 2063\": \"Terrasanta\",\n \"8073 Palace Monaco Ave\": \"Palace Monaco\",\n \"10550 W Alexander Rd 1130\": \"Chateau Versailles\",\n \"50 E Serene Ave 212\": \"Serene\"}\n\ndownload_dir = \"/Users/eleanorwen/Downloads/\"\n\noutput_dir = './output/'\nraw_dir = './output/raw/'\n\nentity_decoder = {'Cardinal_A': ['ellie.wen@gmail.com', '1'],\n 'Cardinal_B': ['ellie.wen@gmail.com', '2'],\n 'Cardinal_C': ['gegkat@gmail.com', '1'],\n 'Cardinal_D': ['gegkat@gmail.com', '2'],\n 'Ellie_Wen': ['ellie.wen@gmail.com', '3'],\n 'Greg_Katz': ['gegkat@gmail.com', '3'],\n 'You_Me': ['gegkat@gmail.com', '4']}\n\nirow_dict = {'ROS':[0, 1, 3, 9, 10, 12, 14, 16], # Rental Owner Statement\n 'RR': [0, 2, 9, 7] # Rent Roll\n }\n\ndownload_report_name_dict = {'ROS': 'Rental_Owner_Statement.csv',\n 'RR': 'Rent_Roll.csv'}\n\ndef rows2cols(table_data):\n headers = table_data[0]\n data = table_data[1:]\n cols = {}\n for col in headers:\n cols[col] = []\n for row in data:\n for col in range(len(headers)):\n cols[headers[col]].append(row[col])\n return cols\n\ndef str2float(l):\n return [float(i) for i in l]\n\ndef breakout_mortgage(cols):\n N = len(cols['glAccountName'])\n for i in range(N):\n cat = cols['glAccountName'][i]\n payee = cols['payeeName'][i]\n if cat == 'Owner Draw' and 'Cardinal Investments LLC' not in payee:\n cols['glAccountName'][i] = 'Mortgage'\n return cols\n\ndef group(cols):\n props = {}\n N = len(cols['glAccountName'])\n for i in range(N):\n #print(props)\n cat = cols['glAccountName'][i]\n if cat in category_redfines:\n cat = category_redfines[cat]\n amount = cols['amount'][i]\n address = cols['buildingName'][i]\n if address in props:\n if cat in props[address]:\n props[address][cat] += amount\n else:\n if cat not in ignore_categories:\n print(\"category {} not recognized\".format(cat))\n else:\n props[address] = {}\n for cat in categories:\n #print(cat)\n props[address][cat] = 0\n #print(props)\n return props\n\ndef period_time_struct(date):\n curr_time_sec = time.time()\n curr_time_struct = time.localtime(curr_time_sec)\n if date: # date is not empty\n month = date[0]\n year = date[1]\n else:\n month = curr_time_struct.tm_mon\n year = curr_time_struct.tm_year\n\n # Go to previous month if not past the 15th\n if curr_time_struct.tm_mday < 10:\n month -= 1\n # Loop to december if necessary\n if month == 0:\n month = 12\n year -= 1\n day = 15 # Always use the 15th because that is when period always ends\n return time.strptime(\"{}-{}-{}\".format(year, month, day), \"%Y-%m-%d\")\n\ndef report_date_str(time_struct):\n return time.strftime(\"Period ending %B %d, %Y\", time_struct)\n\ndef gsheet_date_str(time_struct):\n return time.strftime(\"%b %Y\", time_struct)\n\n\ndef force_move_file(src, dst):\n src_base = os.path.basename(src)\n if not src_base:\n print(\"force_move_file is gauranteed to work only when the src is a file not a directory\")\n print(src)\n print(src_base)\n\n dst_dir = os.path.dirname(dst)\n dst_base = os.path.basename(dst)\n\n if not dst_base: # empty base, so dst is a directory\n dst_base = os.path.basename(src)\n dst = os.path.join(dst_dir, dst_base)\n\n # remove existing file if neccessary\n if os.path.isfile(dst):\n os.remove(dst)\n\n # create directory if necessary\n if dst_dir and not os.path.isdir(dst_dir):\n os.mkdir(dst_dir)\n\n shutil.move(src, dst)\n\n\n\n\nclass Report:\n def __init__(self, type, in_file = '', out_file='', entity = 'Cardinal_A', date = [], download_new = True):\n\n self.entity = entity\n self.type = type\n\n # get time for file names\n #timestr = time.strftime(\"%Y%m%d-%H%M%S\")\n #timestr = time.strftime(\"%m_%Y\")\n\n self.date_time_struct = period_time_struct(date)\n\n\n\n if in_file:\n self.in_file = in_file\n else:\n self.get_default_name()\n\n print(\"Preparing report for {}\".format(self.in_file))\n\n\n if out_file: # output file name given\n self.out_file = out_file\n else: # create output file name\n self.out_file = output_dir + self.in_file[:-4] + '_Formatted.csv'\n\n # Check if in_file already exists, if not than download from website\n if download_new:\n self.download()\n else:\n if not os.path.isfile(self.in_file):\n self.in_file = raw_dir + self.in_file # try looking in raw dir\n if not os.path.isfile(self.in_file):\n print('{} not found so downloading'.format(self.in_file))\n self.download()\n\n # Convert raw csv file to a more readable format\n self.convert()\n\n # Update google drive sheet with information\n self.update_gsheet()\n print(\"\\n\")\n\n def get_default_name(self):\n if self.type is 'ROS':\n report = 'Rental_Owner_Statement'\n elif self.type is 'RR':\n report = 'Rent_Roll'\n else:\n print('unrecognized type')\n\n datestr = time.strftime(\"%m_%Y\", self.date_time_struct)\n\n self.in_file = self.entity + '_' + report + '_' + datestr + '.csv'\n self.report = report\n self.datestr = datestr\n\n # Use splinter to open a browser and download information from Foster website\n def download(self):\n if self.entity in entity_decoder:\n self.login_id, self.login_number = entity_decoder[self.entity]\n else:\n print(\"Did not recognize entity: {}\".format(self.entity))\n with Browser('chrome') as browser:\n # Log in to Foster site\n url = \"https://foster.managebuilding.com/Manager/PublicPages/Login.aspx?ReturnUrl=%2fmanager%2f\"\n browser.visit(url)\n username = self.login_id\n password = 'wenfamily8'\n browser.find_by_id('txtUserName').first.fill(username)\n browser.find_by_id('txtPassword').first.fill(password)\n browser.find_by_id('btnLogIn').first.click()\n xpath = '//*[@id=\"chooseAccountContainer\"]/li[' + self.login_number + ']/a'\n browser.find_by_xpath(xpath).first.click()\n\n # Download Rent Roll file\n if self.type is \"RR\":\n rent_roll_site = 'https://foster.managebuilding.com/Manager/Reports/ReportsSearch.aspx?category=Residents&query=RentRoll'\n browser.visit(rent_roll_site)\n browser.find_by_id('txtexportTypes').select_by_text('Comma-separated text (.csv)')\n browser.find_by_id('btnSubmit').first.click()\n\n # Download Rental Owner Statement\n if self.type is \"ROS\":\n rental_owner_statement_site = 'https://foster.managebuilding.com/Manager/Reports/ReportsSearch.aspx?category=Financials&query=OwnerStatementNewCalculation'\n browser.visit(rental_owner_statement_site)\n# browser.find_by_id('txtexportTypes').select_by_text('Comma-separated text (.csv)')\n browser.find_by_id('cbincludeDetailTransactions').first.click()\n browser.find_by_id('txtdaterange').select_by_text(report_date_str(self.date_time_struct))\n# browser.find_by_id('btnSubmit').first.click()\n browser.find_by_id('lnkExportAs').click()\n browser.find_by_id('lnkExportCsv').click()\n\n # Sleep to make sure there is time for file(s) to download\n time.sleep(5)\n force_move_file(download_dir + download_report_name_dict[self.type], self.in_file)\n\n # function to read and clean up raw csv report files\n def convert(self):\n in_data = []\n out_data = []\n irow = irow_dict[self.type]\n with open(self.in_file, 'r') as f:\n reader = csv.reader(f)\n with open(self.out_file, 'wt') as fido:\n for row in reader:\n in_data.append(row)\n if row[0].find('CANCELLED') == -1 and row[0].find('SOLD') == -1 and row[0].find(\n 'TRANSFERRED') == -1:\n s = ''\n for i in irow:\n s += row[i] + '|, '\n s = s[:-2]\n s += '\\n'\n fido.write(s)\n next_out_data = s.split('|,')\n next_out_data = [s.strip() for s in next_out_data]\n out_data.append(next_out_data)\n self.in_data = in_data\n self.out_data = out_data\n\n # function to update google sheet\n def update_gsheet(self):\n if len(self.out_data) > 1:\n if self.type is \"ROS\":\n self.update_gsheetROS()\n elif self.type is \"RR\":\n self.update_gsheetRR()\n else:\n print('did not recognize report type')\n else:\n print('out data is empty, nothing to update on gsheet')\n\n def update_gsheetROS(self):\n sheet_name = 'monthly tracking'\n date_str = gsheet_date_str(self.date_time_struct)\n G = gsheet.Gsheet(spreadsheetId)\n # data = self.out_data[1:]\n data = self.out_data\n cols = rows2cols(data)\n cols['amount'] = str2float(cols['amount'])\n cols['amount'] = [-1 * x for x in cols['amount']] # reverse sign of amount\n cols = breakout_mortgage(cols)\n props = group(cols)\n currData = G.query(sheet_name)\n print_data = []\n for prop, propdict in props.items():\n row = []\n row.append(prop)\n row.append(nickname[prop])\n row.append(series[prop])\n row.append(date_str)\n for cat in categories:\n row.append(propdict[cat])\n print_data.append(row)\n row_index = G.firstBlankRow(sheet_name) # start assuming append to end\n count = 1\n for existing_row in currData: # check if address and month already exist\n match = True\n if len(existing_row) > 4:\n for i in range(4):\n if existing_row[i] != row[i]:\n match = False\n break\n else:\n match = False\n\n if match:\n print(\"found match at row {}\".format(count))\n row_index = count\n break\n count += 1\n G.update(print_data, sheet_name + '!A' + str(row_index))\n\n self.G = G\n self.cols = cols\n self.groups = props\n self.print_data = print_data\n\n def update_gsheetRR(self):\n G = gsheet.Gsheet(spreadsheetId)\n # data = self.out_data[1:]\n data = self.out_data\n for r in data:\n r.append(self.in_file)\n row = G.firstBlankRow('rent_roll')\n G.update(data, 'rent_roll!A' + str(row))\n self.G = G\n # G.addSheet(self.rent_roll_file)\n # G.update(self.out_data, \"'\" + self.rent_roll_file + \"'!A1\")\n # G.update(self.out_data, \"A1\")\n\ndef tryReport(type, entity, date, download_new):\n RR = []\n try:\n RR = Report(type=type, entity=entity, date=date)\n except:\n print('Failed to make report: {}, {}, {}'.format(type, entity, date, download_new))\n return RR\n\ndef CurrentCardinalROS():\n type = 'ROS'\n date = []\n download_new = True\n reports = []\n entities = ['Cardinal_A', 'Cardinal_B', 'Cardinal_D']\n for entity in entities:\n reports.append(tryReport(type=type, entity = entity, date=date, download_new = download_new))\n return reports\n\nif __name__ == \"__main__\":\n for i in range(1,13):\n date = [i, 2015]\n timestr = \"{}_{}\".format(date[0], date[1])\n type = 'ROS'\n download_new = True\n\n #entities = ['Carindal_A', 'Cardinal_B', 'Cardinal_C', 'Cardinal_D', 'Ellie_Wen', 'Greg_Katz', 'You_Me']\n #entities = ['Carindal_A', 'Cardinal_B', 'Cardinal_D']\n entities = ['Ellie_Wen', 'Greg_Katz']\n #entities = ['You_Me']\n\n for entity in entities:\n tryReport(type=type, entity=entity, date=date, download_new=download_new)\n\n", "sub_path": "python/realestate/realestate.py", "file_name": "realestate.py", "file_ext": "py", "file_size_in_byte": 13706, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "sys.path.append", "line_number": 7, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 7, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 110, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 111, "usage_type": "call"}, {"api_name": "time.strptime", "line_number": 127, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 130, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 133, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 137, "usage_type": "call"}, {"api_name": "os.path", "line_number": 137, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 143, "usage_type": "call"}, {"api_name": "os.path", "line_number": 143, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 144, "usage_type": "call"}, {"api_name": "os.path", "line_number": 144, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 147, "usage_type": "call"}, {"api_name": "os.path", "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"}, {"api_name": "os.path.isfile", "line_number": 151, "usage_type": "call"}, {"api_name": "os.path", "line_number": 151, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 152, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 155, "usage_type": "call"}, {"api_name": "os.path", "line_number": 155, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 156, "usage_type": "call"}, {"api_name": "shutil.move", "line_number": 158, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 194, "usage_type": "call"}, {"api_name": "os.path", "line_number": 194, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 196, "usage_type": "call"}, {"api_name": "os.path", "line_number": 196, "usage_type": "attribute"}, {"api_name": "time.strftime", "line_number": 215, "usage_type": "call"}, {"api_name": "splinter.Browser", "line_number": 227, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 258, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 267, "usage_type": "call"}, {"api_name": "gsheet.Gsheet", "line_number": 300, "usage_type": "call"}, {"api_name": "gsheet.Gsheet", "line_number": 344, "usage_type": "call"}]}
+{"seq_id": "514780202", "text": "from matplotlib.pylab import gca, figure, plot, subplot, title, xlabel, ylabel, xlim,show\nfrom matplotlib.lines import Line2D\nimport segment\nimport fit\nimport sys\n\nfrom numpy import array\ndef draw_plot(data,plot_title):\n plot(data[:,0],data[:,1],alpha=0.8,color='red')\n title(plot_title)\n xlabel(\"Samples\")\n ylabel(\"Signal\")\n xlim((data[:,0][0],data[:,0][-1]))\n\ndef draw_segments(segments,ticks):\n segments=[(x1,y1,x21,y21) for x,(x1,y1),x2,(x21,y21),err in segments]\n ax = gca()\n ax.set_xticklabels(ticks, rotation=20)\n for segment in segments:\n line = Line2D((segment[0],segment[2]),(segment[1],segment[3]))\n ax.add_line(line)\n\ndef wrapOrchestration(title, labels, data, segment_algo, create_segment, compute_error, max_error):\n figure()\n segments = segment_algo(data, create_segment, compute_error, max_error)\n draw_plot(data,title)\n draw_segments(segments,labels)\n print(len(segments))\n print(len(data)/len(segments))\n name=title.split()[0][:3]+title.split()[-1][:3]\n with open(f\"./output/{name}_{labels[0]}_{labels[-1]}_{max_error}.txt\",\"w\") as file:\n for xbeg, (x0,y0), xend, (x1,y1), err in segments:\n file.write(f\"{labels[xbeg]}\\t{x0}\\t{y0}\\n\")\n file.write(f\"{labels[xend]}\\t{x1}\\t{y1}\\t{err}\\n\")\n\n\nMIN=int(sys.argv[1]) if len(sys.argv)>1 else 0\nMAX=int(sys.argv[2]) if len(sys.argv)>2 else MIN+30\nERROR=float(sys.argv[3]) if len(sys.argv)>3 else 1\nwith open(\"example_data/bitcoin_2010-8-16_2021-9-8.txt\") as f:\n file_lines = f.readlines()\n\ndata = [tuple(x.split(\"\\t\")[1:3]) for x in file_lines[MIN:MAX]]\nlabels = [x.split(\"\\t\")[0] for x in file_lines[MIN:MAX]]\ndata = array([(float(x),float(y.strip())) for x,y in data])\nmax_error = ERROR\n\n#sliding window with regression \nwrapOrchestration(\"Sliding window with regression\",labels,data,segment.slidingwindowsegment, fit.regression, fit.sumsquared_error, max_error)\n#bottom-up with regression\nwrapOrchestration(\"Bottom-up with regression\",labels,data,segment.bottomupsegment,fit.regression, fit.sumsquared_error, max_error)\n#top-down with regression\n#wrapOrchestration(\"Top-down with regression\",labels,data,segment.topdownsegment,fit.regression, fit.sumsquared_error, max_error)\n\n#sliding window with simple interpolation\nwrapOrchestration(\"Sliding window with simple interpolation\",labels,data,segment.slidingwindowsegment, fit.interpolate, fit.sumsquared_error, max_error)\n#bottom-up with simple interpolation\nwrapOrchestration(\"Bottom-up with simple interpolation\",labels,data,segment.bottomupsegment,fit.interpolate, fit.sumsquared_error, max_error)\n#top-down with simple interpolation\n#wrapOrchestration(\"Top-down with simple interpolation\",labels,data,segment.topdownsegment,fit.interpolate, fit.sumsquared_error, max_error)\n\nshow()\n\n", "sub_path": "example.py", "file_name": "example.py", "file_ext": "py", "file_size_in_byte": 2798, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "matplotlib.pylab.plot", "line_number": 9, "usage_type": "call"}, {"api_name": "matplotlib.pylab.title", "line_number": 10, "usage_type": "call"}, {"api_name": "matplotlib.pylab.xlabel", "line_number": 11, "usage_type": "call"}, {"api_name": "matplotlib.pylab.ylabel", "line_number": 12, "usage_type": "call"}, {"api_name": "matplotlib.pylab.xlim", "line_number": 13, "usage_type": "call"}, {"api_name": "matplotlib.pylab.gca", "line_number": 17, "usage_type": "call"}, {"api_name": "matplotlib.lines.Line2D", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pylab.figure", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.pylab.title", "line_number": 26, "usage_type": "argument"}, {"api_name": "matplotlib.pylab.title.split", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pylab.title", "line_number": 30, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 37, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 38, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 39, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 45, "usage_type": "call"}, {"api_name": "segment.slidingwindowsegment", "line_number": 49, "usage_type": "attribute"}, {"api_name": "fit.regression", "line_number": 49, "usage_type": "attribute"}, {"api_name": "fit.sumsquared_error", "line_number": 49, "usage_type": "attribute"}, {"api_name": "segment.bottomupsegment", "line_number": 51, "usage_type": "attribute"}, {"api_name": "fit.regression", "line_number": 51, "usage_type": "attribute"}, {"api_name": "fit.sumsquared_error", "line_number": 51, "usage_type": "attribute"}, {"api_name": "segment.slidingwindowsegment", "line_number": 56, "usage_type": "attribute"}, {"api_name": "fit.interpolate", "line_number": 56, "usage_type": "attribute"}, {"api_name": "fit.sumsquared_error", "line_number": 56, "usage_type": "attribute"}, {"api_name": "segment.bottomupsegment", "line_number": 58, "usage_type": "attribute"}, {"api_name": "fit.interpolate", "line_number": 58, "usage_type": "attribute"}, {"api_name": "fit.sumsquared_error", "line_number": 58, "usage_type": "attribute"}, {"api_name": "matplotlib.pylab.show", "line_number": 62, "usage_type": "call"}]}
+{"seq_id": "300520338", "text": "from lxml import etree\n\n\n\ndef add_entry(dict, key, value = None):\n if key in dict: # если ключ существует\n if value == None:\n pass\n #'ключ есть, новое значение None - пропускаем'\n return dict\n else:\n if dict.get(key) == None:\n dict.update({key: [value]})\n #'ключ есть, старое значение None - добавляем не None'\n return dict\n else:\n old_value = dict.get(key)\n old_value.append(value)\n dict.update({key: old_value})\n #'ключ есть, старое значение не None - добавляем в список'\n return dict\n else:\n if value == None:\n dict.update({key: value})\n #'ключa нет - добавляем None'\n return dict\n else:\n dict.update({key: [ value]})\n #'ключa нет - добавляем'\n return dict\n\n\n\ndef HeaderCheck(filename):\n result = {}\n tree = etree.parse(filename)\n root = tree.getroot()\n for dashboard in root.iter('dashboard'): #проходим по каждой ноде \n header_check = list()\n\n for zones in dashboard.iter('zones'): #ищем первую ноду с именем \n\n for item in zones.getchildren():\n if item.get('type') == 'layout-basic': # проеряем тип зоны, чтобы исключить floating контейнеры\n\n child = item.find('zone') #vert container\n header_check.append(child.attrib)\n\n\n if child.find('zone') != None: # проверка структуры заголовка\n sub_child = child.find('zone') #horz container\n header_check.append(sub_child.attrib)\n\n # проверка структуры заголовка\n if header_check[0].get('param') == 'vert' and header_check[1].get('param') == 'horz':\n result = add_entry(key = 'Заголовок', dict = result)\n else:\n result = add_entry(key = 'Заголовок', value = ' в дашборде \"{}\" структура не соответствует'.format(dashboard.get('name')) , dict = result)\n\n # проверка высоты заголовка\n if int(header_check[1].get('fixed-size')) == 44:\n result = add_entry(key = 'Заголовок', dict = result)\n else:\n result = add_entry(key = 'Заголовок', value = ' в дашборде \"{}\" высота не равна 44px'.format(dashboard.get('name')) , dict = result)\n\n # проверка ширины логотипа\n logo = sub_child.find('zone')\n\n try:\n if int(logo.get('fixed-size')) == 105:\n result = add_entry(key = 'Заголовок', dict = result)\n else:\n result = add_entry(key = 'Заголовок', value = ' в дашборде \"{}\" ширина логотипа не равна 105px'.format(dashboard.get('name')), dict = result )\n except:\n result = add_entry(key = 'Заголовок', value = ' в дашборде \"{}\" проверка ширины логотипа не удалась'.format(dashboard.get('name')), dict = result )\n\n # проверка отступов логотипа\n try:\n if int(logo.find('..//zone-style/format[@attr=\"margin\"]').get('value')) == 12:\n result = add_entry(key = 'Заголовок')\n else:\n result = add_entry(key = 'Заголовок', value = ' в дашборде \"{}\" внешние отступы логотипа не равны 12px'.format(dashboard.get('name')), dict = result )\n except:\n result = add_entry(key = 'Заголовок', value = ' в дашборде \"{}\" проверка отступов логотипа не удалась'.format(dashboard.get('name')), dict = result )\n\n # проверка центровки логотипа\n try:\n if int(logo.get('is-centered')) == 0:\n result = add_entry(key = 'Заголовок', value = ' в дашборде \"{}\" у логотипа не не стоит флаг \"Center Image\"'.format(dashboard.get('name')), dict = result )\n else:\n pass\n except:\n result = add_entry(key = 'Заголовок', dict = result)\n\n # проверка Fit Image логотипа\n try:\n if int(logo.get('is-scaled')) == 1:\n result = add_entry(key = 'Заголовок', dict = result)\n else:\n result = add_entry(key = 'Заголовок', value = ' в дашборде \"{}\" у логотипа не не стоит флаг \"Fit Image\"'.format(dashboard.get('name')), dict = result )\n except:\n result = add_entry(key = 'Заголовок', value = ' в дашборде \"{}\" проверка параметра \"Fit Image\" не удалась'.format(dashboard.get('name')), dict = result )\n\n # проверка фона #565C61\n if sub_child.find('..//zone-style/format[@attr=\"background-color\"]').get('value').upper() == '#565C61':\n result = add_entry(key = 'Заголовок', dict = result)\n else:\n result = add_entry(key = 'Заголовок', value = ' в дашборде \"{}\" у заголовка фон не \"#565C61\" '.format(dashboard.get('name')), dict = result )\n\n else:\n result = add_entry(key = 'Заголовок', value = ' в дашборде \"{}\" структура не соответствует'.format(dashboard.get('name')) , dict = result)\n\n\n else:\n pass\n return result\n", "sub_path": "uploader/logic.py", "file_name": "logic.py", "file_ext": "py", "file_size_in_byte": 6790, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "lxml.etree.parse", "line_number": 36, "usage_type": "call"}, {"api_name": "lxml.etree", "line_number": 36, "usage_type": "name"}]}
+{"seq_id": "592770237", "text": "from typing import List, Any\n\nfrom hearthstone.entities import Entity\nfrom hearthstone.enums import GameTag\n\nfrom .base_entity import BaseEntity\nfrom .spell_entity import SpellEntity\n\n\nclass HeroEntity(BaseEntity):\n\n def __init__(self, entity: Entity):\n super().__init__(entity)\n self.card_id = 0\n self.atk = 0\n self.max_health = 0\n # 受伤\n self.damage = 0\n # INVALID = 0 施法者CASTER = 1 斗士FIGHTER = 2 TANK = 3 NEUTRAL = 4\n self.lettuce_role = 2 # 斗士\n self.cardrace = None\n self.pos = [0, 0] # 坐标[x, y]\n # 场上位置 从左往右1开始\n\n self.zone_position = 0\n # 意义不明\n self.cost = 0\n self.divine_shield = 0\n # INVALID = 0 部落HORDE = 1 联盟ALLIANCE = 2 中立NEUTRAL = 3\n self.faction = 0\n self.windfury = 0\n self.spell_cnt = 1\n # 被动 一技能 二技能 三技能 ...\n self.spell: List[SpellEntity] = []\n self.spellpower = 0\n self.deathrattle = 0\n # 是否选择了技能\n self.lettuce_has_manually_selected_ability = 0\n # 选了什么技能\n self.lettuce_ability_tile_visual_self_only = 0\n # 技能选择的目标\n self.lettuce_selected_target = 0\n # 经验 55000满级\n self.lettuce_mercenary_experience = 0\n self.skill_seq = None\n self.parse_entity()\n\n def parse_entity(self):\n if self.entity is None:\n return\n super(HeroEntity, self).parse_entity()\n self.card_id = self.entity.card_id\n self.atk = self.get_tag(GameTag.ATK)\n self.max_health = self.get_tag(GameTag.HEALTH)\n self.damage = self.get_tag(GameTag.DAMAGE)\n self.lettuce_role = self.get_tag(GameTag.LETTUCE_ROLE)\n self.cardrace = self.get_tag(GameTag.CARDRACE)\n self.zone_position = self.get_tag(GameTag.ZONE_POSITION)\n self.cost = self.get_tag(GameTag.COST)\n self.divine_shield = self.get_tag(GameTag.DIVINE_SHIELD)\n self.faction = self.get_tag(GameTag.FACTION)\n self.windfury = self.get_tag(GameTag.WINDFURY)\n self.spellpower = self.get_tag(GameTag.SPELLPOWER)\n self.deathrattle = self.get_tag(GameTag.DEATHRATTLE)\n self.lettuce_has_manually_selected_ability = self.get_tag(GameTag.LETTUCE_HAS_MANUALLY_SELECTED_ABILITY)\n self.lettuce_ability_tile_visual_self_only = self.get_tag(GameTag.LETTUCE_ABILITY_TILE_VISUAL_SELF_ONLY)\n self.lettuce_selected_target = self.get_tag(GameTag.LETTUCE_SELECTED_TARGET)\n self.lettuce_mercenary_experience = self.get_tag(GameTag.LETTUCE_MERCENARY_EXPERIENCE)\n\n def set_pos(self, x, y):\n self.pos = [x, y]\n\n def set_skill_seq(self, skills):\n self.skill_seq = skills\n\n def own(self):\n \"\"\"\n 谁的随从\n \"\"\"\n return self.controller == 3\n\n def add_spell(self, spell: SpellEntity):\n self.spell.append(spell)\n\n def get_health(self):\n return self.max_health - self.damage\n\n def basic_attack(self, target, dmg):\n total_dmg = dmg * BaseEntity.damage_advantage[self.lettuce_role][target.lettuce_role]\n target.damage += total_dmg\n return total_dmg\n\n def __str__(self):\n return {'card_id': self.card_id, 'atk': self.atk, 'health': self.get_health(),\n 'zone_pos': self.zone_position}.__str__()\n", "sub_path": "entity/hero_entity.py", "file_name": "hero_entity.py", "file_ext": "py", "file_size_in_byte": 3422, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "base_entity.BaseEntity", "line_number": 10, "usage_type": "name"}, {"api_name": "hearthstone.entities.Entity", "line_number": 12, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 34, "usage_type": "name"}, {"api_name": "spell_entity.SpellEntity", "line_number": 34, "usage_type": "name"}, {"api_name": "hearthstone.enums.GameTag.ATK", "line_number": 53, "usage_type": "attribute"}, {"api_name": "hearthstone.enums.GameTag", "line_number": 53, "usage_type": "name"}, {"api_name": "hearthstone.enums.GameTag.HEALTH", "line_number": 54, "usage_type": "attribute"}, {"api_name": "hearthstone.enums.GameTag", "line_number": 54, "usage_type": "name"}, {"api_name": "hearthstone.enums.GameTag.DAMAGE", "line_number": 55, "usage_type": "attribute"}, {"api_name": "hearthstone.enums.GameTag", "line_number": 55, "usage_type": "name"}, {"api_name": "hearthstone.enums.GameTag.LETTUCE_ROLE", "line_number": 56, "usage_type": "attribute"}, {"api_name": "hearthstone.enums.GameTag", "line_number": 56, "usage_type": "name"}, {"api_name": "hearthstone.enums.GameTag.CARDRACE", "line_number": 57, "usage_type": "attribute"}, {"api_name": "hearthstone.enums.GameTag", "line_number": 57, "usage_type": "name"}, {"api_name": "hearthstone.enums.GameTag.ZONE_POSITION", "line_number": 58, "usage_type": "attribute"}, {"api_name": "hearthstone.enums.GameTag", "line_number": 58, "usage_type": "name"}, {"api_name": "hearthstone.enums.GameTag.COST", "line_number": 59, "usage_type": "attribute"}, {"api_name": "hearthstone.enums.GameTag", "line_number": 59, "usage_type": "name"}, {"api_name": "hearthstone.enums.GameTag.DIVINE_SHIELD", "line_number": 60, "usage_type": "attribute"}, {"api_name": "hearthstone.enums.GameTag", "line_number": 60, "usage_type": "name"}, {"api_name": "hearthstone.enums.GameTag.FACTION", "line_number": 61, "usage_type": "attribute"}, {"api_name": "hearthstone.enums.GameTag", "line_number": 61, "usage_type": "name"}, {"api_name": "hearthstone.enums.GameTag.WINDFURY", "line_number": 62, "usage_type": "attribute"}, {"api_name": "hearthstone.enums.GameTag", "line_number": 62, "usage_type": "name"}, {"api_name": "hearthstone.enums.GameTag.SPELLPOWER", "line_number": 63, "usage_type": "attribute"}, {"api_name": "hearthstone.enums.GameTag", "line_number": 63, "usage_type": "name"}, {"api_name": "hearthstone.enums.GameTag.DEATHRATTLE", "line_number": 64, "usage_type": "attribute"}, {"api_name": "hearthstone.enums.GameTag", "line_number": 64, "usage_type": "name"}, {"api_name": "hearthstone.enums.GameTag.LETTUCE_HAS_MANUALLY_SELECTED_ABILITY", "line_number": 65, "usage_type": "attribute"}, {"api_name": "hearthstone.enums.GameTag", "line_number": 65, "usage_type": "name"}, {"api_name": "hearthstone.enums.GameTag.LETTUCE_ABILITY_TILE_VISUAL_SELF_ONLY", "line_number": 66, "usage_type": "attribute"}, {"api_name": "hearthstone.enums.GameTag", "line_number": 66, "usage_type": "name"}, {"api_name": "hearthstone.enums.GameTag.LETTUCE_SELECTED_TARGET", "line_number": 67, "usage_type": "attribute"}, {"api_name": "hearthstone.enums.GameTag", "line_number": 67, "usage_type": "name"}, {"api_name": "hearthstone.enums.GameTag.LETTUCE_MERCENARY_EXPERIENCE", "line_number": 68, "usage_type": "attribute"}, {"api_name": "hearthstone.enums.GameTag", "line_number": 68, "usage_type": "name"}, {"api_name": "spell_entity.SpellEntity", "line_number": 82, "usage_type": "name"}, {"api_name": "base_entity.BaseEntity.damage_advantage", "line_number": 89, "usage_type": "attribute"}, {"api_name": "base_entity.BaseEntity", "line_number": 89, "usage_type": "name"}]}
+{"seq_id": "227136654", "text": "# Data-store record for voter\n\n\n# Import external modules\nimport logging\nimport re\nimport urlparse\n# Import app modules\nfrom configOpenVoterId import const as conf\nfrom secretsOpenVoterId import const as secrets\nimport security\nimport voter\n\n\n# If not unit testing... include gCloud code\nif __name__ != '__main__':\n\n from google.appengine.ext import ndb\n\n # Parent key: none\n # Key: identityHash: long alpha-numeric string\n class IdRecord( ndb.Model ):\n saltPhone = ndb.StringProperty()\n saltSocialSec = ndb.StringProperty()\n saltBirthdate = ndb.StringProperty()\n saltMailedCode = ndb.StringProperty()\n city = ndb.StringProperty()\n verificationHashes = ndb.TextProperty( repeated=True )\n\n\n # Parent key: none\n # Key: string: client/voter type + identity\n class RateRecord( ndb.Model ):\n loginFailuresSinceSuccess = ndb.IntegerProperty( default=0 )\n nextAttemptTime = ndb.IntegerProperty( default=0 ) # Needed to know when wait ends\n resetFailuresOnNextAttempt = ndb.BooleanProperty( default=False )\n \n def allowed( self, now ):\n\n logging.debug( 'RateRecord.allowed() now=' + str(now) + ' nextAttemptTime=' + str(self.nextAttemptTime) \n + ' nextAttemptTime-now = ' + str(self.nextAttemptTime - now)\n + ' loginFailuresSinceSuccess=' + str(self.loginFailuresSinceSuccess) )\n\n return (self.nextAttemptTime <= now)\n\n\n####################################################################################\n# Rate-limit functions\n\nconf.rateRecordTypeClient = 'client'\nconf.rateRecordTypeVoter = 'voter'\n\nconf.rateUseDatastore = False # Turn off persistent storage, and expire records via memcache expiration\nconf.rateUseMemcache = True\nconf.rateMemcacheTimeout = conf.oneDaySec\n\n# Continuing to login and failing will not keep memcache record alive longer than memcache-expiration, \n# because rate-check only reads memcache, and only memcache-writes update expiration-time\n\n\ndef retrieveClientRateLimit( clientIp ):\n recordId = toRateRecordId( conf.rateRecordTypeClient, clientIp )\n if conf.isDev: logging.debug( 'retrieveClientRateLimit() recordId=' + str(recordId) )\n return RateRecord.get_by_id( recordId, use_datastore=conf.rateUseDatastore, use_memcache=conf.rateUseMemcache, memcache_timeout=conf.rateMemcacheTimeout )\n\ndef retrieveVoterRateLimit( voterId ):\n recordId = toRateRecordId( conf.rateRecordTypeVoter, voterId )\n if conf.isDev: logging.debug( 'retrieveVoterRateLimit() recordId=' + str(recordId) )\n return RateRecord.get_by_id( recordId, use_datastore=conf.rateUseDatastore, use_memcache=conf.rateUseMemcache, memcache_timeout=conf.rateMemcacheTimeout )\n\n\n# Modifies/creates and returns rateRecord\ndef updateClientLoginRate( now, success, clientIp, rateRecord ):\n return updateLoginRate( now, success, clientIp, conf.rateRecordTypeClient, rateRecord )\n\ndef updateVoterLoginRate( now, success, voterId, rateRecord ):\n return updateLoginRate( now, success, voterId, conf.rateRecordTypeVoter, rateRecord )\n\ndef updateLoginRate( now, success, recordId, recordType, rateRecord ):\n\n if not rateRecord and ( recordId and recordType ):\n rateRecord = RateRecord( id=toRateRecordId(recordType, recordId) )\n\n if not rateRecord: return None\n \n if success or rateRecord.resetFailuresOnNextAttempt:\n rateRecord.loginFailuresSinceSuccess = 0\n rateRecord.nextAttemptTime = now\n rateRecord.resetFailuresOnNextAttempt = False\n else:\n # Wait-time proportional to number of failures since last login, until wait > 1day ... then reset fail-count\n failuresSinceSuccess = rateRecord.loginFailuresSinceSuccess\n if (not failuresSinceSuccess) or (failuresSinceSuccess < 0): failuresSinceSuccess = 0\n rateRecord.loginFailuresSinceSuccess = failuresSinceSuccess + 1\n\n waitSec = (2 << failuresSinceSuccess)\n if ( waitSec > conf.oneDaySec ):\n rateRecord.nextAttemptTime = now + conf.oneDaySec\n rateRecord.resetFailuresOnNextAttempt = True\n else:\n rateRecord.nextAttemptTime = now + waitSec\n rateRecord.resetFailuresOnNextAttempt = False\n \n # Store record synchronously, because async fails\n if rateRecord: rateRecord.put( use_datastore=conf.rateUseDatastore, use_memcache=conf.rateUseMemcache, memcache_timeout=conf.rateMemcacheTimeout )\n return rateRecord\n\n\ndef toRateRecordId( recordType, recordId ):\n return '{}_{}'.format( recordType, recordId )\n\n\n\n#################################################################################\n# Unit test\n\nimport unittest\n\nclass TestText(unittest.TestCase):\n\n def testRateLimit( self ):\n\n class FakeRateRecord:\n def __init__( self, failures=0 ):\n self.loginFailuresSinceSuccess = failures\n self.nextAttemptTime = 0\n self.resetFailuresOnNextAttempt = False\n\n def put( self, use_datastore=None, use_memcache=None, memcache_timeout=None, use_cache=None ): pass\n\n now = 100\n rateRecord = FakeRateRecord( failures=0 )\n success = True\n recordId = 'recordId'\n recordType = 'recordType'\n rateRecord = updateLoginRate( now, success, recordId, recordType, rateRecord )\n self.assertEqual( rateRecord.loginFailuresSinceSuccess, 0 )\n self.assertEqual( rateRecord.nextAttemptTime, now )\n self.assertFalse( rateRecord.resetFailuresOnNextAttempt )\n\n success = False\n rateRecord = updateLoginRate( now, success, recordId, recordType, rateRecord )\n self.assertEqual( rateRecord.loginFailuresSinceSuccess, 1 )\n self.assertEqual( rateRecord.nextAttemptTime, now+2 )\n self.assertFalse( rateRecord.resetFailuresOnNextAttempt )\n\n rateRecord = FakeRateRecord( failures=50 )\n success = False\n rateRecord = updateLoginRate( now, success, recordId, recordType, rateRecord )\n self.assertEqual( rateRecord.loginFailuresSinceSuccess, 51 )\n self.assertEqual( rateRecord.nextAttemptTime, now + conf.oneDaySec )\n self.assertTrue( rateRecord.resetFailuresOnNextAttempt )\n\n success = False\n rateRecord = updateLoginRate( now, success, recordId, recordType, rateRecord )\n self.assertEqual( rateRecord.loginFailuresSinceSuccess, 0 )\n self.assertEqual( rateRecord.nextAttemptTime, now )\n self.assertFalse( rateRecord.resetFailuresOnNextAttempt )\n\n\nif __name__ == '__main__':\n unittest.main()\n\n\n", "sub_path": "voterRecord.py", "file_name": "voterRecord.py", "file_ext": "py", "file_size_in_byte": 6566, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "google.appengine.ext.ndb.Model", "line_number": 22, "usage_type": "attribute"}, {"api_name": "google.appengine.ext.ndb", "line_number": 22, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.StringProperty", "line_number": 23, "usage_type": "call"}, {"api_name": "google.appengine.ext.ndb", "line_number": 23, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.StringProperty", "line_number": 24, "usage_type": "call"}, {"api_name": "google.appengine.ext.ndb", "line_number": 24, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.StringProperty", "line_number": 25, "usage_type": "call"}, {"api_name": "google.appengine.ext.ndb", "line_number": 25, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.StringProperty", "line_number": 26, "usage_type": "call"}, {"api_name": "google.appengine.ext.ndb", "line_number": 26, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.StringProperty", "line_number": 27, "usage_type": "call"}, {"api_name": "google.appengine.ext.ndb", "line_number": 27, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.TextProperty", "line_number": 28, "usage_type": "call"}, {"api_name": "google.appengine.ext.ndb", "line_number": 28, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.Model", "line_number": 33, "usage_type": "attribute"}, {"api_name": "google.appengine.ext.ndb", "line_number": 33, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.IntegerProperty", "line_number": 34, "usage_type": "call"}, {"api_name": "google.appengine.ext.ndb", "line_number": 34, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.IntegerProperty", "line_number": 35, "usage_type": "call"}, {"api_name": "google.appengine.ext.ndb", "line_number": 35, "usage_type": "name"}, {"api_name": "google.appengine.ext.ndb.BooleanProperty", "line_number": 36, "usage_type": "call"}, {"api_name": "google.appengine.ext.ndb", "line_number": 36, "usage_type": "name"}, {"api_name": "logging.debug", "line_number": 40, "usage_type": "call"}, {"api_name": "configOpenVoterId.const.rateRecordTypeClient", "line_number": 50, "usage_type": "attribute"}, {"api_name": "configOpenVoterId.const", "line_number": 50, "usage_type": "name"}, {"api_name": "configOpenVoterId.const.rateRecordTypeVoter", "line_number": 51, "usage_type": "attribute"}, {"api_name": "configOpenVoterId.const", "line_number": 51, "usage_type": "name"}, {"api_name": "configOpenVoterId.const.rateUseDatastore", "line_number": 53, "usage_type": "attribute"}, {"api_name": "configOpenVoterId.const", "line_number": 53, "usage_type": "name"}, {"api_name": "configOpenVoterId.const.rateUseMemcache", "line_number": 54, "usage_type": "attribute"}, {"api_name": "configOpenVoterId.const", "line_number": 54, "usage_type": "name"}, {"api_name": "configOpenVoterId.const.rateMemcacheTimeout", "line_number": 55, "usage_type": "attribute"}, {"api_name": "configOpenVoterId.const", "line_number": 55, "usage_type": "name"}, {"api_name": "configOpenVoterId.const.oneDaySec", "line_number": 55, "usage_type": "attribute"}, {"api_name": "configOpenVoterId.const.rateRecordTypeClient", "line_number": 62, "usage_type": "attribute"}, {"api_name": "configOpenVoterId.const", "line_number": 62, "usage_type": "name"}, {"api_name": "configOpenVoterId.const.isDev", "line_number": 63, "usage_type": "attribute"}, {"api_name": "configOpenVoterId.const", "line_number": 63, "usage_type": "name"}, {"api_name": "logging.debug", "line_number": 63, "usage_type": "call"}, {"api_name": "configOpenVoterId.const.rateUseDatastore", "line_number": 64, "usage_type": "attribute"}, {"api_name": "configOpenVoterId.const", "line_number": 64, "usage_type": "name"}, {"api_name": "configOpenVoterId.const.rateUseMemcache", "line_number": 64, "usage_type": "attribute"}, {"api_name": "configOpenVoterId.const.rateMemcacheTimeout", "line_number": 64, "usage_type": "attribute"}, {"api_name": "configOpenVoterId.const.rateRecordTypeVoter", "line_number": 67, "usage_type": "attribute"}, {"api_name": "configOpenVoterId.const", "line_number": 67, "usage_type": "name"}, {"api_name": "configOpenVoterId.const.isDev", "line_number": 68, "usage_type": "attribute"}, {"api_name": "configOpenVoterId.const", "line_number": 68, "usage_type": "name"}, {"api_name": "logging.debug", "line_number": 68, "usage_type": "call"}, {"api_name": "configOpenVoterId.const.rateUseDatastore", "line_number": 69, "usage_type": "attribute"}, {"api_name": "configOpenVoterId.const", "line_number": 69, "usage_type": "name"}, {"api_name": "configOpenVoterId.const.rateUseMemcache", "line_number": 69, "usage_type": "attribute"}, {"api_name": "configOpenVoterId.const.rateMemcacheTimeout", "line_number": 69, "usage_type": "attribute"}, {"api_name": "configOpenVoterId.const.rateRecordTypeClient", "line_number": 74, "usage_type": "attribute"}, {"api_name": "configOpenVoterId.const", "line_number": 74, "usage_type": "name"}, {"api_name": "configOpenVoterId.const.rateRecordTypeVoter", "line_number": 77, "usage_type": "attribute"}, {"api_name": "configOpenVoterId.const", "line_number": 77, "usage_type": "name"}, {"api_name": "configOpenVoterId.const.oneDaySec", "line_number": 97, "usage_type": "attribute"}, {"api_name": "configOpenVoterId.const", "line_number": 97, "usage_type": "name"}, {"api_name": "configOpenVoterId.const.oneDaySec", "line_number": 98, "usage_type": "attribute"}, {"api_name": "configOpenVoterId.const", "line_number": 98, "usage_type": "name"}, {"api_name": "configOpenVoterId.const.rateUseDatastore", "line_number": 105, "usage_type": "attribute"}, {"api_name": "configOpenVoterId.const", "line_number": 105, "usage_type": "name"}, {"api_name": "configOpenVoterId.const.rateUseMemcache", "line_number": 105, "usage_type": "attribute"}, {"api_name": "configOpenVoterId.const.rateMemcacheTimeout", "line_number": 105, "usage_type": "attribute"}, {"api_name": "unittest.TestCase", "line_number": 119, "usage_type": "attribute"}, {"api_name": "configOpenVoterId.const.oneDaySec", "line_number": 151, "usage_type": "attribute"}, {"api_name": "configOpenVoterId.const", "line_number": 151, "usage_type": "name"}, {"api_name": "unittest.main", "line_number": 162, "usage_type": "call"}]}
+{"seq_id": "562045568", "text": "from prodnet.view import ProdnetView\nfrom prodnet.models import DBSession, Bid, Project, BidRecord\nfrom pyramid.view import view_config, view_defaults\nfrom pyramid.httpexceptions import HTTPBadRequest, HTTPOk, HTTPNotFound\nfrom prodnet.util import _, dictify\n\n\n@view_defaults(renderer='json', permission='user', route_name='project_bid')\nclass BidAPI(ProdnetView):\n def __init__(self, request):\n super().__init__(request)\n project = Project.get_by_id(self.request.matchdict['id'], True)\n if project.user_id == self.user.id or not project.auction:\n raise HTTPBadRequest()\n\n self.bid = project.auction.get_bid(self.user)\n self.bid_active = self.bid.is_active() if self.bid else True\n self.project = project\n\n @view_config(request_method='POST')\n def create(self):\n project = self.project\n\n if project.state != 'running':\n raise HTTPBadRequest()\n\n bid = self.bid\n price = float(self.request.json_body['price'])\n insured = self.request.json_body['insured']\n\n if bid:\n bid.records.insert(0, BidRecord(price=price, insured=insured))\n cause_text = \"Sie haben ihr Gebot für ${pname} auf ${price} ${curr} aktualisiert\"\n text = \"${name} hat sein Gebot für ${pname} auf ${price} ${curr} aktualisiert\"\n else:\n if not project.auction.can_bid(self.user):\n raise HTTPBadRequest()\n try:\n self.user.watched_projects.remove(project)\n except ValueError:\n pass\n bid = Bid(project.auction, self.user, price, insured)\n cause_text = \"Sie haben ein Gebot für ${pname} abgegeben: ${price} ${curr}\"\n text = \"${name} hat ein Gebot für ${pname} abgegeben: ${price} ${curr}\"\n self.bid = bid\n\n mapping = dict(pname=project.name, price=price, curr=_(\"€\"))\n self.event(self.user, _(cause_text, **mapping), project.user, seen=True)\n self.event(project.user, _(text, name=self.user.name, **mapping), self.user, project)\n DBSession.flush()\n return {\n 'bid': dictify(bid, [\n 'id',\n ('records', ['price', 'insured', 'created_at'])\n ]),\n 'project': {\n 'auction': self.project.auction.dictify(all_data=True)\n }\n }\n\n @view_config(request_method='DELETE')\n def delete(self):\n if not self.bid:\n raise HTTPNotFound()\n project = self.project\n if project.state not in ['running', 'frozen']:\n raise HTTPBadRequest()\n\n DBSession.delete(self.bid)\n self.user.watched_projects.append(project)\n\n cause_text = \"Sie haben ihr Gebot für ${pname} zurückgezogen\"\n text = \"${name} hat sein Gebot für ${pname} zurückgezogen\"\n self.event(self.user, _(cause_text, pname=project.name), project.user, project, seen=True)\n self.event(project.user, _(text, name=self.user.name, pname=project.name), self.user, project)\n return {\n 'bid': None,\n 'project': {\n 'auction': self.project.auction.dictify(all_data=True)\n }\n }\n\n @view_config(request_method='POST', route_name='project_bid_accept_mods')\n def accept_mods(self):\n if self.project.state != 'running':\n raise HTTPBadRequest()\n if not self.bid:\n raise HTTPNotFound()\n self.bid.accept_mods()\n return HTTPOk()", "sub_path": "prodnet/views/api/project/bid.py", "file_name": "bid.py", "file_ext": "py", "file_size_in_byte": 3520, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "prodnet.view.ProdnetView", "line_number": 9, "usage_type": "name"}, {"api_name": "prodnet.models.Project.get_by_id", "line_number": 12, "usage_type": "call"}, {"api_name": "prodnet.models.Project", "line_number": 12, "usage_type": "name"}, {"api_name": "pyramid.httpexceptions.HTTPBadRequest", "line_number": 14, "usage_type": "call"}, {"api_name": "pyramid.httpexceptions.HTTPBadRequest", "line_number": 25, "usage_type": "call"}, {"api_name": "prodnet.models.BidRecord", "line_number": 32, "usage_type": "call"}, {"api_name": "pyramid.httpexceptions.HTTPBadRequest", "line_number": 37, "usage_type": "call"}, {"api_name": "prodnet.models.Bid", "line_number": 42, "usage_type": "call"}, {"api_name": "prodnet.util._", "line_number": 47, "usage_type": "call"}, {"api_name": "prodnet.util._", "line_number": 48, "usage_type": "call"}, {"api_name": "prodnet.util._", "line_number": 49, "usage_type": "call"}, {"api_name": "prodnet.models.DBSession.flush", "line_number": 50, "usage_type": "call"}, {"api_name": "prodnet.models.DBSession", "line_number": 50, "usage_type": "name"}, {"api_name": "prodnet.util.dictify", "line_number": 52, "usage_type": "call"}, {"api_name": "pyramid.view.view_config", "line_number": 20, "usage_type": "call"}, {"api_name": "pyramid.httpexceptions.HTTPNotFound", "line_number": 64, "usage_type": "call"}, {"api_name": "pyramid.httpexceptions.HTTPBadRequest", "line_number": 67, "usage_type": "call"}, {"api_name": "prodnet.models.DBSession.delete", "line_number": 69, "usage_type": "call"}, {"api_name": "prodnet.models.DBSession", "line_number": 69, "usage_type": "name"}, {"api_name": "prodnet.util._", "line_number": 74, "usage_type": "call"}, {"api_name": "prodnet.util._", "line_number": 75, "usage_type": "call"}, {"api_name": "pyramid.view.view_config", "line_number": 61, "usage_type": "call"}, {"api_name": "pyramid.httpexceptions.HTTPBadRequest", "line_number": 86, "usage_type": "call"}, {"api_name": "pyramid.httpexceptions.HTTPNotFound", "line_number": 88, "usage_type": "call"}, {"api_name": "pyramid.httpexceptions.HTTPOk", "line_number": 90, "usage_type": "call"}, {"api_name": "pyramid.view.view_config", "line_number": 83, "usage_type": "call"}, {"api_name": "pyramid.view.view_defaults", "line_number": 8, "usage_type": "call"}]}
+{"seq_id": "258219933", "text": "# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Import\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n# Import Standard libraries\nimport tensorflow as tf\nimport numpy as np \nimport matplotlib.cm as cm\nfrom IPython.display import Image, display\n\n\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Functions\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\ndef save_and_display_gradcam(img, heatmap,idx, cam_path=\"cam.jpg\", alpha=0.4):\n # Load the original image\n #img = tf.keras.preprocessing.image.load_img(img_path)\n img = tf.keras.preprocessing.image.img_to_array(img)\n\n # Rescale heatmap to a range 0-255\n heatmap = np.uint8(255 * heatmap)\n\n # Use jet colormap to colorize heatmap\n jet = cm.get_cmap(\"jet\")\n\n # Use RGB values of the colormap\n jet_colors = jet(np.arange(256))[:, :3]\n jet_heatmap = jet_colors[heatmap]\n\n # Create an image with RGB colorized heatmap\n jet_heatmap = tf.keras.preprocessing.image.array_to_img(jet_heatmap)\n jet_heatmap = jet_heatmap.resize((img.shape[1], img.shape[0]))\n jet_heatmap = tf.keras.preprocessing.image.img_to_array(jet_heatmap)\n\n # Superimpose the heatmap on original image\n superimposed_img = jet_heatmap * alpha + img\n superimposed_img = tf.keras.preprocessing.image.array_to_img(superimposed_img)\n\n # Save the superimposed image\n superimposed_img.save(\"cam_\" + str(idx) + \".jpg\")\n\n # Display Grad CAM\n #display(Image(cam_path))\n\n\ndef make_gradcam_heatmap(\n model\n , image\n , pred_index = None\n):\n # Check for the latest convolution layer with a 4D output\n for layer in reversed(model.layers):\n if len(layer.output_shape) == 4:\n last_conv_layer_name = layer.name\n break\n\n # First, we create a model that maps the input image to the activations of the last conv layer as well as the output\n # predictions\n grad_model = tf.keras.models.Model(\n [ model.inputs ]\n , [ model.get_layer(last_conv_layer_name).output, model.output ]\n )\n\n # Then, we compute the gradient of the top predicted class for our input image with respect to the activations of\n # the last conv layer\n with tf.GradientTape() as tape:\n last_conv_layer_output, preds = grad_model(image)\n if pred_index is None:\n pred_index = tf.argmax(preds[0])\n class_channel = preds[:, pred_index]\n\n # This is the gradient of the output neuron (top predicted or chosen) with regard to the output feature map of the\n # last conv layer\n grads = tape.gradient(class_channel, last_conv_layer_output)\n\n # This is a vector where each entry is the mean intensity of the gradient over a specific feature map channel\n pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))\n\n # We multiply each channel in the feature map array by \"how important this channel is\" with regard to the top\n # predicted class then sum all the channels to obtain the heatmap class activation\n last_conv_layer_output = last_conv_layer_output[0]\n heatmap = last_conv_layer_output @ pooled_grads[..., tf.newaxis]\n heatmap = tf.squeeze(heatmap)\n\n # For visualization purpose, we will also normalize the heatmap between 0 & 1\n heatmap = tf.maximum(heatmap, 0) / tf.math.reduce_max(heatmap)\n return heatmap.numpy()\n", "sub_path": "streamlit/model/interpretability.py", "file_name": "interpretability.py", "file_ext": "py", "file_size_in_byte": 3262, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "tensorflow.keras.preprocessing.image.img_to_array", "line_number": 18, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 18, "usage_type": "attribute"}, {"api_name": "numpy.uint8", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.cm.get_cmap", "line_number": 24, "usage_type": "call"}, {"api_name": "matplotlib.cm", "line_number": 24, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 27, "usage_type": "call"}, {"api_name": "tensorflow.keras.preprocessing.image.array_to_img", "line_number": 31, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 31, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.preprocessing.image.img_to_array", "line_number": 33, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 33, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.preprocessing.image.array_to_img", "line_number": 37, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 37, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.models.Model", "line_number": 59, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 59, "usage_type": "attribute"}, {"api_name": "tensorflow.GradientTape", "line_number": 66, "usage_type": "call"}, {"api_name": "tensorflow.argmax", "line_number": 69, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 77, "usage_type": "call"}, {"api_name": "tensorflow.newaxis", "line_number": 82, "usage_type": "attribute"}, {"api_name": "tensorflow.squeeze", "line_number": 83, "usage_type": "call"}, {"api_name": "tensorflow.maximum", "line_number": 86, "usage_type": "call"}, {"api_name": "tensorflow.math.reduce_max", "line_number": 86, "usage_type": "call"}, {"api_name": "tensorflow.math", "line_number": 86, "usage_type": "attribute"}]}
+{"seq_id": "458874653", "text": "import tokenize\nfrom collections import defaultdict, OrderedDict\nimport six\n\n\nSTATE_LABEL = 256\nops = set(['&=', '<<', '<=', '==', '[', '//=', '%=', '^', ']',\n '~', '//', '|=', '-=', '}', '^=', '!=', '>=', '>>',\n '<', '**=', '>>=', '*=', '+=', ';', ':', '/=', '<<=',\n '>', '=', '|', '{', '**', '@', '&', '%', '+', '*',\n ')', '(', '.', '-', ',', '<>', '...', '->'])\nnormal_tks = set(['NAME', 'STRING', 'NUMBER', 'INDENT',\n 'DEDENT', 'NEWLINE', 'ENDMARKER'])\n\nclass Label(object):\n __slots__ = 'type', 'val'\n\n def __init__(self, type, val=None):\n self.type = type\n self.val = val\n\n @classmethod\n def get_label(cls, label):\n if label[0] == \"'\":\n if label[-1] != \"'\" or len(label) < 3:\n raise Exception('invalid label: %r' % label)\n label = label[1:-1]\n if label in ops:\n return cls(tokenize.OP, label)\n return cls(tokenize.NAME, label)\n elif label in normal_tks:\n return cls(getattr(tokenize, label))\n\n\nclass State(object):\n __slots__ = 'is_final', 'name', 'symbol', 'arcs', 'bootstrap'\n\n def __init__(self, is_final, name=None, symbol=None):\n self.is_final = is_final\n self.name = name\n self.symbol = symbol\n self.arcs = {}\n\n def __repr__(self):\n if self.name is not None:\n return '' % self.name\n return super(State, self).__repr__()\n\n def arc(self, label, state):\n if label in self.arcs:\n raise Exception('duplicated arc')\n self.arcs[label] = state\n\n def build_bootstrap(self):\n if not hasattr(self, 'bootstrap'):\n self.bootstrap = defaultdict(lambda: {})\n for label, state in self.arcs.items():\n if label.type == STATE_LABEL:\n if label.val == self:\n continue\n for t, vals in label.val.build_bootstrap().items():\n for val in vals.keys():\n if val in self.bootstrap[t]:\n raise Exception('duplicated bootstrap')\n self.bootstrap[t][val] = (label.val, state)\n else:\n self.bootstrap[label.type][label.val] = (None, state)\n return self.bootstrap\n\n def generate(self, name, ids):\n myid = ids[self]\n varname = '%s%d' % (name, myid)\n if myid == 0:\n yield '%s = %s\\n' % (varname, self.name)\n else:\n yield '%s = State(%r)\\n' % (varname, self.is_final)\n\n for label, state in self.arcs.items():\n if state not in ids:\n yield from state.generate(name, ids)\n if label.type == STATE_LABEL:\n yield '%s.arc(Label(%d, %s), %s%d)\\n' % (varname,\n label.type, label.val.name, name, ids[state])\n else:\n yield '%s.arc(Label(%d, %r), %s%d)\\n' % (varname,\n label.type, label.val, name, ids[state])\n yield '%s.bootstrap = {' % varname\n for t, vals in self.bootstrap.items():\n yield '\\n %d: {' % t\n for v, (st1, st2) in vals.items():\n yield '\\n %r: (' % v\n if st1 is None:\n yield 'None'\n else:\n yield '%s' % st1.name\n yield ', %s%d),' % (name, ids[st2])\n yield '},'\n yield '}\\n'\n\n\nclass IDs(object):\n def __init__(self):\n self.inc = 0\n self.m = {}\n\n def __getitem__(self, k):\n i = self.m.get(k, None)\n if i is None:\n i = self.inc\n self.inc += 1\n self.m[k] = i\n return i\n\n def __contains__(self, k):\n return k in self.m\n\n\nclass States(object):\n def __init__(self, **states):\n self.all_states = []\n self.states = OrderedDict()\n self.symbols = {} # name -> id\n self.inc = STATE_LABEL\n self.reverse_symbol = {} # id -> name\n for name, state in states.items():\n self[name] = state\n\n def __setitem__(self, name, state):\n self.inc += 1\n self.symbols[name] = self.inc\n self.reverse_symbol[self.inc] = name\n self.states[name] = state\n stack = [state]\n states = set([state])\n while stack:\n st = stack[0]\n stack = stack[1:]\n for s in st.arcs.values():\n if s not in states:\n self.all_states.append(s)\n stack.append(s)\n states.add(s)\n self.all_states.append(state)\n\n def __getitem__(self, k):\n if isinstance(k, int):\n k = self.reverse_symbol[k]\n return self.states[k]\n\n def __iter__(self):\n yield from self.states\n\n def keys(self):\n yield from self.states.keys()\n\n def items(self):\n yield from self.states.items()\n\n def from_dfas(self, dfas):\n states = {}\n def dfa2state(dfa):\n state = states.get(dfa, None)\n if state is not None:\n return state\n state = State(dfa.is_final)\n states[dfa] = state\n for name, d in dfa.arcs.items():\n label = Label.get_label(name)\n if label is None:\n label = Label(STATE_LABEL,\n dfa2state(dfas[name][0]))\n state.arc(label, dfa2state(d))\n return state\n for name, dfa in dfas.items():\n dfa2state(dfa[0])\n for name, dfa in dfas.items():\n state = states[dfa[0]]\n state.name = name\n self[name] = state\n\n def build_bootstrap(self):\n for state in self.all_states:\n state.build_bootstrap()\n\n def generate(self):\n buf = six.StringIO()\n buf.write('# generated by cpy.parser.state.States\\n')\n buf.write('from .grammar.state import State, Label\\n')\n buf.write('from .grammar.symbols import Symbols\\n\\n\\n')\n\n buf.write('class _Symbols(Symbols):\\n')\n for i, name in enumerate(self.states.keys()):\n buf.write(' %s = %d\\n' % (name, i + STATE_LABEL + 1))\n buf.write('symbols = _Symbols()\\n\\n\\n')\n\n for i, (name, state) in enumerate(self.states.items()):\n buf.write('%s = State(%r, %r, %d)\\n' % (\n name, state.is_final, name, STATE_LABEL + i + 1))\n for name, state in self.states.items():\n buf.write('\\n\\n')\n buf.write(''.join(state.generate(name, IDs())))\n return buf.getvalue()\n", "sub_path": "cpy/parser/grammar/state.py", "file_name": "state.py", "file_ext": "py", "file_size_in_byte": 6645, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "tokenize.OP", "line_number": 29, "usage_type": "attribute"}, {"api_name": "tokenize.NAME", "line_number": 30, "usage_type": "attribute"}, {"api_name": "collections.defaultdict", "line_number": 56, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 121, "usage_type": "call"}, {"api_name": "six.StringIO", "line_number": 186, "usage_type": "call"}]}
+{"seq_id": "38512234", "text": "import numpy as np\nimport scipy.optimize as opt\nfrom lrCostFunction import lrCostFunction\n\n# ONEVSALL trains multiple logistic regression classifiers and returns all\n# the classifiers in a matrix all_theta, where the i-th row of all_theta \n# corresponds to the classifier for label i\n# [all_theta] = ONEVSALL(X, y, num_labels, lambda) trains num_labels\n# logistic regression classifiers and returns each of these classifiers\n# in a matrix all_theta, where the i-th row of all_theta corresponds \n# to the classifier for label i\n\ndef oneVsAll(X, y, num_labels, l):\n# Some useful variables\n m, n = X.shape\n all_theta = np.zeros((num_labels, n + 1))\n X = np.hstack((np.ones((m, 1)), X))\n initial_theta = np.zeros(n + 1)\n\n # ====================== YOUR CODE HERE ======================\n # Instructions: You should complete the following code to train num_labels\n # logistic regression classifiers with regularization\n # parameter lambda.\n #\n # Hint: theta(:) will return a column vector.\n #\n # Hint: You can use y == c to obtain a vector of 1's and 0's that tell you\n # whether the ground truth is true/false for this class.\n #\n # Note: For this assignment, we recommend using fmincg to optimize the cost\n # function. It is okay to use a for-loop (for c = 1:num_labels) to\n # loop over the different classes.\n #\n # fmincg works similarly to fminunc, but is more efficient when we\n # are dealing with large number of parameters.\n\n for i in range(0, num_labels):\n label = 10 if i == 0 else i\n result = opt.minimize(fun=lrCostFunction, x0=initial_theta, args=(X, (y == label).astype(int), l), method='TNC', jac=True)\n all_theta[i, :] = result.x\n\n\n return all_theta\n", "sub_path": "3. Neural Networks Representation/oneVsAll.py", "file_name": "oneVsAll.py", "file_ext": "py", "file_size_in_byte": 1827, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "numpy.zeros", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 18, "usage_type": "call"}, {"api_name": "scipy.optimize.minimize", "line_number": 39, "usage_type": "call"}, {"api_name": "scipy.optimize", "line_number": 39, "usage_type": "name"}, {"api_name": "lrCostFunction.lrCostFunction", "line_number": 39, "usage_type": "name"}]}
+{"seq_id": "163709940", "text": "\"\"\"\nCopyright 2021 The Magma Authors.\n\nThis source code is licensed under the BSD-style license found in the\nLICENSE file in the root directory of this source tree.\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport os\nimport sys\nimport json\n\nimport click\nfrom boto3 import Session\n\nfrom .common import (\n run_command,\n run_playbook,\n print_error_msg,\n print_warning_msg,\n print_success_msg)\n\ndef setup_aws_creds():\n session = Session()\n creds = session.get_credentials()\n if not creds:\n print_error_msg('''\nAWS credentials not configured.\nconfigure through awscli or through orcl\norcl configure set -k aws_access_key_id -v \norcl configure set -k aws_secret_access_key -v \norcl configure set -k region -v \n''')\n sys.exit(1)\n\n frozen_creds = creds.get_frozen_credentials()\n os.environ[\"AWS_ACCESS_KEY_ID\"] = frozen_creds.access_key\n os.environ[\"AWS_SECRET_ACCESS_KEY\"] = frozen_creds.secret_key\n\n\n@click.group(invoke_without_command=True)\n@click.pass_context\ndef cleanup(ctx):\n \"\"\"\n Removes resources deployed for orc8r\n \"\"\"\n tf_destroy = [ \"terraform\", \"destroy\", \"-auto-approve\"]\n\n if ctx.invoked_subcommand is None:\n cmd = \" \".join(tf_destroy)\n click.echo(f\"Following commands will be run during cleanup\\n{cmd}\")\n click.confirm('Do you want to continue with cleanup?', abort=True)\n click.echo(f\"Running {cmd}\")\n rc = run_command(tf_destroy)\n if rc != 0:\n print_error_msg(\"Destroy Failed!!! Attempt cleaning up individual resources using 'orcl cleanup raw' subcommand\")\n return\n\n@cleanup.command()\n@click.pass_context\n@click.option('--dryrun', default=False, is_flag=True, help='Show resources to be cleaned up during raw cleanup')\n@click.option('--state', help='Provide state file containing resource information e.g. terraform.tfstate or terraform.tfstate.backup')\n@click.option('--values', multiple=True, help='Key value pairs. for e.g. cluster_name,orc8r. Can be used multiple times')\ndef raw(ctx, dryrun, state, values):\n \"\"\"\n Individually cleans up resources deployed for orc8r\n \"\"\"\n click.confirm(click.style('This is irreversable!! Do you want to continue with cleanup?', fg='red'), abort=True)\n if state:\n ctx.obj['cleanup_state'] = state\n\n # add additional items\n for config_items in values:\n k, v = config_items.split(\",\")\n ctx.obj[k] = v\n\n extra_vars = json.dumps(ctx.obj)\n cleanup_playbook = \"%s/cleanup.yml\" % ctx.obj[\"playbooks\"]\n playbook_args = [ \"ansible-playbook\", \"-v\", \"-e\", extra_vars]\n\n # Few boto dependent modules in ansible require these values to be\n # setup as environment variables. Hence setting these up.\n setup_aws_creds()\n\n if dryrun:\n tag_args = [\"-t\", \"cleanup_dryrun\"]\n else:\n tag_args = [\"-t\", \"cleanup\"]\n\n rc = run_playbook(playbook_args + tag_args + [cleanup_playbook])\n if rc != 0:\n print_error_msg(\"Failed cleaning up resources!!!\")\n sys.exit(1)\n print_success_msg(\"Successfully cleaned up underlying resources\")", "sub_path": "orc8r/cloud/deploy/orc8r_deployer/docker/root/scripts/cli/cleanup.py", "file_name": "cleanup.py", "file_ext": "py", "file_size_in_byte": 3396, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "boto3.Session", "line_number": 28, "usage_type": "call"}, {"api_name": "common.print_error_msg", "line_number": 31, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 38, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 41, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 42, "usage_type": "attribute"}, {"api_name": "click.echo", "line_number": 55, "usage_type": "call"}, {"api_name": "click.confirm", "line_number": 56, "usage_type": "call"}, {"api_name": "click.echo", "line_number": 57, "usage_type": "call"}, {"api_name": "common.run_command", "line_number": 58, "usage_type": "call"}, {"api_name": "common.print_error_msg", "line_number": 60, "usage_type": "call"}, {"api_name": "click.group", "line_number": 45, "usage_type": "call"}, {"api_name": "click.pass_context", "line_number": 46, "usage_type": "attribute"}, {"api_name": "click.confirm", "line_number": 72, "usage_type": "call"}, {"api_name": "click.style", "line_number": 72, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 81, "usage_type": "call"}, {"api_name": "common.run_playbook", "line_number": 94, "usage_type": "call"}, {"api_name": "common.print_error_msg", "line_number": 96, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 97, "usage_type": "call"}, {"api_name": "common.print_success_msg", "line_number": 98, "usage_type": "call"}, {"api_name": "click.pass_context", "line_number": 64, "usage_type": "attribute"}, {"api_name": "click.option", "line_number": 65, "usage_type": "call"}, {"api_name": "click.option", "line_number": 66, "usage_type": "call"}, {"api_name": "click.option", "line_number": 67, "usage_type": "call"}]}
+{"seq_id": "124128885", "text": "import time\nimport random\nimport string\nimport serial.tools.list_ports\n\nfor port in serial.tools.list_ports.comports():\n if port.vid == 6790 and port.pid == 29987:\n try:\n print(\"Found \" + port.device)\n ser = serial.Serial(port.device, 115200) # open serial port\n app_eui = ''.join(random.SystemRandom().choice(string.hexdigits) for _ in range(16))\n app_key = ''.join(random.SystemRandom().choice(string.hexdigits) for _ in range(32))\n print(\"App EUI will be \" + app_eui)\n print(\"App Key will be \" + app_key)\n print(ser.name) # check which port was really used\n cmd = 'at+set_config=app_eui:' + app_eui + '&app_key:' + app_key + '\\r\\n'\n ser.write(cmd.encode('ASCII'))\n time.sleep(5)\n ser.close()\n print(\"Initialized \" + port.device)\n except:\n print(\"Cannot initialize \" + port.device)\n\n", "sub_path": "install/scripts/reset_loranode.py", "file_name": "reset_loranode.py", "file_ext": "py", "file_size_in_byte": 954, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "serial.tools.list_ports.tools.list_ports.comports", "line_number": 6, "usage_type": "call"}, {"api_name": "serial.tools.list_ports.tools", "line_number": 6, "usage_type": "attribute"}, {"api_name": "serial.tools.list_ports", "line_number": 6, "usage_type": "name"}, {"api_name": "serial.tools.list_ports.Serial", "line_number": 10, "usage_type": "call"}, {"api_name": "serial.tools.list_ports", "line_number": 10, "usage_type": "name"}, {"api_name": "random.SystemRandom", "line_number": 11, "usage_type": "call"}, {"api_name": "string.hexdigits", "line_number": 11, "usage_type": "attribute"}, {"api_name": "random.SystemRandom", "line_number": 12, "usage_type": "call"}, {"api_name": "string.hexdigits", "line_number": 12, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 18, "usage_type": "call"}]}
+{"seq_id": "182008044", "text": "#!/usr/bin/python3\n\nimport sqlite3\nimport re\nimport unicodedata\n\nfrom bs4 import BeautifulSoup\nfrom pprint import pprint\nfrom urllib.request import Request, urlopen\nfrom urllib.error import URLError, HTTPError\n\n\nclass amd_fx_cpus_mining:\n def parser(self, url, pn_list):\n\n conn = sqlite3.connect('components.db')\n c = conn.cursor()\n\n user_agent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:43.0'\n\n try:\n q = Request(url)\n q.add_header('User-Agent', user_agent)\n html = urlopen(q).read()\n except HTTPError as e:\n print('The server couldn\\'t fulfill the request.')\n print('Error code: ', e.code)\n print('Error message: ', e.msg)\n except URLError as e:\n print('We failed to reach a server.')\n print('Reason: ', e.reason)\n else:\n soup = BeautifulSoup(html, \"html.parser\")\n for pn in pn_list:\n sliced_pn = pn[0:9]\n pn_element = soup.find(text=sliced_pn) # in BeatifulSoup 4.4 text became string\n if pn_element is None:\n for column in soup.find_all('td'): # BeautifulSoup won't find text inside
tag\n if sliced_pn in column.get_text():\n pn_element = column # if column with the given pn was found, take the whole element for\n # research\n # try-except block in case cpu was not found in wikipedia\n try:\n cpu_row = pn_element.find_parent('tr')\n except AttributeError:\n c.execute(\"UPDATE cpu SET core_clock = ?, no_of_cores = ?, l2_l3_cache = ?, \"\n \"tdp = ? WHERE pn = ?\", (-1, -1, -1, -1, pn))\n continue\n\n # Declaring variables for the new cpu and the db\n no_of_cores = -1\n no_of_cores_found = False\n core_clock = -1\n core_clock_found = False\n l_cache = -1\n l2_cache_found = False\n tdp = -1\n tdp_found = False\n unicoded_space = unicodedata.normalize(\"NFKD\", '\\xa0')\n i = 0\n\n while not (no_of_cores_found is True and core_clock_found is True and l2_cache_found is True\n and tdp_found is True):\n # If cell was merged, try to find the previous cell that has the desired info\n if i != 0:\n cpu_row = cpu_row.find_previous('tr')\n\n for i, column in enumerate(cpu_row.find_all('td')):\n if pn == 'FD837EWMHKBOX':\n core_clock = 3.3\n core_clock_found = True\n elif pn == 'FD9590FHHKWOF':\n core_clock = 4.7\n core_clock_found = True\n\n # cpu_row is the row of our cpu and main_cpu_row is the row of the info that is shared\n if i == 1 and re.search(r'[0-9][0-9]?/[0-9][0-9]?',\n column.get_text()) and no_of_cores_found is False:\n no_of_cores = column.get_text()\n if no_of_cores.find('/') != -1:\n index = no_of_cores.find('/')\n no_of_cores = no_of_cores[0:index]\n no_of_cores = int(no_of_cores)\n no_of_cores_found = True\n elif 'Hz' in column.get_text() and (\n 'V)' not in column.get_text() or i == 7) and core_clock_found is False:\n core_clock = column.get_text()\n index = core_clock.find('GHz')\n core_clock = core_clock[0:index]\n # Fix the code of spaces (latin-1) for the sqlite3 db\n core_clock = core_clock.replace('\\xa0', unicoded_space)\n core_clock = core_clock.strip()\n core_clock = float(core_clock)\n core_clock_found = True\n elif ('MB' in column.get_text() or 'kB' in column.get_text()) and l2_cache_found is False:\n l2_cache = column.get_text()\n # Fix the code of spaces (latin-1) for the sqlite3 db\n l2_cache = l2_cache.replace('\\xa0', unicoded_space)\n if 'MB' in l2_cache:\n l2_cache = l2_cache.replace('MB', '').strip()\n if '×' in l2_cache:\n index = l2_cache.find('×')\n element1 = int(l2_cache[0:index])\n element2 = int(l2_cache[index + 1:])\n l2_cache = element1 * element2 * 1024\n else:\n l2_cache = int(l2_cache) * 1024\n elif 'kB' in l2_cache:\n l2_cache = l2_cache.replace('kB', '')\n if '×' in l2_cache:\n index = l2_cache.find('×')\n element1 = int(l2_cache[0:index])\n element2 = int(l2_cache[index + 1:])\n l2_cache = element1 * element2\n else:\n l2_cache = int(l2_cache)\n l2_cache_found = True\n # Try to find l3 cache in the next td\n l3_cache = 0\n if 'MB' in cpu_row.find_all('td')[i + 1].get_text() or 'KB' in cpu_row.find_all('td')[\n i + 1].get_text():\n l3_cache = cpu_row.find_all('td')[i + 1].get_text()\n # Fix the code of spaces (latin-1) for the sqlite3 db\n l3_cache = l3_cache.replace('\\xa0', unicoded_space)\n if 'MB' in l3_cache:\n l3_cache = l3_cache.replace('MB', '').strip()\n if '×' in l3_cache:\n index = l3_cache.find('×')\n element1 = int(l3_cache[0:index])\n element2 = int(l3_cache[index + 1:])\n l3_cache = element1 * element2 * 1024\n else:\n l3_cache = int(l3_cache) * 1024\n elif 'KB' in l3_cache:\n l3_cache = l3_cache.replace('KB', '')\n if '×' in l3_cache:\n index = l3_cache.find('×')\n element1 = int(l3_cache[0:index])\n element2 = int(l3_cache[index + 1:])\n l3_cache = element1 * element2\n else:\n l3_cache = int(l2_cache)\n l_cache = l2_cache + l3_cache\n elif re.search(r'^[0-9]{1,4}\\s*W$', column.get_text()) and tdp_found is False:\n tdp = column.get_text()\n tdp = tdp.replace('W', '').strip()\n # Fix the code of spaces (latin-1) for the sqlite3 db\n tdp = tdp.replace('\\xa0', unicoded_space)\n tdp = int(tdp)\n tdp_found = True\n\n c.execute(\"UPDATE cpu SET core_clock = ?, no_of_cores = ?, l2_l3_cache = ?, \"\n \"tdp = ? WHERE pn = ?\", (core_clock, no_of_cores, l_cache, tdp, pn))\n\n conn.commit()\n conn.close()\n\n return\n", "sub_path": "amd_fx_cpus_mining.py", "file_name": "amd_fx_cpus_mining.py", "file_ext": "py", "file_size_in_byte": 8315, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "sqlite3.connect", "line_number": 16, "usage_type": "call"}, {"api_name": "urllib.request.Request", "line_number": 22, "usage_type": "call"}, {"api_name": "urllib.request.urlopen", "line_number": 24, "usage_type": "call"}, {"api_name": "urllib.error.HTTPError", "line_number": 25, "usage_type": "name"}, {"api_name": "urllib.error.URLError", "line_number": 29, "usage_type": "name"}, {"api_name": "bs4.BeautifulSoup", "line_number": 33, "usage_type": "call"}, {"api_name": "unicodedata.normalize", "line_number": 59, "usage_type": "call"}, {"api_name": "re.search", "line_number": 77, "usage_type": "call"}, {"api_name": "re.search", "line_number": 144, "usage_type": "call"}]}
+{"seq_id": "8626824", "text": "from __future__ import print_function\n\nimport argparse\nimport sys\n\nimport onthego.download\nimport onthego.spotify.auth\n\n\ndef download_playlist():\n parser = argparse.ArgumentParser(description=\"Download the tracks of a Spotify playlist from YouTube\")\n parser.add_argument(\"-S\", \"--no-skip\", action='store_true',\n help=\"Don't skip files that were already downloaded.\")\n parser.add_argument(\"-C\", \"--no-convert\", action='store_true',\n help=\"Don't convert audio files to mp3 format.\")\n parser.add_argument(\"playlist\", help=\"Name of playlist. E.g: 'Road music'\")\n parser.add_argument(\"dst\", help=\"Destination directory\")\n args = parser.parse_args()\n\n spotify_client = onthego.spotify.auth.Client()\n try:\n for track in spotify_client.iter_tracks(args.playlist):\n onthego.download.audio(track, args.dst,skip_existing=(not args.no_skip), convert_to_mp3=(not args.no_convert))\n except onthego.spotify.auth.PlaylistNotFound as e:\n print(\"Playlist '%s' was not found. Did you type its name correctly?\" % e.playlist_name)\n sys.exit(1)\n", "sub_path": "onthego/scripts/cli.py", "file_name": "cli.py", "file_ext": "py", "file_size_in_byte": 1104, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 11, "usage_type": "call"}, {"api_name": "onthego.download.spotify.auth.Client", "line_number": 20, "usage_type": "call"}, {"api_name": "onthego.download.spotify", "line_number": 20, "usage_type": "attribute"}, {"api_name": "onthego.download", "line_number": 20, "usage_type": "name"}, {"api_name": "onthego.download.download.audio", "line_number": 23, "usage_type": "call"}, {"api_name": "onthego.download.download", "line_number": 23, "usage_type": "attribute"}, {"api_name": "onthego.download", "line_number": 23, "usage_type": "name"}, {"api_name": "onthego.download.spotify", "line_number": 24, "usage_type": "attribute"}, {"api_name": "onthego.download", "line_number": 24, "usage_type": "name"}, {"api_name": "sys.exit", "line_number": 26, "usage_type": "call"}]}
+{"seq_id": "644332668", "text": "from __future__ import print_function\nimport numpy as np\nimport preprocessing as proc\nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\n\n# Training settings\nparser = argparse.ArgumentParser(description='BASE Model')\nparser.add_argument('--batch-size', type=int, default=64, metavar='N',\n help='input batch size for training (default: 64)')\nparser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',\n help='input batch size for testing (default: 1000)')\nparser.add_argument('--epochs', type=int, default=20, metavar='N',\n help='number of epochs to train (default: 20)')\nparser.add_argument('--lr', type=float, default=0.01, metavar='LR',\n help='learning rate (default: 0.01)')\nparser.add_argument('--momentum', type=float, default=0.5, metavar='M',\n help='SGD momentum (default: 0.5)')\nparser.add_argument('--no-cuda', action='store_true', default=True,\n help='disables CUDA training')\nparser.add_argument('--seed', type=int, default=0, metavar='S',\n help='random seed (default: 0)')\nparser.add_argument('--log-interval', type=int, default=10, metavar='N',\n help='how many batches to wait before logging training status')\nargs = parser.parse_args()\nargs.cuda = not args.no_cuda and torch.cuda.is_available()\n\ntorch.manual_seed(args.seed)\nif args.cuda:\n torch.cuda.manual_seed(args.seed)\n\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(1, 20, kernel_size=5, stride=1, padding=0)\n self.conv2 = nn.Conv2d(20, 50, kernel_size=5, stride=1, padding=0)\n self.fc1 = nn.Linear(4*4*50, 500)\n self.fc2 = nn.Linear(500, 10)\n self.bn1 = nn.BatchNorm2d(20)\n self.bn2 = nn.BatchNorm2d(50)\n self.bn3 = nn.BatchNorm1d(500)\n self.drop = nn.Dropout(p=0.5)\n\n def forward(self, x):\n x = self.conv1(x)\n x = F.max_pool2d(self.bn1(x), 2)\n x = self.conv2(x)\n x = F.max_pool2d(self.bn2(x), 2)\n x = x.view(-1, 4*4*50)\n x = self.fc1(x)\n x = F.relu(self.bn3(x))\n x = self.fc2(x)\n x = self.drop(x)\n return F.log_softmax(x)\n\nmodel = Net()\n# print(model)\nif args.cuda:\n model.cuda()\n\noptimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum)\n\n\ndef generate_data(data, label, batchSize, data_type='train', shuffle=True):\n assert batchSize > 0\n data_len = data.shape[0]\n total_batch = data_len / batchSize + (1 if data_len % batchSize != 0 else 0)\n if shuffle:\n indices = np.random.permutation(data_len)\n data = data[indices]\n label = label[indices]\n for idx in range(total_batch):\n start = idx * batchSize\n end = min((idx + 1) * batchSize, data_len)\n if data_type == 'train':\n yield proc.Normalize(data[start:end], (proc.TRAIN_MEAN,)*(end-start),\n (proc.TRAIN_STD,)*(end-start)), label[start:end]\n else:\n yield proc.Normalize(data[start:end], (proc.TRAIN_MEAN,)*(end-start),\n (proc.TRAIN_STD,)*(end-start)), label[start:end]\n\n\ndef train(epoch, train_data, train_labels, use_data_len=10000):\n model.train() # set to training mode\n batch_idx = 1\n for (_data, _target) in generate_data(train_data[:use_data_len], train_labels[:use_data_len], batchSize=args.batch_size, shuffle=True):\n data = torch.from_numpy(_data)\n target = torch.from_numpy(_target).long()\n if args.cuda:\n data, target = data.cuda(), target.cuda()\n data, target = Variable(data), Variable(target)\n # print(data.size(), target.size())\n optimizer.zero_grad()\n output = model.forward(data)\n # print(output.size())\n loss = F.nll_loss(output, target)\n loss.backward()\n optimizer.step()\n if batch_idx % args.log_interval == 0:\n print('Train Epoch: {} [{:5d}/{} ({:2d}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), use_data_len,\n int(100. * batch_idx * len(data) / use_data_len), loss.data[0]))\n batch_idx += 1\n\n\ndef test(test_data, test_labels):\n model.eval() # set to evaluation mode\n test_loss = 0\n correct = 0\n for (data, target) in generate_data(test_data, test_labels,\n batchSize=args.batch_size, shuffle=True):\n data = torch.from_numpy(data)\n target = torch.from_numpy(target).long()\n if args.cuda:\n data, target = data.cuda(), target.cuda()\n data, target = Variable(data, volatile=True), Variable(target)\n output = model.forward(data)\n test_loss += F.nll_loss(output, target).data[0]\n pred = output.data.max(1)[1] # get the index of the max log-probability\n correct += pred.eq(target.data).cpu().sum()\n\n test_loss = test_loss\n test_loss /= test_data.shape[0] # loss function already averages over batch size\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.1f}%)\\n'.format(\n test_loss, correct, test_data.shape[0],\n 100. * correct / test_data.shape[0]))\n\n\ndef go():\n train_images, train_labels = proc.get_data(\"train\")\n test_images, test_labels = proc.get_data(\"test\")\n for epoch in range(1, args.epochs + 1):\n train(epoch, train_images, train_labels, 10000)\n test(test_images, test_labels)\n\ngo()\n", "sub_path": "CNN_for_Mnist/batchnormalization.py", "file_name": "batchnormalization.py", "file_ext": "py", "file_size_in_byte": 5629, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 12, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 30, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 30, "usage_type": "attribute"}, {"api_name": "torch.manual_seed", "line_number": 32, "usage_type": "call"}, {"api_name": "torch.cuda.manual_seed", "line_number": 34, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 34, "usage_type": "attribute"}, {"api_name": "torch.nn.Module", "line_number": 37, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 37, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 40, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 40, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 41, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 41, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 42, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 42, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 43, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 43, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 44, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 44, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 45, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 45, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm1d", "line_number": 46, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 46, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 47, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 47, "usage_type": "name"}, {"api_name": "torch.nn.functional.max_pool2d", "line_number": 51, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 51, "usage_type": "name"}, {"api_name": "torch.nn.functional.max_pool2d", "line_number": 53, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 53, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 56, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 56, "usage_type": "name"}, {"api_name": "torch.nn.functional.log_softmax", "line_number": 59, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 59, "usage_type": "name"}, {"api_name": "torch.optim.SGD", "line_number": 66, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 66, "usage_type": "name"}, {"api_name": "numpy.random.permutation", "line_number": 74, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 74, "usage_type": "attribute"}, {"api_name": "preprocessing.Normalize", "line_number": 81, "usage_type": "call"}, {"api_name": "preprocessing.TRAIN_MEAN", "line_number": 81, "usage_type": "attribute"}, {"api_name": "preprocessing.TRAIN_STD", "line_number": 82, "usage_type": "attribute"}, {"api_name": "preprocessing.Normalize", "line_number": 84, "usage_type": "call"}, {"api_name": "preprocessing.TRAIN_MEAN", "line_number": 84, "usage_type": "attribute"}, {"api_name": "preprocessing.TRAIN_STD", "line_number": 85, "usage_type": "attribute"}, {"api_name": "torch.from_numpy", "line_number": 92, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 93, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 96, "usage_type": "call"}, {"api_name": "torch.nn.functional.nll_loss", "line_number": 101, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 101, "usage_type": "name"}, {"api_name": "torch.from_numpy", "line_number": 117, "usage_type": "call"}, {"api_name": "torch.from_numpy", "line_number": 118, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 121, "usage_type": "call"}, {"api_name": "torch.nn.functional.nll_loss", "line_number": 123, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 123, "usage_type": "name"}, {"api_name": "preprocessing.get_data", "line_number": 135, "usage_type": "call"}, {"api_name": "preprocessing.get_data", "line_number": 136, "usage_type": "call"}]}
+{"seq_id": "157169457", "text": "# Convnet with Data augmentation, Regularization\nimport numpy\nimport keras\nfrom keras.preprocessing.image import ImageDataGenerator\nimport matplotlib.pyplot as plt\nfrom keras.datasets import cifar10\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Dropout\nfrom keras.layers import Flatten\nfrom keras.constraints import maxnorm\nfrom keras.optimizers import SGD\nfrom keras.layers.convolutional import Conv2D\nfrom keras.layers.convolutional import MaxPooling2D\nfrom keras.utils import np_utils\nfrom keras import backend as K\nK.set_image_dim_ordering('th')\n\n\nclass AccHistory_train(keras.callbacks.Callback):\n def on_train_begin(self, logs={}):\n self.accuracy = []\n\n def on_epoch_end(self, batch, logs={}):\n self.accuracy.append(logs.get('acc'))\n\n\nclass AccHistory_valid(keras.callbacks.Callback):\n def on_train_begin(self, logs={}):\n self.accuracy = []\n\n def on_epoch_end(self, batch, logs={}):\n self.accuracy.append(logs.get('val_acc'))\n\nseed = 7\nnumpy.random.seed(seed)\n\n(X_train, y_train), (X_test, y_test) = cifar10.load_data()\n\nX_train = X_train.astype('float32')\nX_test = X_test.astype('float32')\nX_train = X_train / 255.0\nX_test = X_test / 255.0\n\ny_train = np_utils.to_categorical(y_train)\ny_test = np_utils.to_categorical(y_test)\nnum_classes = y_test.shape[1]\n\n\nmodel = Sequential()\nmodel.add(Conv2D(32, (3, 3), input_shape=(3, 32, 32), activation='relu', padding='same'))\nmodel.add(Dropout(0.2))\nmodel.add(Conv2D(32, (3, 3), activation='relu', padding='same'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Conv2D(64, (3, 3), activation='relu', padding='same'))\nmodel.add(Dropout(0.2))\nmodel.add(Conv2D(64, (3, 3), activation='relu', padding='same'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Conv2D(128, (3, 3), activation='relu', padding='same'))\nmodel.add(Dropout(0.2))\nmodel.add(Conv2D(128, (3, 3), activation='relu', padding='same'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Flatten())\nmodel.add(Dropout(0.2))\nmodel.add(Dense(1024, activation='relu', kernel_constraint=maxnorm(3)))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(512, activation='relu', kernel_constraint=maxnorm(3)))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(num_classes, activation='softmax'))\n# Compile model\nepochs = 25\n\n# lrate = 0.01\n# decay = lrate/epochs\n# sgd = SGD(lr=lrate, momentum=0.9, decay=decay, nesterov=False)\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\nprint(model.summary())\n\n\nt_accuracy_history = AccHistory_train()\nv_accuracy_history = AccHistory_valid()\n\n# using keras ImageDataGenerator class for data augmentation\ndatagen = ImageDataGenerator(\n rotation_range=40,\n width_shift_range=0.2,\n shear_range=0.2,\n horizontal_flip=True,\n fill_mode='nearest')\n\n\n# compute quantities required for featurewise normalization\ndatagen.fit(X_train)\n\n# fits the model on batches with real-time data augmentation:\nmodel.fit_generator(datagen.flow(X_train, y_train, batch_size=100),\n samples_per_epoch=len(X_train), nb_epoch=epochs, validation_data=(X_test, y_test),\n callbacks=[t_accuracy_history, v_accuracy_history])\n\n# model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=epochs, batch_size=128,\n# callbacks=[t_accuracy_history, v_accuracy_history])\n# Final evaluation of the model\nscores = model.evaluate(X_test, y_test, verbose=0)\nprint(\"Accuracy: %.2f%%\" % (scores[1]*100))\n\n# model.save_weights('first_try_1.h5')\n\nta = t_accuracy_history.accuracy\nva = v_accuracy_history.accuracy\n\nfig, ax = plt.subplots()\nline_1, = ax.plot(ta, label='Inline label')\nline_2, = ax.plot(va, 'r-', label='Inline label')\n# Overwrite the label by calling the method.\nline_1.set_label('training set')\nline_2.set_label('validation set')\nax.legend()\nax.set_ylabel('Accuracy')\nax.set_title('convnet_reg_aug')\nax.set_xlabel('epoch')\nplt.show()", "sub_path": "convnet_reg_aug.py", "file_name": "convnet_reg_aug.py", "file_ext": "py", "file_size_in_byte": 3951, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "keras.backend.set_image_dim_ordering", "line_number": 17, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 17, "usage_type": "name"}, {"api_name": "keras.callbacks", "line_number": 20, "usage_type": "attribute"}, {"api_name": "keras.callbacks", "line_number": 28, "usage_type": "attribute"}, {"api_name": "numpy.random.seed", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 36, "usage_type": "attribute"}, {"api_name": "keras.datasets.cifar10.load_data", "line_number": 38, "usage_type": "call"}, {"api_name": "keras.datasets.cifar10", "line_number": 38, "usage_type": "name"}, {"api_name": "keras.utils.np_utils.to_categorical", "line_number": 45, "usage_type": "call"}, {"api_name": "keras.utils.np_utils", "line_number": 45, "usage_type": "name"}, {"api_name": "keras.utils.np_utils.to_categorical", "line_number": 46, "usage_type": "call"}, {"api_name": "keras.utils.np_utils", "line_number": 46, "usage_type": "name"}, {"api_name": "keras.models.Sequential", "line_number": 50, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.Conv2D", "line_number": 51, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 52, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.Conv2D", "line_number": 53, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.MaxPooling2D", "line_number": 54, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.Conv2D", "line_number": 55, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 56, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.Conv2D", "line_number": 57, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.MaxPooling2D", "line_number": 58, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.Conv2D", "line_number": 59, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 60, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.Conv2D", "line_number": 61, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.MaxPooling2D", "line_number": 62, "usage_type": "call"}, {"api_name": "keras.layers.Flatten", "line_number": 63, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 64, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 65, "usage_type": "call"}, {"api_name": "keras.constraints.maxnorm", "line_number": 65, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 66, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 67, "usage_type": "call"}, {"api_name": "keras.constraints.maxnorm", "line_number": 67, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 68, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 69, "usage_type": "call"}, {"api_name": "keras.preprocessing.image.ImageDataGenerator", "line_number": 84, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 111, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 111, "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": "589495372", "text": "from nmt.utils.argument import get_main_argument\r\nfrom nmt.utils.log import get_logger\r\nfrom os.path import join, exists\r\nfrom os import makedirs\r\nimport os\r\nimport torch\r\nimport json\r\n\r\n\r\ndef create_dir(dir_path):\r\n if not exists(dir_path):\r\n makedirs(dir_path)\r\n\r\n\r\nclass Context:\r\n def __init__(self, desc=\"Transformer\", config=None, logger=None):\r\n self.description = desc\r\n\r\n # A dictionary of Config Parameters\r\n self.config = get_main_argument(desc=self.description)\r\n if config is not None:\r\n self.config.update(config)\r\n\r\n self.project_name = self.config[\"project_name\"]\r\n self.phase = self.config[\"phase\"]\r\n\r\n self.project_raw_dir = str(self.config[\"project_raw_dir\"])\r\n create_dir(self.project_raw_dir)\r\n\r\n self.project_log = self.config[\"project_log\"]\r\n if not exists(self.project_log):\r\n self.project_log = join(os.path.dirname(self.project_raw_dir), 'logs', f'{self.phase}.log')\r\n create_dir(os.path.dirname(self.project_log))\r\n\r\n # logger interface\r\n self.isDebug = self.config[\"debug\"] == 'True'\r\n self.logger = get_logger(self.description, self.project_log, self.isDebug) if logger is None else logger\r\n self.logger.debug(\"The logger interface is initited ...\")\r\n\r\n self.project_config = self.config[\"project_config\"]\r\n if exists(self.project_config):\r\n with open(self.project_config) as f:\r\n self.config.update(json.load(f))\r\n else:\r\n create_dir(join(os.path.dirname(self.project_raw_dir), 'configs'))\r\n\r\n self.project_save_config = self.config[\"project_save_config\"]\r\n\r\n if self.project_save_config is True:\r\n config_filepath = join(os.path.dirname(self.project_raw_dir),\r\n 'configs',\r\n f'${self.project_name}_save_config.json')\r\n self.logger.debug(f\"Dump project configration to the file {config_filepath} ...\")\r\n with open(config_filepath, 'w') as config_file:\r\n json.dump(self.config, config_file)\r\n\r\n self.logger.debug(\"The Input Parameters:\")\r\n for key, val in self.config.items():\r\n self.logger.debug(f\"{key} => {val}\")\r\n\r\n self.project_processed_dir = self.config[\"project_processed_dir\"]\r\n create_dir(self.project_processed_dir)\r\n\r\n self.project_checkpoint = str(self.config[\"project_checkpoint\"])\r\n if not exists(self.project_checkpoint):\r\n create_dir(os.path.dirname(self.project_checkpoint))\r\n\r\n # Model Paramters\r\n self.d_model = self.config[\"d_model\"]\r\n self.layers_count = self.config[\"layers_count\"]\r\n self.heads_count = self.config[\"heads_count\"]\r\n self.d_ff = self.config[\"d_ff\"]\r\n self.dropout = self.config[\"dropout\"]\r\n self.label_smoothing = self.config[\"label_smoothing\"]\r\n self.optimizer = self.config[\"optimizer\"]\r\n self.lr = self.config[\"lr\"]\r\n self.clip_grads = self.config[\"clip_grads\"]\r\n self.batch_size = self.config[\"batch_size\"]\r\n self.epochs = self.config[\"epochs\"]\r\n self.vocabulary_size = self.config[\"vocabulary_size\"]\r\n self.padding_index = 0\r\n\r\n self.dataset_limit = self.config[\"dataset_limit\"]\r\n self.print_every = self.config[\"print_every\"]\r\n self.print_every = self.config[\"print_every\"]\r\n\r\n self.source = self.config[\"source\"]\r\n self.num_candidates = self.config[\"num_candidates\"]\r\n self.save_result = self.config[\"save_result\"]\r\n self.share_dictionary = self.config[\"share_dictionary\"]\r\n self.save_every = self.config[\"save_every\"]\r\n\r\n # Trainning Device Set up\r\n self.device = torch.device(self.config[\"device\"])\r\n self.device_id = list(self.config[\"device_id\"])\r\n self.is_cuda = self.config[\"device\"] == 'cuda'\r\n self.is_cpu = self.config[\"device\"] == 'cpu'\r\n self.is_gpu_parallel = self.is_cuda and (len(self.device_id) > 1)\r\n", "sub_path": "nmt/utils/context.py", "file_name": "context.py", "file_ext": "py", "file_size_in_byte": 4082, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "os.path.exists", "line_number": 11, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 12, "usage_type": "call"}, {"api_name": "nmt.utils.argument.get_main_argument", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 32, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 32, "usage_type": "call"}, {"api_name": "os.path", "line_number": 32, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 33, "usage_type": "call"}, {"api_name": "os.path", "line_number": 33, "usage_type": "attribute"}, {"api_name": "nmt.utils.log.get_logger", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 41, "usage_type": "call"}, {"api_name": "json.load", "line_number": 43, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path", "line_number": 45, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path", "line_number": 50, "usage_type": "attribute"}, {"api_name": "json.dump", "line_number": 55, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 65, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 66, "usage_type": "call"}, {"api_name": "os.path", "line_number": 66, "usage_type": "attribute"}, {"api_name": "torch.device", "line_number": 94, "usage_type": "call"}]}
+{"seq_id": "491549771", "text": "import matplotlib.pyplot as plt\nfrom tqdm import tqdm\n\n# fungsi untuk mendapatkan data node dari file\ndef getCoorNodesFromFile(cityOption):\n coorNodes = []\n fNodes = open(f'../data/{cityOption}/NodeData.txt', 'r').readlines()\n for line in fNodes:\n parseLine = [x for x in line.split()]\n x = float(parseLine[1])\n y = float(parseLine[2])\n coorNodes.append((x,y)) \n return coorNodes\n\n# fungsi untuk draw map nya\ndef drawMap(adjListAll, mapNodeToIdx, listPath, jumlahKurir, resTSPkurir, cntAllNode, cityOption):\n coorNodes = getCoorNodesFromFile(cityOption)\n\n if (cityOption==\"Oldenburg\"):\n #print all map\n for i in tqdm(range(cntAllNode)):\n if (len(adjListAll[i])!=0):\n for v in adjListAll[i]:\n x1 = coorNodes[i][0]\n y1 = coorNodes[i][1]\n x2 = coorNodes[v][0]\n y2 = coorNodes[v][1]\n plt.plot([x1,x2],[y1,y2],color=\"k\")\n\n listColor=['c','r','y','m','g','b']\n\n for i in tqdm(range(jumlahKurir)):\n for pairNode in resTSPkurir[i]:\n path = listPath[mapNodeToIdx[pairNode[0]]][mapNodeToIdx[pairNode[1]]]\n predNode = path[0]\n for nodes in path:\n x1 = coorNodes[predNode][0]\n y1 = coorNodes[predNode][1]\n x2 = coorNodes[nodes][0]\n y2 = coorNodes[nodes][1]\n plt.plot([x1,x2],[y1,y2],color=listColor[i%6])\n\n predNode = nodes\n \n \n plt.show()", "sub_path": "src/mapDrawer.py", "file_name": "mapDrawer.py", "file_ext": "py", "file_size_in_byte": 1567, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "tqdm.tqdm", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 28, "usage_type": "name"}, {"api_name": "tqdm.tqdm", "line_number": 32, "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.pyplot.show", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 46, "usage_type": "name"}]}
+{"seq_id": "477688167", "text": "from typing import Dict\n\nfrom bobocep.rules.events.bobo_event import BoboEvent\n\n\nclass PrimitiveEvent(BoboEvent):\n \"\"\"A primitive event.\n\n :param timestamp: The event timestamp indicating when it was first\n generated.\n :type timestamp: int\n\n :param data: The event data, defaults to an empty dict.\n :type data: Dict[str, str], optional\n\n :param event_id: The event ID, defaults to a randomly generated ID.\n :type event_id: str, optional\n \"\"\"\n\n def __init__(self,\n timestamp: int,\n data: Dict[str, str] = None,\n event_id: str = None) -> None:\n super().__init__(timestamp=timestamp,\n data=data,\n event_id=event_id)\n\n def to_dict(self) -> dict:\n \"\"\"\n :return: A dict representation of the object.\n \"\"\"\n\n return {\n self.TIMESTAMP: self.timestamp,\n self.DATA: self.data,\n self.EVENT_ID: self.event_id\n }\n", "sub_path": "bobocep/rules/events/primitive_event.py", "file_name": "primitive_event.py", "file_ext": "py", "file_size_in_byte": 1021, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "bobocep.rules.events.bobo_event.BoboEvent", "line_number": 6, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 22, "usage_type": "name"}]}
+{"seq_id": "489698056", "text": "import os\nimport sys\nimport json\nfrom datetime import date\nimport pandas as pd\nimport streamlit as st\n\n\nfrom litmscript.litmanalysis.remittance_downloader import download_cheque_files as download_cheque_files\nfrom litmscript.litmanalysis.generate_row_level_data_from_json_updated_labelling import generate_row_level_data_util\nfrom litmscript.litmanalysis.heading_model import predict_on_test_data as header_prediction\nfrom litmscript.litmanalysis.total_model import predict_on_test_data as total_prediction\nfrom litmscript.litmanalysis.is_remittance import predict_on_test_data as remittance_prediction\nfrom litmscript.litmanalysis.amount_and_reference_no_capture import monitoring_litm_data\n\n\n\ndef flow_code(root_dir,s3_path,account_no):\n \n \n super_directory = root_dir\n model_dir = \"/root/caascript/litmscript/litmanalysis\"\n header_pkl_path = os.path.join(model_dir,\"LITM_heading.pickle\")\n total_pkl_path = os.path.join(model_dir,\"LITM_total.pickle\")\n remittance_pkl_path = os.path.join(model_dir,\"LITM_remittance.pickle\")\n\n\n account_id=str(account_no)\n directory = os.path.join(super_directory,str(account_id))\n\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n \n data = pd.read_csv(s3_path)\n \n with st.spinner(\"Downloading Image files\"):\n download_cheque_files(data, directory)\n print(\"directory path\"+directory)\n \n with st.spinner(\"Generating Prediction files: \"):\n json_csv_write_path = os.path.join(directory,'row_level_data.csv')\n print(\"json path:\"+json_csv_write_path)\n generate_row_level_data_util(directory,json_csv_write_path)\n header_prediction(header_pkl_path,json_csv_write_path,directory)\n print(\"header prediction\")\n header_prediction_path = os.path.join(directory,'is_heading_prediction.csv')\n print(\"header prediction path\")\n total_prediction(total_pkl_path,header_prediction_path,directory)\n print(\"total prediction\")\n total_prediction_path = os.path.join(directory,'is_total_pred.csv')\n print(\"total prediction path\")\n remittance_prediction(remittance_pkl_path,total_prediction_path,directory)\n print(\"remittance prediciton\")\n remittace_prediction_path = os.path.join(directory,'is_remittance_pred.csv')\n print(\"remittance prediction path\")\n monitoring_litm_data(remittace_prediction_path,directory)\n print(\"monitoring Prediction path\")\n\n correctly_closed_path = os.path.join(directory, 'correctly_closed_checks.csv')\n os.chdir(root_dir)\n return correctly_closed_path", "sub_path": "flow_new.py", "file_name": "flow_new.py", "file_ext": "py", "file_size_in_byte": 2591, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "os.path.join", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path", "line_number": 23, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 24, "usage_type": "call"}, {"api_name": "os.path", "line_number": 24, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path", "line_number": 29, "usage_type": "attribute"}, {"api_name": "os.path.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": "pandas.read_csv", "line_number": 35, "usage_type": "call"}, {"api_name": "streamlit.spinner", "line_number": 37, "usage_type": "call"}, {"api_name": "litmscript.litmanalysis.remittance_downloader.download_cheque_files", "line_number": 38, "usage_type": "call"}, {"api_name": "streamlit.spinner", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path", "line_number": 42, "usage_type": "attribute"}, {"api_name": "litmscript.litmanalysis.generate_row_level_data_from_json_updated_labelling.generate_row_level_data_util", "line_number": 44, "usage_type": "call"}, {"api_name": "litmscript.litmanalysis.heading_model.predict_on_test_data", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 47, "usage_type": "call"}, {"api_name": "os.path", "line_number": 47, "usage_type": "attribute"}, {"api_name": "litmscript.litmanalysis.total_model.predict_on_test_data", "line_number": 49, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 51, "usage_type": "call"}, {"api_name": "os.path", "line_number": 51, "usage_type": "attribute"}, {"api_name": "litmscript.litmanalysis.is_remittance.predict_on_test_data", "line_number": 53, "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": "litmscript.litmanalysis.amount_and_reference_no_capture.monitoring_litm_data", "line_number": 57, "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": "os.chdir", "line_number": 61, "usage_type": "call"}]}
+{"seq_id": "597830333", "text": "\nfrom django.db import models\n\n\nclass TimeStamp(models.Model):\n created_at = models.DateTimeField(auto_now_add=True)\n\n class Meta:\n abstract = True\n\n def age(self):\n import datetime\n from django.utils.timezone import utc\n now = datetime.datetime.utcnow().replace(tzinfo=utc)\n age_in_minutes = int((now - self.created_at).total_seconds()) / 60\n\n if age_in_minutes < 60:\n value = age_in_minutes\n precision = 'minute'\n elif age_in_minutes < 60 * 24:\n value = age_in_minutes // 60\n precision = 'hour'\n else:\n value = age_in_minutes // (60*24)\n precision = 'day'\n\n age_string ='%d %s%s ago' % (value, precision,\n ('s' if value > 1 else ''))\n return age_string\n", "sub_path": "posts/behaviours.py", "file_name": "behaviours.py", "file_ext": "py", "file_size_in_byte": 836, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "django.db.models.Model", "line_number": 5, "usage_type": "attribute"}, {"api_name": "django.db.models", "line_number": 5, "usage_type": "name"}, {"api_name": "django.db.models.DateTimeField", "line_number": 6, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 6, "usage_type": "name"}, {"api_name": "datetime.datetime.utcnow", "line_number": 14, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 14, "usage_type": "attribute"}, {"api_name": "django.utils.timezone.utc", "line_number": 14, "usage_type": "name"}]}
+{"seq_id": "375281849", "text": "import numpy as np\nimport keras\nimport cv2\nimport os\n# from vidaug import augmentors as va\nfrom matplotlib.pyplot import imread, imshow, show\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom data_helper import calculateRGBdiff\n# from imageai.Detection import ObjectDetection\n\nclass DataGeneratorBKB(keras.utils.Sequence):\n 'Generates data for Keras'\n def __init__(self, list_IDs, labels, batch_size=32, dim=(32,32), n_channels=1,\n n_sequence=4, shuffle=True, path_dataset=None,\n select_joint=[], type_gen='train', type_model='rgb', option=None):\n 'Initialization'\n self.dim = dim\n self.batch_size = batch_size\n self.labels = labels\n self.list_IDs = list_IDs\n self.n_channels = n_channels\n self.n_sequence = n_sequence\n self.shuffle = shuffle\n self.path_dataset = path_dataset\n self.select_joint = select_joint\n self.n_joint = len(select_joint)\n self.option = option\n self.type_gen = type_gen\n self.type_model = type_model\n print(\"all:\", len(self.list_IDs), \" batch per epoch\", int(np.floor(len(self.list_IDs) / self.batch_size)) )\n \n # execution_path = os.getcwd()\n # self.detector = ObjectDetection()\n # self.detector.setModelTypeAsYOLOv3()\n # self.detector.setModelPath( os.path.join(execution_path , \"pretrain/yolo.h5\"))\n # self.detector.loadModel(detection_speed=\"fast\")#detection_speed=\"fast\"\n # self.execution_path = execution_path\n # self.detector = detector\n\n # sometimes = lambda aug: va.Sometimes(0.5, aug) # Used to apply augmentor with 50% probability\n # self.seq = va.SomeOf([ #va.Sequential([\n # # va.RandomCrop(size=(300, 300)), # randomly crop video with a size of (240 x 180)\n # va.RandomRotate(degrees=10), # randomly rotates the video with a degree randomly choosen from [-10, 10] \n # va.RandomTranslate(x=60,y=30), \n # # sometimes(va.Add(value=-100)),\n # # sometimes(va.Pepper(ratio=40)),\n # sometimes(va.Add(value=-60)),\n # sometimes(va.HorizontalFlip()) # horizontally flip the video with 50% probability\n # ], 2)\n\n self.aug_gen = ImageDataGenerator() \n \n self.on_epoch_end()\n\n def __len__(self):\n 'Denotes the number of batches per epoch'\n return int(np.floor(len(self.list_IDs) / self.batch_size))\n\n def on_epoch_end(self):\n 'Updates indexes after each epoch' \n self.indexes = np.arange(len(self.list_IDs))\n if self.shuffle == True:\n np.random.shuffle(self.indexes)\n\n def __getitem__(self, index):\n 'Generate one batch of data'\n # Generate indexes of the batch\n indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]\n # Find list of IDs\n list_IDs_temp = [self.list_IDs[k] for k in indexes]\n # Generate data\n X, y = self.__data_generation(list_IDs_temp)\n if self.type_gen == 'predict':\n return X\n else:\n return X, y\n\n def get_sampling_frame(self, len_frames, path_video): \n '''\n Sampling n_sequence frame from video file\n Input: \n len_frames -- number of frames that this video have\n Output: \n index_sampling -- n_sequence frame indexs from sampling algorithm \n '''\n\n # Define maximum sampling rate\n # sample_interval = len_frames//self.n_sequence\n # start_i = 0 #np.random.randint(0, len_frames - sample_interval * self.n_sequence + 1)\n\n if True:#self.type_gen =='train':\n random_sample_range = 10\n if random_sample_range*self.n_sequence > len_frames:\n random_sample_range = len_frames//self.n_sequence\n\n if random_sample_range <= 0:\n print('test:',random_sample_range, len_frames, path_video)\n # Randomly choose sample interval and start frame\n if random_sample_range < 3:\n sample_interval = np.random.randint(1, random_sample_range + 1)\n else:\n sample_interval = np.random.randint(3, random_sample_range + 1)\n\n # sample_interval = np.random.randint(1, random_sample_range + 1)\n\n # temp = len_frames - sample_interval * self.n_sequence + 1\n # if temp <= 0:\n # print(temp, len_frames)\n start_i = np.random.randint(0, len_frames - sample_interval * self.n_sequence + 1)\n \n # Get n_sequence index of frames\n index_sampling = []\n end_i = sample_interval * self.n_sequence + start_i\n for i in range(start_i, end_i, sample_interval):\n if len(index_sampling) < self.n_sequence:\n index_sampling.append(i)\n \n return index_sampling\n\n def get_crop_img(self, frame):\n # detect_image, detections, extract_picture = self.detector.detectObjectsFromImage(input_type=\"array\", input_image=frame, output_type='array', \n # minimum_percentage_probability=10, extract_detected_objects=True )\n print('#################',self.execution_path)\n detections = self.detector.detectObjectsFromImage(input_image=os.path.join(self.execution_path , \"room.jpg\"),\n output_image_path=os.path.join(self.execution_path , \"image2new.jpg\"), minimum_percentage_probability=30)\n max_prob = 0\n max_idx = 0\n for i,eachObject in enumerate(detections):\n if eachObject[\"name\"] == 'person' and eachObject[\"percentage_probability\"] > max_prob:\n max_prob = eachObject[\"percentage_probability\"]\n max_idx = i\n if max_idx > len(detections):\n # if no detection, use black array\n crop_img = np.zeros((*self.dim, self.n_channels))\n else:\n crop_img = extract_picture[max_idx]\n return crop_img\n\n # def calculateRGBdiff(self, sequence_img):\n # 'keep first frame as rgb data, other is use RGBdiff for temporal data'\n # length = len(sequence_img)\n # new_sequence = np.zeros((length,self.dim[0],self.dim[1],self.n_channels))\n\n # # find RGBdiff frame 1 to last frame\n # for i in range(length-1,3,-1): # count down\n # new_sequence[i] = cv2.subtract(sequence_img[i],sequence_img[i-1])\n \n # new_sequence[:4] = sequence_img[:4] # first frame as rgb data\n\n # return new_sequence\n\n def sequence_augment(self, sequence):\n name_list = ['rotate','width_shift','height_shift',\n 'brightness','flip_horizontal','width_zoom',\n 'height_zoom']\n dictkey_list = ['theta','ty','tx',\n 'brightness','flip_horizontal','zy',\n 'zx']\n # dictkey_list = ['ty','tx','zy','zx']\n random_aug = np.random.randint(2, 5) # random 0-4 augmentation method\n pick_idx = np.random.choice(len(dictkey_list), random_aug, replace=False) #\n\n dict_input = {}\n for i in pick_idx:\n if dictkey_list[i] == 'theta':\n # dict_input['theta'] = np.random.randint(-10, 10)\n dict_input['theta'] = np.random.randint(-5,5)\n\n elif dictkey_list[i] == 'ty': # width_shift\n # dict_input['ty'] = np.random.randint(-60, 60)\n dict_input['ty'] = np.random.randint(-20,20)\n\n elif dictkey_list[i] == 'tx': # height_shift\n # dict_input['tx'] = np.random.randint(-30, 30)\n dict_input['tx'] = np.random.randint(-10,10)\n\n elif dictkey_list[i] == 'brightness': \n dict_input['brightness'] = np.random.uniform(0.15,1)\n\n elif dictkey_list[i] == 'flip_horizontal': \n dict_input['flip_horizontal'] = True\n\n elif dictkey_list[i] == 'zy': # width_zoom\n # dict_input['zy'] = np.random.uniform(0.5,1.5)\n dict_input['zy'] = np.random.uniform(0.9,1.3) \n\n elif dictkey_list[i] == 'zx': # height_zoom\n # dict_input['zx'] = np.random.uniform(0.5,1.5)\n dict_input['zx'] = np.random.uniform(0.9,1.3) \n \n sh = sequence.shape\n new_sequence = np.zeros((sh[0],sh[1],sh[2],sh[3]))\n for i in range(sh[0]):\n new_sequence[i] = self.aug_gen.apply_transform(sequence[i],dict_input)\n \n return new_sequence\n \n\n def __data_generation(self, list_IDs_temp):\n 'Generates data containing batch_size samples'\n # Initialization\n X1 = np.empty((self.batch_size, self.n_sequence, *self.dim, self.n_channels)) # X : (n_samples, timestep, *dim, n_channels)\n X2 = np.empty((self.batch_size, self.n_sequence, self.n_joint*3))\n Y = np.empty((self.batch_size), dtype=int)\n\n for i, ID in enumerate(list_IDs_temp): # ID is name of file (2 batch)\n path_video = self.path_dataset + ID + '.mp4'\n # print(path_video)\n path_skeleton = self.path_dataset + ID + '.npy'\n \n # print(path_video)\n \n if self.type_model == '2stream' or self.type_model == 'rgb':\n cap = cv2.VideoCapture(path_video) \n length_file = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) # get how many frames this video have ,-1 because some bug \n \n if self.type_model == '2stream' or self.type_model == 'skeleton':\n skeleton_data = np.load(path_skeleton)\n length_file = skeleton_data.shape[0]\n\n index_sampling = self.get_sampling_frame(length_file, path_video) # get sampling index \n # print(index_sampling)\n if self.type_model == '2stream' or self.type_model == 'rgb': \n # Get RGB sequence\n for j, n_pic in enumerate(index_sampling):\n cap.set(cv2.CAP_PROP_POS_FRAMES, n_pic) # jump to that index\n ret, frame = cap.read()\n # frame = self.get_crop_img(frame)\n new_image = cv2.resize(frame, self.dim)\n # new_image = frame\n # new_image = new_image/255.0 \n X1[i,j,:,:,:] = new_image\n \n\n if self.type_gen =='train':\n X1[i,] = self.sequence_augment(X1[i,])/255.0*2-1\n else:\n X1[i,] = X1[i,]/255.0*2-1\n\n # cv2.imshow('imgae',X1[i,0])\n # cv2.waitKey(2000)\n\n\n if self.option == 'RGBdiff':\n # print(\"dddddddddddd\")\n X1[i,] = calculateRGBdiff(X1[i,], 0)\n \n\n if self.type_model == '2stream' or self.type_model == 'skeleton':\n # Get skeleton sequence \n skeleton_data = skeleton_data[index_sampling]\n skeleton_data = skeleton_data[:,:,self.select_joint]\n skeleton_data = skeleton_data.reshape(self.n_sequence,self.n_joint*3)\n X2[i] = skeleton_data\n\n # Get label\n Y[i] = self.labels[ID]\n if self.type_model == '2stream' or self.type_model == 'rgb':\n cap.release() \n\n # for i_frame in range(self.n_sequence):\n # cv2.imshow('Frame', X1[i,i_frame])\n # cv2.waitKey(1000)\n\n if self.type_model == 'rgb':\n X = X1\n elif self.type_model == 'skeleton':\n X = X2\n elif self.type_model == '2stream':\n X = [X1, X2]\n\n return X,Y\n\n\n# class DataGenerator2Stream(DataGeneratorBKB):\n# def __init__(self, list_IDs, labels, batch_size=32, dim=(32,32),\n# n_channels=1, n_sequence=4, shuffle=True, path_dataset=None, \n# select_joint=[], type_gen='train'):\n\n# super().__init__(list_IDs, labels, batch_size, dim, n_channels,\n# n_sequence, shuffle, path_dataset, type_gen)\n# self.select_joint = select_joint\n", "sub_path": "data_gen_bkb.py", "file_name": "data_gen_bkb.py", "file_ext": "py", "file_size_in_byte": 12219, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "keras.utils", "line_number": 11, "usage_type": "attribute"}, {"api_name": "numpy.floor", "line_number": 30, "usage_type": "call"}, {"api_name": "tensorflow.keras.preprocessing.image.ImageDataGenerator", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.floor", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 61, "usage_type": "call"}, {"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.randint", "line_number": 100, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 100, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 102, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 102, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 109, "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": "numpy.zeros", "line_number": 134, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 160, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 160, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 161, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 161, "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": "numpy.random.randint", "line_number": 171, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 171, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 175, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 175, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 178, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 178, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 185, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 185, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 189, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 189, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 192, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 202, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 203, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 204, "usage_type": "call"}, {"api_name": "cv2.VideoCapture", "line_number": 214, "usage_type": "call"}, {"api_name": "cv2.CAP_PROP_FRAME_COUNT", "line_number": 215, "usage_type": "attribute"}, {"api_name": "numpy.load", "line_number": 218, "usage_type": "call"}, {"api_name": "cv2.CAP_PROP_POS_FRAMES", "line_number": 226, "usage_type": "attribute"}, {"api_name": "cv2.resize", "line_number": 229, "usage_type": "call"}, {"api_name": "data_helper.calculateRGBdiff", "line_number": 246, "usage_type": "call"}]}
+{"seq_id": "199248646", "text": "# Copyright 2021 MosaicML. All Rights Reserved.\n\nfrom copy import deepcopy\n\nimport pytest\nimport torch\n\nfrom composer.algorithms import LayerFreezing, LayerFreezingHparams\nfrom composer.core.state import State\nfrom composer.core.types import Event, Model, Precision\nfrom composer.loggers import Logger\nfrom composer.trainer.trainer_hparams import TrainerHparams\nfrom composer.utils import ensure_tuple\nfrom tests.utils.trainer_fit import train_model\n\n\ndef _generate_state(epoch: int, max_epochs: int, model: Model):\n state = State(\n epoch=epoch,\n step=epoch,\n train_batch_size=64,\n eval_batch_size=64,\n grad_accum=1,\n max_epochs=max_epochs,\n model=model,\n optimizers=(torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.99),),\n precision=Precision.FP32,\n )\n return state\n\n\ndef _check_param_groups(expected_groups, actual_groups):\n assert len(expected_groups) == len(actual_groups), 'Incorrect number of param groups'\n\n for i, expected_group in enumerate(expected_groups):\n assert len(expected_group) == len(actual_groups[i]), \\\n f'Group {i} has the wrong number of parameters'\n\n for j, expected_params in enumerate(expected_group['params']):\n torch.testing.assert_equal(actual_groups[i]['params'][j], expected_params)\n\n\ndef test_freeze_layers_no_freeze(simple_conv_model: Model, noop_dummy_logger: Logger):\n state = _generate_state(epoch=10, max_epochs=100, model=simple_conv_model)\n\n first_optimizer = ensure_tuple(state.optimizers)[0]\n assert first_optimizer is not None\n\n expected_param_groups = deepcopy(first_optimizer.param_groups)\n freezing = LayerFreezing(freeze_start=0.5, freeze_level=1.0)\n freezing.apply(event=Event.EPOCH_END, state=state, logger=noop_dummy_logger)\n updated_param_groups = first_optimizer.param_groups\n\n _check_param_groups(expected_param_groups, updated_param_groups)\n\n\ndef test_freeze_layers_with_freeze(simple_conv_model: Model, noop_dummy_logger: Logger):\n state = _generate_state(epoch=80, max_epochs=100, model=simple_conv_model)\n\n first_optimizer = ensure_tuple(state.optimizers)[0]\n assert first_optimizer is not None\n\n expected_param_groups = deepcopy(first_optimizer.param_groups)\n # The first group should be removed due to freezing\n expected_param_groups[0]['params'] = expected_param_groups[0]['params'][1:]\n freezing = LayerFreezing(freeze_start=0.05, freeze_level=1.0)\n freezing.apply(event=Event.EPOCH_END, state=state, logger=noop_dummy_logger)\n updated_param_groups = first_optimizer.param_groups\n\n _check_param_groups(expected_param_groups, updated_param_groups)\n\n\n@pytest.mark.run_long\n@pytest.mark.timeout(90)\ndef test_layer_freezing_trains(mosaic_trainer_hparams: TrainerHparams):\n mosaic_trainer_hparams.algorithms = [LayerFreezingHparams(freeze_start=.25, freeze_level=1)]\n train_model(mosaic_trainer_hparams, max_epochs=4)\n", "sub_path": "tests/algorithms/test_layer_freezing.py", "file_name": "test_layer_freezing.py", "file_ext": "py", "file_size_in_byte": 2955, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "composer.core.types.Model", "line_number": 17, "usage_type": "name"}, {"api_name": "composer.core.state.State", "line_number": 18, "usage_type": "call"}, {"api_name": "torch.optim.SGD", "line_number": 26, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 26, "usage_type": "attribute"}, {"api_name": "composer.core.types.Precision.FP32", "line_number": 27, "usage_type": "attribute"}, {"api_name": "composer.core.types.Precision", "line_number": 27, "usage_type": "name"}, {"api_name": "torch.testing.assert_equal", "line_number": 40, "usage_type": "call"}, {"api_name": "torch.testing", "line_number": 40, "usage_type": "attribute"}, {"api_name": "composer.core.types.Model", "line_number": 43, "usage_type": "name"}, {"api_name": "composer.loggers.Logger", "line_number": 43, "usage_type": "name"}, {"api_name": "composer.utils.ensure_tuple", "line_number": 46, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 49, "usage_type": "call"}, {"api_name": "composer.algorithms.LayerFreezing", "line_number": 50, "usage_type": "call"}, {"api_name": "composer.core.types.Event.EPOCH_END", "line_number": 51, "usage_type": "attribute"}, {"api_name": "composer.core.types.Event", "line_number": 51, "usage_type": "name"}, {"api_name": "composer.core.types.Model", "line_number": 57, "usage_type": "name"}, {"api_name": "composer.loggers.Logger", "line_number": 57, "usage_type": "name"}, {"api_name": "composer.utils.ensure_tuple", "line_number": 60, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 63, "usage_type": "call"}, {"api_name": "composer.algorithms.LayerFreezing", "line_number": 66, "usage_type": "call"}, {"api_name": "composer.core.types.Event.EPOCH_END", "line_number": 67, "usage_type": "attribute"}, {"api_name": "composer.core.types.Event", "line_number": 67, "usage_type": "name"}, {"api_name": "composer.trainer.trainer_hparams.TrainerHparams", "line_number": 75, "usage_type": "name"}, {"api_name": "composer.algorithms.LayerFreezingHparams", "line_number": 76, "usage_type": "call"}, {"api_name": "tests.utils.trainer_fit.train_model", "line_number": 77, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 73, "usage_type": "attribute"}, {"api_name": "pytest.mark.timeout", "line_number": 74, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 74, "usage_type": "attribute"}]}
+{"seq_id": "616909160", "text": "#\n# @lc app=leetcode id=1557 lang=python3\n#\n# [1557] Minimum Number of Vertices to Reach All Nodes\n#\n\n# @lc code=start\nimport collections\nclass Solution:\n def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]:\n indgree = collections.Counter()\n for edge in edges:\n indgree[edge[1]]+=1\n result = []\n for i in range(n):\n if indgree[i] == 0:\n result.append(i)\n return result\n \n \n\n \n# @lc code=end\n\n", "sub_path": "py-src/1557.minimum-number-of-vertices-to-reach-all-nodes.py", "file_name": "1557.minimum-number-of-vertices-to-reach-all-nodes.py", "file_ext": "py", "file_size_in_byte": 525, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "collections.Counter", "line_number": 11, "usage_type": "call"}]}
+{"seq_id": "414266124", "text": "from flask import Flask\nfrom flask_jwt_extended import JWTManager\nfrom flask_cors import CORS\n\nfrom api_v1.api_user import main as user_api_routes\nfrom api_v1.api_auth import main as auth_api_routes\nfrom api_v1.api_topic import main as topic_api_routes\nfrom api_v1.api_board import main as board_api_routes\nfrom api_v1.api_reply import main as reply_api_routes\nfrom api_v1.api_mail import main as mail_api_routes\nfrom config import secret_key\n\n\ndef configured_app():\n app = Flask(__name__)\n # 设置 secret_key 来使用 flask 自带的 session\n # 这个字符串只要hard to guess就可以了\n app.secret_key = secret_key\n\n # app.register_blueprint(index_routes)\n # app.register_blueprint(topic_routes, url_prefix='/topic')\n # app.register_blueprint(reply_routes, url_prefix='/reply')\n # app.register_blueprint(board_routes, url_prefix='/board')\n # app.register_blueprint(mail_routes, url_prefix='/mail')\n app.register_blueprint(auth_api_routes, url_prefix='/api/v1')\n app.register_blueprint(user_api_routes, url_prefix='/api/v1')\n app.register_blueprint(topic_api_routes, url_prefix='/api/v1')\n app.register_blueprint(board_api_routes, url_prefix='/api/v1')\n app.register_blueprint(reply_api_routes, url_prefix='/api/v1')\n app.register_blueprint(mail_api_routes, url_prefix='/api/v1')\n # Setup the Flask-JWT-Extended extension\n app.config['JWT_SECRET_KEY'] = 'super-secret' # Change this!\n jwt = JWTManager(app)\n CORS(app)\n return app\n\n\nif __name__ == '__main__':\n app = configured_app()\n # 自动 reload jinja\n app.config['TEMPLATES_AUTO_RELOAD'] = True\n app.jinja_env.auto_reload = True\n app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0\n # debug 模式可以自动加载对代码的变动, 所以不用重启程序\n # host 参数指定为 '0.0.0.0' 可以让别的机器访问代码\n config = dict(\n debug=True,\n host='0.0.0.0',\n port=8000,\n threaded=True,\n )\n app.run(**config)\n", "sub_path": "bbsapi/app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 1999, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "flask.Flask", "line_number": 15, "usage_type": "call"}, {"api_name": "config.secret_key", "line_number": 18, "usage_type": "name"}, {"api_name": "api_v1.api_auth.main", "line_number": 25, "usage_type": "argument"}, {"api_name": "api_v1.api_user.main", "line_number": 26, "usage_type": "argument"}, {"api_name": "api_v1.api_topic.main", "line_number": 27, "usage_type": "argument"}, {"api_name": "api_v1.api_board.main", "line_number": 28, "usage_type": "argument"}, {"api_name": "api_v1.api_reply.main", "line_number": 29, "usage_type": "argument"}, {"api_name": "api_v1.api_mail.main", "line_number": 30, "usage_type": "argument"}, {"api_name": "flask_jwt_extended.JWTManager", "line_number": 33, "usage_type": "call"}, {"api_name": "flask_cors.CORS", "line_number": 34, "usage_type": "call"}]}
+{"seq_id": "162080484", "text": "from django.shortcuts import render\nfrom django.http import JsonResponse\nfrom default.models import Todolist\n\n# Create your views here.\n\ndef index(request):\n return render(request,\"index.html\")\n\n\ndef todogetlist(request):\n dataset = Todolist.objects.all()\n todolist = []\n for item in dataset:\n temp ={\"id\":item.id,\"content\":item.content}\n todolist.append(temp)\n res ={\"todolist\":todolist}\n return JsonResponse(res)\n\n\ndef todoadd(request):\n todo = request.POST['todo']\n Todolist.objects.create(content=todo)\n res ={\"success\":\"true\"}\n return JsonResponse(res)\n\n\ndef todoedit(request):\n id = request.POST['id']\n content = request.POST['todo']\n todo = Todolist.objects.get(id=id)\n todo.content =content\n todo.save()\n res ={\"success\":\"true\"}\n return JsonResponse(res)\n\ndef tododel(request):\n id = request.GET['id']\n Todolist.objects.get(id=id).delete()\n res ={\"success\":\"true\"}\n return JsonResponse(res)", "sub_path": "django框架练习/todolist3/default/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 975, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "django.shortcuts.render", "line_number": 8, "usage_type": "call"}, {"api_name": "default.models.Todolist.objects.all", "line_number": 12, "usage_type": "call"}, {"api_name": "default.models.Todolist.objects", "line_number": 12, "usage_type": "attribute"}, {"api_name": "default.models.Todolist", "line_number": 12, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 18, "usage_type": "call"}, {"api_name": "default.models.Todolist.objects.create", "line_number": 23, "usage_type": "call"}, {"api_name": "default.models.Todolist.objects", "line_number": 23, "usage_type": "attribute"}, {"api_name": "default.models.Todolist", "line_number": 23, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 25, "usage_type": "call"}, {"api_name": "default.models.Todolist.objects.get", "line_number": 31, "usage_type": "call"}, {"api_name": "default.models.Todolist.objects", "line_number": 31, "usage_type": "attribute"}, {"api_name": "default.models.Todolist", "line_number": 31, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 35, "usage_type": "call"}, {"api_name": "default.models.Todolist.objects.get", "line_number": 39, "usage_type": "call"}, {"api_name": "default.models.Todolist.objects", "line_number": 39, "usage_type": "attribute"}, {"api_name": "default.models.Todolist", "line_number": 39, "usage_type": "name"}, {"api_name": "django.http.JsonResponse", "line_number": 41, "usage_type": "call"}]}
+{"seq_id": "3811282", "text": "import requests,time\nfrom lxml import etree\n\n# url = \"https://weixin.sogou.com/weixin?query=%E5%BE%AE%E7%A4%BE%E5%8C%BAe%E5%AE%B6%E9%80%9A%E9%87%91%E8%8A%B1\"\nagent = 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Mobile Safari/537.36'\nagent1 = \"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Mobile Safari/537.36\"\nheaders = {\n'Host': \"weixin.sogou.com\",\n'Accept': \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n'Accept-Encoding': \"gzip, deflate, br\",\n'Accept-Language': \"zh-CN,zh;q=0.9,en;q=0.8\",\n'User-Agent': agent,\n'Connection': \"keep-alive\",\n}\n#读取本地ip.txt中的IP代理\ndef ip_proxy():#\n # encoding=utf-8\n # 随机数,随机读取每一行的数据\n import linecache\n import random\n\n for i in range(1, 2): # for循环几次3\n a = random.randrange(1, 27) # 1-9中生成随机数\n print(a)\n # 从文件poem.txt中对读取第a行的数据\n theline = linecache.getline(r'ip.txt', a)\n theline = theline.strip('\\n')\n print(\"the a row data is:\",theline)\n return theline\n\n# proxy = ip_proxy()\nproxy = '12.191.182.53:9999'\nurl = 'http://www.baidu.com' # 验证ip有效性的指定url\n# url = \"https://weixin.sogou.com/weixin?query=\"+'公众号'\nproxies = {\n 'http': 'http://' + proxy\n}\nprint(proxy)\nresponse = requests.get(url, allow_redirects=False, headers=headers, proxies=proxies)\nprint(response.status_code)\n\n# time.sleep(3)\nif response.status_code == 200:\n with open('test.html', 'w', encoding='utf-8') as f:\n f.write(response.text)\n session = requests.Session()\n print(session)\n seletor = etree.HTML(response.text)\n print(\"current page:\", response.url)\nelse:\n print(\"网页出错了\",response.status_code)\n", "sub_path": "WeChat/Ejiatong/proxyTest.py", "file_name": "proxyTest.py", "file_ext": "py", "file_size_in_byte": 1890, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "random.randrange", "line_number": 23, "usage_type": "call"}, {"api_name": "linecache.getline", "line_number": 26, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 39, "usage_type": "call"}, {"api_name": "requests.Session", "line_number": 46, "usage_type": "call"}, {"api_name": "lxml.etree.HTML", "line_number": 48, "usage_type": "call"}, {"api_name": "lxml.etree", "line_number": 48, "usage_type": "name"}]}
+{"seq_id": "135227536", "text": "from django.shortcuts import render, redirect\r\nfrom User.models import Branch, User\r\n\r\ndef home(request):\r\n return render(request, 'index.html')\r\n\r\ndef register(request):\r\n branches = Branch.objects.all()\r\n print(branches)\r\n return render(request, 'register.html',{\r\n 'branches':branches\r\n })\r\n\r\ndef saveuser(request):\r\n ob= User()\r\n ob.user_name = request.POST.get('uname')\r\n ob.user_email = request.POST.get('email')\r\n ob.user_password = request.POST.get('pwd')\r\n ob.user_type = request.POST.get('type')\r\n branch_slug = request.POST.get('branch')\r\n branch = Branch.objects.filter(branch_slug=branch_slug)\r\n ob.user_branch = branch[0]\r\n ob.save()\r\n return redirect(\"/register\")\r\n \r\n\r\ndef login(request):\r\n if request.method == \"GET\":\r\n return render(request, 'login.html') \r\n else:\r\n email = request.POST.get(\"email\")\r\n pwd = request.POST.get(\"pwd\")\r\n\r\n records = User.objects.filter(user_email=email,user_password=pwd)\r\n count = len(records)\r\n if count == 0:\r\n return redirect(\"/login\") \r\n else:\r\n userob = records[0]\r\n request.session['user'] = {\r\n 'userid': userob.id,\r\n 'name' : userob.user_name,\r\n 'email' : userob.user_email,\r\n 'type' : userob.user_type,\r\n 'branch' : userob.user_branch.branch_slug\r\n }\r\n return redirect(\"/user/home\") ", "sub_path": "CollegeQuera/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1499, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "django.shortcuts.render", "line_number": 5, "usage_type": "call"}, {"api_name": "User.models.Branch.objects.all", "line_number": 8, "usage_type": "call"}, {"api_name": "User.models.Branch.objects", "line_number": 8, "usage_type": "attribute"}, {"api_name": "User.models.Branch", "line_number": 8, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 10, "usage_type": "call"}, {"api_name": "User.models.User", "line_number": 15, "usage_type": "call"}, {"api_name": "User.models.Branch.objects.filter", "line_number": 21, "usage_type": "call"}, {"api_name": "User.models.Branch.objects", "line_number": 21, "usage_type": "attribute"}, {"api_name": "User.models.Branch", "line_number": 21, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 24, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 29, "usage_type": "call"}, {"api_name": "User.models.User.objects.filter", "line_number": 34, "usage_type": "call"}, {"api_name": "User.models.User.objects", "line_number": 34, "usage_type": "attribute"}, {"api_name": "User.models.User", "line_number": 34, "usage_type": "name"}, {"api_name": "django.shortcuts.redirect", "line_number": 37, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 47, "usage_type": "call"}]}
+{"seq_id": "233719166", "text": "#!/usr/bin/env python\n\n\"\"\"\n########################################################################\n# Author: Carlos A. Ruiz Perez\n# Email: cruizperez3@gatech.edu\n# Intitution: Georgia Institute of Technology\n# Version: 1.0.0\n# Date: Nov 13, 2020\n\n# Description: Parses compressed dat files and extracts protein\ninformation relevant for annotation purposes.\n########################################################################\n\"\"\"\n\n################################################################################\n\"\"\"---0.0 Import Modules---\"\"\"\nimport gzip\nfrom pathlib import Path\n\n################################################################################\n\"\"\"---1.0 Define Functions---\"\"\"\n\ndef parse_uniprot_dat(dat_file, output_file_table):\n output_folder = Path(output_file_table).parent\n uniprot_to_refseq = output_folder / \"03.uniprot_to_refseq.txt\"\n with gzip.open(dat_file, 'rt') as uniprot, open(output_file_table, 'w') as output_file, open(uniprot_to_refseq, 'a') as uni_to_ref:\n gene_id = \"\"\n accession = \"\"\n gene_name = \"\"\n ko_number = \"\"\n organism = \"\"\n taxonomy = \"\"\n function = \"\"\n compartment = \"\"\n process = \"\"\n interpro = \"\"\n pfam = \"\"\n ec_number = \"\"\n refseq_code = \"\"\n for line in uniprot:\n if line.startswith(\"ID\", 0):\n gene_id = line.split()[1]\n elif \"AC \" in line:\n accession = line.split()[1].replace(\";\",\"\")\n elif line.startswith(\"DE\") and \"Full=\" in line:\n gene_name = line.split(\"Full=\")[1]\n gene_name = gene_name.split(\"{\")[0].strip().replace(\";\",\"\")\n gene_name = gene_name.lower()\n elif \"OS \" in line:\n organism = ' '.join([organism, line.split(\"OS\")[1].strip()]).replace(\".\",\"\")\n elif \"OC \" in line:\n taxonomy = ' '.join([taxonomy, line.split(\"OC\")[1].strip()]).replace(\".\",\"\")\n elif \"DR KO;\" in line:\n ko_number = line.split()[2].replace(\";\", \"\")\n elif \"DR GO;\" in line:\n if \"; F:\" in line:\n code = line.strip().split(\";\")[1]\n code = code.strip()\n if function == \"\":\n function = code\n else:\n function = ''.join([function, \" \", code])\n elif \"; C:\" in line:\n code = line.strip().split(\";\")[1]\n code = code.strip()\n if compartment == \"\":\n compartment = code\n else:\n compartment = ''.join([compartment, \" \", code])\n elif \"; P:\" in line:\n code = line.strip().split(\";\")[1]\n code = code.strip()\n if process == \"\":\n process = code\n else:\n process = ''.join([process, \" \", code])\n elif \"DR InterPro\" in line:\n code = line.strip().split()[2]\n code = code.replace(\";\", \"\")\n if interpro == \"\":\n interpro = code\n else:\n interpro = ' '.join([interpro, code])\n elif \"DR Pfam\" in line:\n code = line.strip().split()[2]\n code = code.replace(\";\", \"\")\n if pfam == \"\":\n pfam = code\n else:\n pfam = ' '.join([pfam, code])\n elif line.startswith(\"DE\") and \"EC=\" in line:\n ec_code = line.strip().split()[1]\n ec_code = ec_code.replace(\";\", \"\")\n ec_code = ec_code.replace(\"EC=\", \"\")\n if ec_number == \"\":\n ec_number = ec_code\n else:\n ec_number = ' '.join([ec_number, ec_code])\n elif line.startswith(\"DR\") and \"RefSeq\" in line:\n refseq_code = line.strip().split()[2]\n refseq_code = refseq_code.replace(\";\", \"\")\n uni_to_ref.write(\"{}\\t{}\\n\".format(gene_id, refseq_code))\n elif \"//\\n\" in line:\n if ko_number == \"\":\n ko_number = \"NA\"\n if organism == \"\":\n organism = \"NA\"\n if function == \"\":\n function = \"NA\"\n if compartment == \"\":\n compartment = \"NA\"\n if process == \"\":\n process = \"NA\"\n if interpro == \"\":\n interpro = \"NA\"\n if pfam == \"\":\n pfam = \"NA\"\n if ec_number == \"NA\":\n ec_number = \"NA\"\n output_file.write(\"{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n\".format(gene_id, \n accession, gene_name, ko_number, organism, taxonomy, function, compartment, process, interpro, pfam, ec_number))\n gene_id = \"\"\n accession = \"\"\n gene_name = \"\"\n ko_number = \"\"\n organism = \"\"\n taxonomy = \"\"\n function = \"\"\n compartment = \"\"\n process = \"\"\n interpro = \"\"\n pfam =\"\"\n ec_number = \"\"\n refseq_code = \"\"\n\n\n################################################################################\n\"\"\"---3.0 Main Function---\"\"\"\n\ndef main():\n import argparse, sys\n # Setup parser for arguments.\n parser = argparse.ArgumentParser(description='''This script parses a Uniprot.dat file and output_files a table with\\n'''\n '''the ID, Accession, Gene Name, Organism, Taxonomy, KEGG ID, Function,\\n\n Compartment, Process, InterPro, and Pfam\\n\n For faster usage in alrge files use gnu parallel (read script file to see how)\\n'''\n '''\\nGlobal mandatory parameters: [Input Uniprot.dat File]\\n'''\n '''\\nOptional Database Parameters: See ''' + sys.argv[0] + ' -h')\n parser.add_argument('-i', '--input', dest='input_dat', action='store', required=True, help='Uniprot.dat file to parse')\n parser.add_argument('-o', '--output_file', dest='output_file_table', action='store', required=False, help='output_file table')\n args = parser.parse_args()\n\n input_dat = args.input_dat\n output_file_table = args.output_file_table\n\n parse_uniprot_dat(input_dat, output_file_table)\n\nif __name__ == \"__main__\":\n main()\n", "sub_path": "independent_scripts/uniprot_dat_parser.py", "file_name": "uniprot_dat_parser.py", "file_ext": "py", "file_size_in_byte": 6786, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "pathlib.Path", "line_number": 25, "usage_type": "call"}, {"api_name": "gzip.open", "line_number": 27, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 144, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 149, "usage_type": "attribute"}]}
+{"seq_id": "158367951", "text": "from __future__ import print_function\n\nimport os\nimport sys\nfrom time import sleep\nfrom os import environ\nfrom socket import socket\nfrom traceback import format_tb\nfrom socket import AF_INET, SOCK_STREAM\n\n\nfrom circuits.web.errors import httperror\nfrom circuits.web import Controller, Server\nfrom circuits.web.exceptions import NotFound\nfrom circuits import handler, Event, Component\n\nfrom jinja2 import Environment, FileSystemLoader, TemplateNotFound\n\nfrom redisco import connection_setup, get_client\n\n\nfrom models import TodoItem, TodoList\n\n\nDEFAULTS = {\n \"appname\": \"todoapp\",\n \"version\": \"dev\",\n}\n\n\nclass render(Event):\n \"\"\"render Event\"\"\"\n\n\nclass JinjaTemplate(object):\n\n def __init__(self, _name, **context):\n self._name = _name\n self.context = context\n\n @property\n def name(self):\n return self._name\n\n\nclass JinjaRenderer(Component):\n\n channel = \"web\"\n\n def init(self, path, defaults=None):\n self.path = path\n self.defaults = defaults or {}\n\n self.env = Environment(loader=FileSystemLoader(path))\n\n @handler(\"response\", priority=1.0)\n def serialize_response_body(self, event, response):\n template = response.body\n if not isinstance(template, JinjaTemplate):\n return\n\n try:\n request = response.request\n\n try:\n tmpl = self.env.get_template(\"{0}.html\".format(template.name))\n except TemplateNotFound:\n raise NotFound()\n\n ctx = self.defaults.copy()\n ctx.update({\"request\": request, \"response\": response, \"uri\": request.uri})\n\n ctx.update(template.context)\n\n response.body = tmpl.render(**ctx)\n except:\n event.stop()\n evalue, etype, etraceback = sys.exc_info()\n error = (evalue, etype, format_tb(etraceback))\n self.fire(httperror(request, response, 500, error=error))\n\n\nclass Root(Controller):\n\n def GET(self, *args, **kwargs):\n name = (args and args[0]) or \"TODO\"\n todo = TodoList.objects.get_or_create(name=name)\n entries = [entry for entry in todo.entries if not entry.done]\n return JinjaTemplate(\"views/index\", name=name, entries=entries)\n\n\nclass Add(Controller):\n\n channel = \"/add\"\n\n def GET(self, *args, **kwargs):\n return JinjaTemplate(\"views/add\")\n\n def POST(self, *args, **kwargs):\n name = (args and args[0]) or \"TODO\"\n todo = TodoList.objects.get_or_create(name=name)\n todo.add_entry(kwargs[\"title\"])\n return self.redirect(self.uri(\"/\"))\n\n\nclass Update(Controller):\n\n channel = \"/update\"\n\n def done(self, *args, **kwargs):\n id = int(kwargs[\"id\"])\n item = TodoItem.objects.get_by_id(id)\n item.mark_done()\n return self.redirect(self.uri(\"/\"))\n\n\ndef waitfor(host, port, timeout=10):\n sock = socket(AF_INET, SOCK_STREAM)\n\n while sock.connect_ex((host, port)) != 0 and timeout:\n timeout -= 1\n sleep(1)\n\n if timeout <= 0:\n print(\"Timed out waiting for {0:s}:{1:d}\".format(host, port))\n raise SystemExit(1)\n\n\ndef setup_database():\n dbhost = environ.get(\"REDIS_PORT_6379_TCP_ADDR\", \"localhost\")\n dbport = int(environ.get(\"REDIS_PORT_6379_TCP_PORT\", \"6379\"))\n\n print(\"Waiting for Redis Service on {0:s}:{1:d} ...\".format(dbhost, dbport))\n\n waitfor(dbhost, dbport)\n\n print(\"Connecting to Redis on {0:s}:{1:d} ...\".format(dbhost, dbport))\n\n connection_setup(host=dbhost, port=dbport)\n\n print(\"Success!\")\n\n db = get_client()\n\n return db\n\n\nclass TodoApp(Component):\n\n def init(self, db):\n self.db = db\n\n Server((\"0.0.0.0\", 8000)).register(self)\n JinjaRenderer(\"templates\", defaults=DEFAULTS).register(self)\n\n Root().register(self)\n Add().register(self)\n Update().register(self)\n\n def stopped(self, *args):\n print(\"Shutting down...\")\n self.db.save()\n\n\ndef main():\n sys.stdout = os.fdopen(sys.stdout.fileno(), \"w\", 0)\n\n db = setup_database()\n\n TodoApp(db).run()\n\n\nif __name__ == \"__main__\":\n main()\n", "sub_path": "todoapp/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 4105, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "circuits.Event", "line_number": 31, "usage_type": "name"}, {"api_name": "circuits.Component", "line_number": 46, "usage_type": "name"}, {"api_name": "jinja2.Environment", "line_number": 54, "usage_type": "call"}, {"api_name": "jinja2.FileSystemLoader", "line_number": 54, "usage_type": "call"}, {"api_name": "jinja2.TemplateNotFound", "line_number": 67, "usage_type": "name"}, {"api_name": "circuits.web.exceptions.NotFound", "line_number": 68, "usage_type": "call"}, {"api_name": "sys.exc_info", "line_number": 78, "usage_type": "call"}, {"api_name": "traceback.format_tb", "line_number": 79, "usage_type": "call"}, {"api_name": "circuits.web.errors.httperror", "line_number": 80, "usage_type": "call"}, {"api_name": "circuits.handler", "line_number": 56, "usage_type": "call"}, {"api_name": "circuits.web.Controller", "line_number": 83, "usage_type": "name"}, {"api_name": "models.TodoList.objects.get_or_create", "line_number": 87, "usage_type": "call"}, {"api_name": "models.TodoList.objects", "line_number": 87, "usage_type": "attribute"}, {"api_name": "models.TodoList", "line_number": 87, "usage_type": "name"}, {"api_name": "circuits.web.Controller", "line_number": 92, "usage_type": "name"}, {"api_name": "models.TodoList.objects.get_or_create", "line_number": 101, "usage_type": "call"}, {"api_name": "models.TodoList.objects", "line_number": 101, "usage_type": "attribute"}, {"api_name": "models.TodoList", "line_number": 101, "usage_type": "name"}, {"api_name": "circuits.web.Controller", "line_number": 106, "usage_type": "name"}, {"api_name": "models.TodoItem.objects.get_by_id", "line_number": 112, "usage_type": "call"}, {"api_name": "models.TodoItem.objects", "line_number": 112, "usage_type": "attribute"}, {"api_name": "models.TodoItem", "line_number": 112, "usage_type": "name"}, {"api_name": "socket.socket", "line_number": 118, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 118, "usage_type": "argument"}, {"api_name": "socket.SOCK_STREAM", "line_number": 118, "usage_type": "argument"}, {"api_name": "time.sleep", "line_number": 122, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 130, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 130, "usage_type": "name"}, {"api_name": "os.environ.get", "line_number": 131, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 131, "usage_type": "name"}, {"api_name": "redisco.connection_setup", "line_number": 139, "usage_type": "call"}, {"api_name": "redisco.get_client", "line_number": 143, "usage_type": "call"}, {"api_name": "circuits.Component", "line_number": 148, "usage_type": "name"}, {"api_name": "circuits.web.Server", "line_number": 153, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 166, "usage_type": "attribute"}, {"api_name": "os.fdopen", "line_number": 166, "usage_type": "call"}, {"api_name": "sys.stdout.fileno", "line_number": 166, "usage_type": "call"}]}
+{"seq_id": "169219636", "text": "from impala.dbapi import connect\nimport glob\nfrom datetime import date\n\nconn = connect(host='node02', port=21050, auth_mechanism='GSSAPI')\ncursor = conn.cursor()\n\ndatabase = \"data_telco\"\n\ncursor.execute(\"use \"+database)\npath = \"data/transformed_data/*.csv\"\nfiles = glob.glob(path)\n\ntoday = str(date.today().strftime(\"%Y%m%d\"))\n\nfor file in files:\n folder_name = str(file).split(\"data/transformed_data/\")[1].split(\".\")[0]\n query = 'CREATE EXTERNAL TABLE IF NOT EXISTS ' + folder_name + '(`ten_kh` string, `dia_chi` string, `sdt` bigint, `thanh_pho` string)' + \" ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' \" + \"LOCATION 'hdfs:///user/hive/warehouse/data_telco_namnn2/data_telco_\" + today + \"/\" + folder_name + \"'\"\n cursor.execute(query)", "sub_path": "vega_data_telco/create_table_impala.py", "file_name": "create_table_impala.py", "file_ext": "py", "file_size_in_byte": 746, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "impala.dbapi.connect", "line_number": 5, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 12, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 14, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 14, "usage_type": "name"}]}
+{"seq_id": "564878038", "text": "from pylab import *\r\nimport matplotlib as mpl\r\nimport numpy as np\r\n\r\nclass GridPlotter:\r\n \"\"\"\r\n Controls the production of a plot image from\r\n a geodata class. The plot image contains\r\n a series of sub plots.\r\n\r\n Author: M. Gill\r\n Copyright: M. Gill\r\n \"\"\"\r\n \r\n def __init__ (self):\r\n \"\"\"\r\n Constructor\r\n \"\"\"\r\n self.sdev = -9999\r\n self.mean = -9999\r\n self.min = -9999\r\n self.max = -9999\r\n self.shownulls = True\r\n\r\n\r\n def plotcsv(self, filename, delim, title, outfile):\r\n \"\"\"\r\n Entry point to create a plot from a csv file.\r\n The CSV file should be a formatted file, not\r\n a raw data file. Null values should be represented\r\n by nan (which indicates 'not a number').\r\n \r\n filename - a string of the full path and filename\r\n of the source data file\r\n delim - the string delimiter in the file\r\n title - the title for the plot\r\n outfile - a string of the full path and filename\r\n of the out file\r\n \"\"\"\r\n arr = np.loadtxt(filename,\r\n delimiter=delim,\r\n unpack=True)\r\n self.plotgrid(arr, title, outfile)\r\n \r\n\r\n def plotgeodata(self, geodata, title, outfile):\r\n \"\"\"\r\n Entry point to create a plot from a geodata object.\r\n \r\n geodata - the geodata object to be plotted\r\n title - the title for the plot\r\n outfile - a string of the full path and filename\r\n of the out file\r\n \"\"\"\r\n \r\n # Array columns and rows need to be swapped in order\r\n # to be shown properly on the plot (np.transpose())\r\n self.plotgrid(np.transpose(np.array(geodata.data)),\r\n title,\r\n outfile)\r\n\r\n\r\n def plotgrid(self, arr, title, outfile):\r\n \"\"\"\r\n The main controlling method for the production\r\n of a plot file.\r\n \r\n arr - the geodata object to be plotted\r\n title - the title for the plot\r\n outfile - a string of the full path and filename\r\n of the out file\r\n \"\"\"\r\n # Calculate relevant stats\r\n self.calcstats(arr) \r\n\r\n # Find positions of nulls\r\n arrnulls = self.getnullindexes(arr)\r\n\r\n # Clear figure and set global figure settings \r\n plt.clf()\r\n mpl.rc('xtick', labelsize=8)\r\n mpl.rc('ytick', labelsize=8)\r\n mpl.rc('savefig', dpi=300)\r\n\r\n fig = plt.figure(figsize=(10,10))\r\n plt.title(title)\r\n\r\n # Calculate lower and upper limit values for\r\n # the 2 standard deviations plot\r\n sdev_lower = self.mean - 2*self.sdev\r\n if sdev_lower < self.min:\r\n sdev_lower = self.min\r\n sdev_upper = self.mean + 2*self.sdev\r\n if sdev_upper > self.max:\r\n sdev_upper = self.max\r\n\r\n # Create the subplots\r\n self.makeplot(arr, 331, 'nearest', cm.gray, [],\r\n 'Grey nearest', 10,\r\n True, True, arrnulls)\r\n self.makeplot(arr, 332, 'bilinear', cm.gray, [],\r\n 'Grey bilinear', 10,\r\n True, True, arrnulls)\r\n self.makeplot(arr, 333, 'nearest', cm.gray,\r\n [sdev_lower, sdev_upper],\r\n 'Two STDEV nearest ', 10,\r\n True, True, arrnulls)\r\n self.makeplot(arr, 334, 'nearest', cm.jet, [],\r\n 'Colour nearest', 10,\r\n True, True, arrnulls)\r\n self.makeplot(arr, 335, 'bilinear', cm.jet, [],\r\n 'Colour bilinear', 10,\r\n True, True, arrnulls)\r\n self.makeplot(arr, 336, 'bilinear', cm.gray,\r\n [sdev_lower, sdev_upper],\r\n 'Two STDEV bilinear', 10,\r\n True, True, arrnulls)\r\n self.makeplot(arr, 337, 'nearest', cm.jet,\r\n [sdev_lower, sdev_upper],\r\n 'Two STDEV nearest', 10,\r\n True, True, arrnulls)\r\n self.makeplot(arr, 338, 'bilinear', cm.jet,\r\n [sdev_lower, sdev_upper],\r\n 'Two STDEV bilinear', 10,\r\n True, True, arrnulls)\r\n\r\n # Save the figure to file \r\n plt.savefig(outfile)\r\n\r\n \r\n def makeplot(self,\r\n arr,\r\n plotref,\r\n interp,\r\n colmap,\r\n col_lim,\r\n title,\r\n titlesize,\r\n showlegend,\r\n showgrid,\r\n arrnulls):\r\n \"\"\"\r\n Controls the creation of a subplot.\r\n \r\n arr - the 2D array to be plotted\r\n plotref - the subplot position index\r\n interp - the interpolation method (eg bilinear)\r\n colmap - the colormap (eg cm.jet)\r\n col_lim - lower and upper data limits as an array\r\n of format [lower_val, upper_val]\r\n title - the title to be shown for the subplot\r\n titlesize - the font size\r\n showlegend - boolean controlling legend display\r\n showgrid - boolean controlling grid display\r\n arrnulls - 2D array of null value indexes in form\r\n [[r,c],[r,c]]\r\n \"\"\"\r\n ax = plt.subplot(plotref)\r\n ax.axis('off')\r\n imgplot = plt.imshow(arr, origin='lower',\r\n interpolation=interp, cmap=colmap)\r\n if len(col_lim) != 0:\r\n imgplot.set_clim(col_lim[0], col_lim[1])\r\n plt.grid(showgrid)\r\n if showlegend:\r\n plt.colorbar()\r\n plt.title(title, size=titlesize)\r\n if len(arrnulls) > 0:\r\n self.plotnulls(ax, arrnulls)\r\n \r\n\r\n def getnullindexes(self, arr):\r\n \"\"\"\r\n Calculates the row and column indexes for null\r\n values.\r\n\r\n arr - the 2D array\r\n returns - 2D array of null value indexes in form\r\n [[r,c],[r,c]]\r\n \"\"\"\r\n arrnulls = []\r\n for r in range(0, len(arr)):\r\n for c in range(0, len(arr[r])):\r\n if math.isnan(arr[r][c]):\r\n arrnulls.append([r, c])\r\n return arrnulls\r\n\r\n\r\n def plotnulls(self, ax, arrnulls):\r\n \"\"\"\r\n Displays a small red cross at the position\r\n of a null value on the plot\r\n\r\n ax - the plot axes\r\n arrnulls - 2D array of null value indexes in form\r\n [[r,c],[r,c]] \r\n \"\"\"\r\n if self.shownulls:\r\n ax.set_autoscale_on(False)\r\n if len(arrnulls) == 0:\r\n return\r\n\r\n for i in range(0, len(arrnulls)):\r\n ax.plot([arrnulls[i][1]], [arrnulls[i][0]],\r\n 'rx', markersize=3, mew=1)\r\n \r\n\r\n def filternans(self, arr):\r\n \"\"\"\r\n Creates a list of values from a 2D array, filtering\r\n out nan (not a number) values.\r\n\r\n arr - the array of values to be filtered\r\n returns - a filtered list of values \r\n \"\"\"\r\n list = []\r\n for r in range(0, len(arr)):\r\n for c in range(0, len(arr[r])):\r\n if not math.isnan(arr[r][c]):\r\n list.append(arr[r][c])\r\n return np.array(list)\r\n \r\n\r\n def calcstats(self, arr):\r\n \"\"\"\r\n Calculates mean and standard deviation\r\n statistics for an array of values.\r\n\r\n arr - the array for which stats are to be\r\n calculated \r\n \"\"\"\r\n arrfilt = self.filternans(arr)\r\n self.sdev = np.std(arrfilt)\r\n self.mean = np.mean(arrfilt)\r\n self.min = np.min(arrfilt)\r\n self.max = np.max(arrfilt)\r\n\r\n", "sub_path": "geoconverter/src/geoconverter/GridPlotter.py", "file_name": "GridPlotter.py", "file_ext": "py", "file_size_in_byte": 7739, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "numpy.loadtxt", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 58, "usage_type": "call"}, {"api_name": "matplotlib.rc", "line_number": 81, "usage_type": "call"}, {"api_name": "matplotlib.rc", "line_number": 82, "usage_type": "call"}, {"api_name": "matplotlib.rc", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 221, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 233, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 234, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 235, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 236, "usage_type": "call"}]}
+{"seq_id": "412212094", "text": "\nfrom mrjob.job import MRJob\n\n# Avoid broken pipe error\nfrom signal import signal, SIGPIPE, SIG_DFL\nsignal(SIGPIPE,SIG_DFL) \n\nclass LJ(MRJob):\n def mapper_init(self):\n self.urls = {}\n with open(\"urls.txt\") as urls:\n for line in urls:\n url, key = line.strip().replace('\"',\"\").split(\",\")\n self.urls[key] = url\n \n def mapper(self, _, lines):\n try:\n yield (lines, self.urls[lines[2:6]])\n except ValueError:\n yield (lines, \"\")\n \nif __name__ == \"__main__\":\n LJ.run()", "sub_path": "week5/lj.py", "file_name": "lj.py", "file_ext": "py", "file_size_in_byte": 574, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "signal.signal", "line_number": 6, "usage_type": "call"}, {"api_name": "signal.SIGPIPE", "line_number": 6, "usage_type": "argument"}, {"api_name": "signal.SIG_DFL", "line_number": 6, "usage_type": "argument"}, {"api_name": "mrjob.job.MRJob", "line_number": 8, "usage_type": "name"}]}
+{"seq_id": "69947016", "text": "#Selenium imports here\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom bs4 import BeautifulSoup\nimport time\nimport re\nfrom urllib.request import urlopen\n# from urllib.request import urlopen \nimport json\nfrom pandas.io.json import json_normalize\nimport pandas as pd, numpy as np\nimport bs4, requests\n\n\n#Other imports here\nimport os\nimport wget\n\ndriver=webdriver.Chrome('C:/Users/Professional/Downloads/chromedriver_win32/chromedriver.exe')\n\n# Fisiere txt\ninstagram = open('./instagram.txt', 'r') \n\n#Variables\nURL='https://www.instagram.com/'\nURL_BEST = 'https://www.instagram.com/best_chisinau/'\nPOST_URL_PATTERN='https://www.instagram.com/best_chisinau/p/'\npost_xpath_str = \"//a[contains(@href, '/p/')]\"\npost_links = driver.find_elements_by_xpath(post_xpath_str)\npost_link_el = None\n\ndriver.get(URL)\n\n#target username\nusername = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, \"input[name='username']\")))\npassword = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, \"input[name='password']\")))\n\n#enter username and password\nusername.clear()\nusername.send_keys(\"massveritas\")\npassword.clear()\npassword.send_keys(\"#123456\")\n\n#target the login button and click it\nbutton = WebDriverWait(driver, 2).until(EC.element_to_be_clickable((By.CSS_SELECTOR, \"button[type='submit']\"))).click()\n\n\n#nadle NOT NOW\nnot_now = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//button[contains(text(), \"Not Now\")]'))).click()\n# not_now2 = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//button[contains(text(), \"Not Now\")]'))).click()\n\ndriver.implicitly_wait(10)\n\ndriver.get(URL_BEST)\n\n# scroll to the bottom of the page\nlenOfPage = driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;\")\nmatch=False\nwhile(match==False):\n lastCount = lenOfPage\n time.sleep(3)\n lenOfPage = driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;\")\n if lastCount==lenOfPage:\n match=True\n\n# find all links on the page and if they match '/p' append to list named posts\nposts = []\nlinks = driver.find_elements_by_tag_name('a')\nfor link in links:\n post = link.get_attribute('href')\n if '/p/' in post:\n posts.append( post )\n\nfor post in posts:\n driver.get( post )\n page = requests.get(post)\n soup = BeautifulSoup(page.text, \"lxml\")\n print(soup.find_all('span'))\n\ninstagram = open('./instagram.txt', 'r') \n\n\n# Citire line by line\n# \nLines = instagram.readlines()\n\n#Variabile\ninstagram_array=[]\nroman_numbers=[]\nkeys=[]\n\n#Parsing txts\nfor line in Lines: \n new_line = line.strip().split(':')\n instagram_array.append(new_line)\n\nclass Solution(object):\n def romanToInt(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}\n i = 0\n num = 0\n while i < len(s):\n if i+130*60):\n print('Downloading',csv_fn)\n _download_file(csv_remote_fp, csv_fp)\n\ndef _load_National_data(csv_fp):\n df_arg = pd.read_csv(csv_fp)\n df_arg['LOCATION'] = 'ARGENTINA/' + df_arg['PROVINCIA']\n df_arg = df_arg.drop(columns=['PROVINCIA'])\n df_arg = df_arg.set_index(['TYPE','LOCATION'])\n df_arg = df_arg.rename(columns=lambda colname: pd.to_datetime(colname,format='%d/%m').replace(year=2020))\n\n total_arg = df_arg.groupby(level=[0]).sum()\n total_arg['LOCATION']='ARGENTINA'\n total_arg = total_arg.reset_index().set_index(['TYPE','LOCATION'])\n\n df_arg = pd.concat([df_arg,total_arg]).sort_index()\n df_arg = df_arg[df_arg.columns[:-1]]\n return df_arg\n\ndef _set_location_safe(row):\n location_prefix = 'ARGENTINA/SANTA FE'\n if row['DEPARTMENT']=='##TOTAL':\n return location_prefix\n location_prefix += '/'+row['DEPARTMENT'][3:]\n if row['PLACE'].startswith('#'):\n return location_prefix\n return location_prefix +'/'+ row['PLACE']\n\ndef _load_SantaFe_data(csv_fp):\n df_safe = pd.read_csv(csv_fp)\n df_safe['LOCATION'] = df_safe.apply(_set_location_safe, axis=1)\n df_safe = df_safe[ (df_safe['TYPE']=='CONFIRMADOS') & (df_safe['DEPARTMENT']!='##TOTAL') ]\n df_safe['LOCATION'] = df_safe['LOCATION'].replace({\n 'ARGENTINA/SANTA FE/IRIONDO/CLASSON':'ARGENTINA/SANTA FE/IRIONDO/CLASON',\n 'ARGENTINA/SANTA FE/ROSARIO/VILLA GOB. GALVEZ':'ARGENTINA/SANTA FE/ROSARIO/VILLA GOBERNADOR GALVEZ',\n 'ARGENTINA/SANTA FE/SAN LORENZO/PUERTO GRAL. SAN MARTIN': 'ARGENTINA/SANTA FE/SAN LORENZO/PUERTO GENERAL SAN MARTIN',\n })\n df_safe = df_safe.drop(columns=['DEPARTMENT', 'PLACE'])\n df_safe = df_safe.set_index(['TYPE','LOCATION'])\n df_safe = df_safe.rename(columns=lambda colname: pd.to_datetime(colname,format='%d/%m/%Y'))\n return df_safe\n\ndef _load_data_time_series(df_geoinfo):\n df_arg = _load_National_data(os.path.join(DATA_DIR, 'Argentina_Provinces.csv'))\n df_safe = _load_SantaFe_data(os.path.join(DATA_DIR, 'SantaFe_AllData.csv'))\n df = pd.concat([df_arg,df_safe])\n # Non described dates are 0's\n df = df.fillna(0).sort_index()\n # Set day 0 (prior any date) with all 0's\n day_zero = df.columns[0]-pd.Timedelta(days=1)\n df[day_zero]=0\n df = df[df.columns.sort_values()]\n\n # Add per capita fields\n df_per_capita = pd.merge((df*10000).reset_index(),df_geoinfo[['LOCATION','POPULATION']],on='LOCATION',how='left')\n df_per_capita = df_per_capita.fillna(math.inf).set_index(['TYPE','LOCATION'])\n df_per_capita = df_per_capita.div(df_per_capita['POPULATION'], axis=0)\n df_per_capita = df_per_capita.drop(columns=['POPULATION'])\n df_per_capita.index = df_per_capita.index.map(lambda x : (x[0]+'_PER100K',x[1]) )\n df = pd.concat([df,df_per_capita]).sort_index()\n\n # Calculate number afected subregions\n are_confirmados = df.loc['CONFIRMADOS']>0\n are_confirmados['PARENT_LOCATION'] = are_confirmados.index.map(lambda l : os.path.dirname(l))\n affected_subregions = are_confirmados.groupby('PARENT_LOCATION').sum()\n affected_subregions = affected_subregions.reset_index().rename(columns={'PARENT_LOCATION':'LOCATION'})\n affected_subregions = affected_subregions[ affected_subregions['LOCATION']!='' ]\n affected_subregions['TYPE']='AFFECTED_SUBREGIONS'\n affected_subregions = affected_subregions.set_index(['TYPE','LOCATION'])\n df = pd.concat([df,affected_subregions]).sort_index()\n\n # Calculate difference and differnce ratio with last day\n df_shift = df.shift(axis=1).fillna(0)\n df_diff = df-df_shift\n df_diff.index = df_diff.index.map(lambda x : (x[0]+'_DIFF',x[1]) )\n df_diff_ration = ((df-df_shift)/df_shift).fillna(0)\n df_diff_ration.index = df_diff_ration.index.map(lambda x : (x[0]+'_DIFF_RATIO',x[1]) )\n\n df = pd.concat([df,df_diff,df_diff_ration,affected_subregions])\n\n # Erase non sense columns\n nonsense_columns = [ 'ACTIVOS_PER100K_DIFF_RATIO',\n 'AFFECTED_SUBREGIONS_DIFF_RATIO',\n 'CONFIRMADOS_PER100K_DIFF_RATIO',\n 'MUERTOS_PER100K_DIFF_RATIO',\n 'RECUPERADOS_PER100K_DIFF_RATIO' ]\n df = df[df.index.map(lambda i : i[0] not in nonsense_columns)]\n return df\n\ndef _time_series_melt(df_time_series, df_geoinfo):\n df = pd.melt(df_time_series, id_vars=['TYPE','LOCATION'], value_vars=df_time_series.columns[2:], var_name='date')\n df = df.pivot_table(index=['LOCATION','date'], columns='TYPE', values='value').reset_index()\n df = pd.merge(df,df_geoinfo,on='LOCATION',how='left')\n return df\n\ndef _only_povs(df):\n df = df[ df['LOCATION'].apply(lambda l : l.count('/')==1) ].copy()\n df['LOCATION'] = df['LOCATION'].apply(lambda l : l[10:])\n return df\n\ndef _soon_deprecated_data(df_time_series, df_info):\n df_time_series=_only_povs(df_time_series)\n df_info=_only_povs(df_info)\n df_time_series['2020-03-02 00:00:00']=0.0\n\n df = pd.melt(df_time_series, id_vars=['TYPE','LOCATION'], value_vars=df_time_series.columns[2:], var_name='date')\n df = df[ df['TYPE'].apply(lambda t: t in ['ACTIVOS','CONFIRMADOS','MUERTOS','RECUPERADOS']) ]\n df['TYPE'] = df['TYPE'].replace({\n 'ACTIVOS': 'active',\n 'CONFIRMADOS': 'confirmed',\n 'MUERTOS': 'deceased',\n 'RECUPERADOS': 'recovered',\n })\n df = pd.merge(df,df_info,on='LOCATION')\n df['Province/State']=df['LOCATION']\n df = df.rename(columns={\n 'TYPE':'var',\n 'LAT':'Lat',\n 'LONG':'Long',\n 'LOCATION':'Country/Region',\n 'POPULATION': 'population',\n })\n df = df[ [ 'date', 'Country/Region', 'Province/State', 'var', 'value', 'Lat', 'Long', 'population' ] ]\n df = df.sort_values(by=['Country/Region','date','var'])\n df['value_new'] = df['value'].diff(4)\n df = df.sort_values(by=['date', 'Country/Region','var'])\n df = df[df['date']!='2020-03-02']\n return df\n\ndef _calculate_global_status():\n df_geoinfo = pd.read_csv(os.path.join(DATA_DIR, 'info_general.csv'))\n df_time_series =_load_data_time_series(df_geoinfo).reset_index()\n df_time_series_melt = _time_series_melt(df_time_series,df_geoinfo)\n return {\n 'timestamp': datetime.datetime.today().strftime('%Y-%m-%d-%H:%M:%S'),\n 'geoinfo': df_geoinfo,\n 'time_series': df_time_series,\n 'time_series_melt': df_time_series_melt,\n 'soon_deprecated': _soon_deprecated_data(df_time_series, df_geoinfo)\n }\n\n_global_status = None\ndef backend_update_data():\n global _global_status\n print(\"Updating backend...\")\n _download_expired_data()\n _global_status = _calculate_global_status()\n\ndef backend_global_status_getter(field):\n global _global_status\n return _global_status[field]\n\ndef backend_data_at_date(date):\n global _global_status\n return _global_status['time_series'][date].swaplevel(0,1).unstack()\n\ndef backend_filter_location_by_level(df, level, extract_name=True):\n if level=='LEAF':\n have_childs = set(df['LOCATION'].apply(lambda l : os.path.dirname(l)))\n df = df[ df['LOCATION'].apply(lambda l : l not in have_childs) ]\n else:\n to_level_map = { 'COUNTRY': 0,\n 'PROVINCE': 1,\n 'DEPARTMENT': 2,\n 'CITY': 3 }\n if type(level)==str:\n level = to_level_map[level]\n df = df[ df['LOCATION'].apply(lambda l : l.count('/')) == level ]\n if extract_name:\n df['LOCATION'] = df['LOCATION'].apply(lambda l : os.path.basename(l))\n return df\n", "sub_path": "backend.py", "file_name": "backend.py", "file_ext": "py", "file_size_in_byte": 8628, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "requests.get", "line_number": 20, "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.isfile", "line_number": 30, "usage_type": "call"}, {"api_name": "os.path", "line_number": 30, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 30, "usage_type": "call"}, {"api_name": "os.stat", "line_number": 30, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 35, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 39, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 45, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 59, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 69, "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": 74, "usage_type": "call"}, {"api_name": "os.path", "line_number": 74, "usage_type": "attribute"}, {"api_name": "pandas.concat", "line_number": 75, "usage_type": "call"}, {"api_name": "pandas.Timedelta", "line_number": 79, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 84, "usage_type": "call"}, {"api_name": "math.inf", "line_number": 85, "usage_type": "attribute"}, {"api_name": "pandas.concat", "line_number": 89, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 93, "usage_type": "call"}, {"api_name": "os.path", "line_number": 93, "usage_type": "attribute"}, {"api_name": "pandas.concat", "line_number": 99, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 108, "usage_type": "call"}, {"api_name": "pandas.melt", "line_number": 120, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 122, "usage_type": "call"}, {"api_name": "pandas.melt", "line_number": 135, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 143, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 160, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 160, "usage_type": "call"}, {"api_name": "os.path", "line_number": 160, "usage_type": "attribute"}, {"api_name": "datetime.datetime.today", "line_number": 164, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 164, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 188, "usage_type": "call"}, {"api_name": "os.path", "line_number": 188, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 199, "usage_type": "call"}, {"api_name": "os.path", "line_number": 199, "usage_type": "attribute"}]}
+{"seq_id": "308891261", "text": "from jieba import lcut\nimport re\nimport sys\nimport numpy as np\nfrom memory_profiler import profile\n\n\n# coding=utf-8\n# 读取目标文档\n@profile\ndef readText(path):\n f = open(path, 'r', encoding='utf-8')\n text = f.read()\n # text = []\n # for line in f.readlines(): # 依次读取每行\n # line = line.strip() # 去掉每行头尾空白\n # if not len(line) or line.startswith('#'): # 判断是否是空行或注释行\n # continue\n # text.append(line)\n # text.sort()\n return text # 排序后将文档返回\n\n\n# 利用结巴算法对目标文档进行“分词”处理\n@profile\ndef cut(text):\n words = []\n seg_list = lcut(text, cut_all=False) # 使用jieba下的lcut()方法,精确分割,返回一个列表\n pat = re.compile(u'[a-zA-Z0-9\\u4e00-\\u9fa5]').sub(\" \", \"\") # 将正则表达式转换为内部格式,提高执行效率\n for word in seg_list:\n if re.match(pat, word):\n words.append(word) # 筛选出不含标点符号的结果\n else:\n pass\n return words\n\n\n# 对于两个文档中相同词语进行追加合并进列表\n\ndef mergeWords(t1, t2):\n MergeWords = []\n for i in t1:\n MergeWords.append(i)\n for i in t2:\n if i not in MergeWords:\n MergeWords.append(i)\n return MergeWords\n\n\n# 分别统计两个文档关键词和词频并合并结果转化为向量(vector)\n\ndef countWords(MergeWords, t1, t2):\n list1 = [0 for i in range(len(MergeWords))] # 设定长度并赋值为0\n count1 = dict(zip(MergeWords, list1)) # 设置一个具有���并后词列表的键,但值为零的字典\n for x in t1:\n if x in MergeWords:\n count1[x] += 1 # 遍历合并列表,计算出词频\n else:\n pass\n\n list2 = [0 for i in range(len(MergeWords))]\n count2 = dict(zip(MergeWords, list2))\n for y in t2:\n if y in MergeWords:\n count2[y] += 1\n else:\n pass\n vec1 = list(count1.values()) # 将字典转化为列表类型\n vec2 = list(count2.values())\n return vec1, vec2\n\n\n# 通过向量计算余弦相似度(cosine_similarity)\n\ndef cosine_similarity(v1, v2):\n a = np.array(v1) # 将向量列表转化为数组形式\n b = np.array(v2)\n ma = np.linalg.norm(a) # np.linalg.norm()对数组求整体元素的平方和开根号\n mb = np.linalg.norm(b)\n sim = (np.matmul(a, b)) / (ma * mb) # np.matmul()方法计算内积,结果为余弦相似度\n return sim\n\n\n# 主函数,其包含调用其他函数\n\ndef Main(p1, p2, f) -> object:\n try:\n t1 = cut(readText(p1))\n t2 = cut(readText(p2))\n\n mw = mergeWords(t1, t2)\n v1, v2 = countWords(mw, t1, t2)\n result = cosine_similarity(v1, v2)\n result = np.float(result)*100\n result = round(result, 2) # 保留小数点后两位\n print(\"文本相似度为:\"+str(result)+\"%\")\n fh = open(f, \"a\", encoding='utf-8')\n fh.write(str(p1) + \"与\" + str(p2) + \"的相似度:\" + str(result)+\"%\")\n fh.close()\n except FileNotFoundError:\n print(\"文件不存在!\")\n\n\n# 函数入口\nif __name__ == '__main__':\n path1 = \"\"\n path2 = \"\"\n file_save = \"\"\n try:\n path1 = sys.argv[1] # 实现与命令行交互\n path2 = sys.argv[2]\n file_save = sys.argv[3]\n except IndexError:\n path1 = input(\"请输入正版文件路径:\")\n path2 = input(\"请输入抄袭文件路径:\")\n file_save = input(\"请输入你要保存结果的路径:\")\n Main(path1, path2, file_save)\n", "sub_path": "3119005430/main/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 3601, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "memory_profiler.profile", "line_number": 10, "usage_type": "name"}, {"api_name": "jieba.lcut", "line_number": 28, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 29, "usage_type": "call"}, {"api_name": "re.match", "line_number": 31, "usage_type": "call"}, {"api_name": "memory_profiler.profile", "line_number": 25, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 76, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 78, "usage_type": "attribute"}, {"api_name": "numpy.linalg.norm", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 79, "usage_type": "attribute"}, {"api_name": "numpy.matmul", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.float", "line_number": 94, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 110, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 111, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 112, "usage_type": "attribute"}]}
+{"seq_id": "299678464", "text": "import argparse\nfrom cocos.director import director\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--sprite', nargs=1)\nparser.add_argument('--bg', nargs=1)\nparser.add_argument('--level', nargs=1)\nargs = parser.parse_args()\n\ndirector.init()\nscene = None\n\nif args.sprite is not None:\n # To run this test:\n # $ python . --sprite game.sprite.test.StickSprite.run --bg 255,255,255,255\n from importlib import import_module\n from game.scene.tests import SpriteTestScene\n\n module, sheet, sprite = args.sprite[0].rsplit('.', 2)\n module = import_module(module)\n sheet = getattr(module, sheet)\n sprite = getattr(sheet, sprite)\n bg = args.bg[0].split(',') if args.bg else None\n\n scene = SpriteTestScene(sprite, bg)\n\nelif args.level is not None:\n # To run this test:\n # $ python . --level 1\n from game.scene.level import LevelScene\n scene = LevelScene(args.level[0])\n\nelse:\n from game.scene import first_scene\n scene = first_scene()\n\ndirector.run(scene)\n", "sub_path": "__main__.py", "file_name": "__main__.py", "file_ext": "py", "file_size_in_byte": 1000, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "76", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 5, "usage_type": "call"}, {"api_name": "cocos.director.director.init", "line_number": 11, "usage_type": "call"}, {"api_name": "cocos.director.director", "line_number": 11, "usage_type": "name"}, {"api_name": "importlib.import_module", "line_number": 21, "usage_type": "call"}, {"api_name": "game.scene.tests.SpriteTestScene", "line_number": 26, "usage_type": "call"}, {"api_name": "game.scene.level.LevelScene", "line_number": 32, "usage_type": "call"}, {"api_name": "game.scene.first_scene", "line_number": 36, "usage_type": "call"}, {"api_name": "cocos.director.director.run", "line_number": 38, "usage_type": "call"}, {"api_name": "cocos.director.director", "line_number": 38, "usage_type": "name"}]}
+{"seq_id": "67447102", "text": "import json\nimport streamlit as st\nfrom hydralit import HydraHeadApp\nimport time\nimport requests\nimport logging\n\nURL = \"http://0.0.0.0:8080\"\ncurrent_time = time.strftime(\"%H%M%S-%d%M%y\")\nfile_name = \"transcript_\" + str(current_time)\n\n\nclass SpeechToTextApp(HydraHeadApp):\n\n def __init__(self, title=\"\", **kwargs):\n self.__dict__.update(kwargs)\n self.title = title\n self.logger = logging.getLogger(__name__)\n\n def run(self):\n\n try:\n # ----------------------------------------------------------------\n # Show display of Speech To Text app\n st.title(\"Speech To Text\")\n st.subheader(\"App to transcribe available audio voice to text\")\n st.markdown('
', unsafe_allow_html=True)\n\n _, col2, _ = st.columns((1, 8, 1))\n self.display_app_header(self.title, True)\n # ----------------------------------------------------------------\n\n # ----------------------------------------------------------------\n # selection of acoustic model and language model\n arg_return = self.generate_sidebar()\n\n # upload file audio\n upload_complete, audio_file = self.upload_file(col2)\n\n # transcribe audio\n trans_btn = col2.button(\"Transcribe\")\n\n if upload_complete:\n predict_str = None\n if trans_btn:\n predict_str = self.predict(audio_file)\n\n if predict_str is not None:\n transcript_result = col2.text_area(\"Text Transcript\", value=predict_str[\"word\"], height=300)\n\n if transcript_result is not None:\n self.save_transcript(col2, transcript_result)\n\n except Exception as e:\n st.image(\"./resources/failure.png\", width=100, )\n st.error(\n 'An error has occurred, someone will be punished for your inconvenience, we humbly request you try again.')\n st.error('Error details: {}'.format(e))\n\n def save_transcript(self, col, result):\n if result is not None:\n _result = result.strip()\n\n try:\n col.download_button(label=\"Save transcript\",\n data=_result,\n file_name=f'{file_name}.txt',\n mime='text/csv')\n\n col.success(\"Save transcript successfully\")\n self.logger.info(\"Saved transcript successfully\")\n\n except Exception as e:\n col.error(\"Error saving transcript: {}\".format(e))\n self.logger.error(\"Error saving transcript: {}\".format(e))\n\n def predict(self, audio_file):\n values = {\"file\": (audio_file.name, audio_file, \"audio/wav\")}\n\n st.session_state.text_result = None\n\n if isinstance(values, dict):\n try:\n response = requests.post(f\"{URL}/predict\", files=values)\n st.session_state.text_result = response.json()\n\n if st.session_state.text_result is not None:\n self.logger.info(f\"Predict: {st.session_state.text_result}\")\n else:\n self.logger.warning(\"Predict failed\")\n\n except Exception as e:\n st.error('Error details: {}'.format(e))\n self.logger.error(f\"Error: {e}\")\n\n else:\n st.warning('Predict failed')\n self.logger.info('Predict failed')\n\n return st.session_state.text_result\n\n def generate_sidebar(self):\n if \"predict_arg\" not in st.session_state:\n st.session_state.predict_arg = {\"model\": \"model1\",\n \"lm\": \"CTC + 4-gram\"}\n if \"acoustic_model\" not in st.session_state:\n st.session_state.acoustic_model = \"model1\"\n if \"lm\" not in st.session_state:\n st.session_state.lm_option = \"CTC + 4-gram\"\n\n with st.sidebar:\n acoustic_model_option = st.selectbox(\"Which acoustic model?\",\n ('Model 50k', 'Model 130k'))\n st.info(f\"You selected:{acoustic_model_option}\")\n if acoustic_model_option == \"Model 50k\":\n st.session_state.acoustic_model = \"model1\"\n elif acoustic_model_option == \"Model 130k\":\n st.session_state.acoustic_model = \"model2\"\n st.session_state.lm_option = st.selectbox(\"Which language model?\",\n (\"CTC\", \"CTC + 4-gram\"))\n st.info(f\"You selected:{st.session_state.lm_option}\")\n\n if st.session_state.acoustic_model == \"\" or st.session_state.lm_option == \"\":\n st.sidebar.warning(\"Setting must not be empty\")\n\n if st.session_state.predict_arg != {\"model\": st.session_state.acoustic_model,\n \"lm\": st.session_state.lm_option}:\n st.session_state.predict_arg = {\"model\": st.session_state.acoustic_model,\n \"lm\": st.session_state.lm_option}\n arg_request = json.dumps(st.session_state.predict_arg)\n response = requests.post(f\"{URL}/pattern\", data=arg_request)\n arg_return = response.json()\n\n return arg_return\n\n def upload_file(self, col):\n st.session_state.audio_file = col.file_uploader(\"Upload audio\", type=['wav', 'mp3'])\n if st.session_state.audio_file is not None:\n col.success(\"File uploaded successfully\")\n col.audio(st.session_state.audio_file)\n st.session_state.upload_complete = True\n else:\n col.info(\"Please upload a audio file\")\n st.session_state.upload_complete = False\n\n return st.session_state.upload_complete, st.session_state.audio_file\n\n def display_app_header(self, main_txt, is_sidebar=False):\n \"\"\"\n function to display major headers at user interface\n ----------\n main_txt: str -> the major text to be displayed\n sub_txt: str -> the minor text to be displayed \n is_sidebar: bool -> check if its side panel or major panel\n \"\"\"\n\n html_temp = f\"\"\"\n {main_txt}
\n \n \"\"\"\n if is_sidebar:\n st.sidebar.markdown(html_temp, unsafe_allow_html=True)\n else:\n st.markdown(html_temp, unsafe_allow_html=True)\n", "sub_path": "apps/stt_app.py", "file_name": "stt_app.py", "file_ext": "py", "file_size_in_byte": 6551, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "time.strftime", "line_number": 9, "usage_type": "call"}, {"api_name": "hydralit.HydraHeadApp", "line_number": 13, "usage_type": "name"}, {"api_name": "logging.getLogger", "line_number": 18, "usage_type": "call"}, {"api_name": "streamlit.title", "line_number": 25, "usage_type": "call"}, {"api_name": "streamlit.subheader", "line_number": 26, "usage_type": "call"}, {"api_name": "streamlit.markdown", "line_number": 27, "usage_type": "call"}, {"api_name": "streamlit.columns", "line_number": 29, "usage_type": "call"}, {"api_name": "streamlit.image", "line_number": 55, "usage_type": "call"}, {"api_name": "streamlit.error", "line_number": 56, "usage_type": "call"}, {"api_name": "streamlit.error", "line_number": 58, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 80, "usage_type": "attribute"}, {"api_name": "requests.post", "line_number": 84, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 85, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 87, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 88, "usage_type": "attribute"}, {"api_name": "streamlit.error", "line_number": 93, "usage_type": "call"}, {"api_name": "streamlit.warning", "line_number": 97, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 100, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 103, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 104, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 106, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 107, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 108, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 109, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar", "line_number": 111, "usage_type": "attribute"}, {"api_name": "streamlit.selectbox", "line_number": 112, "usage_type": "call"}, {"api_name": "streamlit.info", "line_number": 114, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 116, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 118, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 119, "usage_type": "attribute"}, {"api_name": "streamlit.selectbox", "line_number": 119, "usage_type": "call"}, {"api_name": "streamlit.info", "line_number": 121, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 121, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 123, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.warning", "line_number": 124, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 124, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 126, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 127, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 128, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 129, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 130, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 130, "usage_type": "attribute"}, {"api_name": "requests.post", "line_number": 131, "usage_type": "call"}, {"api_name": "streamlit.session_state", "line_number": 137, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 138, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 140, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 141, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 144, "usage_type": "attribute"}, {"api_name": "streamlit.session_state", "line_number": 146, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.markdown", "line_number": 162, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 162, "usage_type": "attribute"}, {"api_name": "streamlit.markdown", "line_number": 164, "usage_type": "call"}]}
+{"seq_id": "130151323", "text": "import datetime\nimport glob\nimport os\nfrom jinja2 import Template\n\ndef main():\n pages = []\n# Auto-discovery of content files\n all_content_files = glob.glob(\"content/*.md\")\n\n for page in all_content_files:\n file_name = os.path.basename(page)\n name_only, extension = os.path.splitext(file_name)\n pages.append({\n \"filename\": \"content/\" + file_name,\n \"title\": name_only,\n \"output\": file_name\n })\n# Create final pages using content files with jinja2 templating\n year = datetime.datetime.now().strftime('%Y')\n for page in all_content_files:\n file_name = os.path.basename(page)\n name_only, extension = os.path.splitext(file_name)\n content_page = open(\"content/\" + file_name).read()\n template_html = open(\"templates/base.md\").read()\n template = Template(template_html)\n results = template.render(\n title=name_only,\n content=content_page,\n year=str(year),\n pages=pages,\n )\n open(\"docs/\"+name_only+\".html\",\"w+\").write(results)\n\n# Auto-generated blog pages\n# NOT WORKING!!\n # blog_pages = []\n # all_blog_posts = glob.glob(\"blog/*.md\")\n \n # for blog in all_blog_posts:\n # blog_pages.append(open(blog).read())\n\n # for blog in blog_pages:\n # file_name = os.path.basename(blog)\n # template_html = open(\"templates/blog_base.md\").read()\n # template2 = Template(template_html)\n # results = template.render(\n # blog=blog,\n # year=str(year),\n # )\n # open(\"docs/\"+file_name,\"w+\").write(results)", "sub_path": "utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 1635, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "65", "api": [{"api_name": "glob.glob", "line_number": 9, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 12, "usage_type": "call"}, {"api_name": "os.path", "line_number": 12, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path", "line_number": 13, "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": "os.path.basename", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path", "line_number": 22, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path", "line_number": 23, "usage_type": "attribute"}, {"api_name": "jinja2.Template", "line_number": 26, "usage_type": "call"}]}
+{"seq_id": "358528820", "text": "from __future__ import print_function, unicode_literals\nimport os\nimport sys\nimport tempfile\nimport boto3\nimport json\nfrom glob import glob\nfrom shutil import copyfile\nfrom aws_tools.s3_handler import S3Handler\nfrom general_tools.file_utils import write_file\nfrom door43_tools import templaters\nfrom datetime import datetime, timedelta\n\n\nclass ProjectDeployer(object):\n \"\"\"\n Deploys a project's revision to the door43.org bucket\n\n Read from the project's user dir in the cdn.door43.org bucket\n by applying the door43.org template to the raw html files\n \"\"\"\n\n def __init__(self, cdn_bucket, door43_bucket):\n \"\"\"\n :param string cdn_bucket: \n :param string door43_bucket: \n \"\"\"\n self.cdn_bucket = cdn_bucket\n self.door43_bucket = door43_bucket\n self.cdn_handler = None\n self.door43_handler = None\n self.lambda_client = None\n self.setup_resources()\n\n def setup_resources(self):\n self.cdn_handler = S3Handler(self.cdn_bucket)\n self.door43_handler = S3Handler(self.door43_bucket)\n self.lambda_client = boto3.client('lambda', region_name='us-west-2')\n\n def deploy_revision_to_door43(self, build_log_key):\n \"\"\"\n Deploys a single revision of a project to door43.org\n :param string build_log_key:\n :return bool:\n \"\"\"\n build_log = None\n try:\n build_log = self.cdn_handler.get_json(build_log_key)\n except:\n pass\n\n if not build_log or 'commit_id' not in build_log or 'repo_owner' not in build_log or 'repo_name' not in build_log:\n return False\n\n user = build_log['repo_owner']\n repo_name = build_log['repo_name']\n commit_id = build_log['commit_id'][:10]\n\n s3_commit_key = 'u/{0}/{1}/{2}'.format(user, repo_name, commit_id)\n s3_repo_key = 'u/{0}/{1}'.format(user, repo_name)\n\n source_dir = tempfile.mkdtemp(prefix='source_')\n output_dir = tempfile.mkdtemp(prefix='output_')\n template_dir = tempfile.mkdtemp(prefix='template_')\n\n self.cdn_handler.download_dir(s3_commit_key, source_dir)\n source_dir = os.path.join(source_dir, s3_commit_key)\n\n resource_type = build_log['resource_type']\n if resource_type == 'ulb' or resource_type == 'udb':\n resource_type = 'bible'\n\n # determining the template and templater from the resource_type, use general if not found\n try:\n templater_class = self.str_to_class('templaters.{0}Templater'.format(resource_type.capitalize()))\n template_key = 'templates/{0}.html'.format(resource_type)\n except AttributeError:\n templater_class = templaters.Templater\n template_key = 'templates/obs.html' # Use a generic template here\n\n template_file = os.path.join(template_dir, 'template.html')\n print(\"Downloading {0} to {1}...\".format(template_key, template_file))\n self.door43_handler.download_file(template_key, template_file)\n\n html_files = sorted(glob(os.path.join(source_dir, '*.html')))\n if len(html_files) < 1:\n content = ''\n if len(build_log['errors']) > 0:\n content += \"\"\"\n