diff --git "a/4548.jsonl" "b/4548.jsonl" new file mode 100644--- /dev/null +++ "b/4548.jsonl" @@ -0,0 +1,653 @@ +{"seq_id":"529381989","text":"from Utilities.PrimeGenerator import PrimeGenerator, is_prime\n\n\ndef main():\n n, maxlen = 1000000, 0\n Set = list(PrimeGenerator(under=10000))\n newb = 2\n for a in range(4):\n for b in range(newb, len(Set)):\n subset = Set[a:b]\n s = sum(subset)\n if is_prime(s) and s < n and len(subset) > maxlen:\n length = len(subset)\n sumprime = s\n maxlen = length\n newb = b\n print(sumprime)\n\nif __name__ == '__main__':\n main()\n","sub_path":"python35/solutions/Problem050.py","file_name":"Problem050.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"1979706","text":"# # -*-coding:utf-8 -*-\n# # 计算jaccard系数\n# def jaccard(p, q):\n# c = [i for i in p if i in q]\n# d = [i for i in p if i not in q]\n# d[0:0] = q\n# return float(len(c)) / len(d)\n#\n#\n# # 注意:在使用之前必须对两个数据集进行去重\n# # 我们用一些特殊的数据集去测试一下:\n#\n# # p = ['shirt', 'shoes', 'pants', 'socks']\n# q = ['shirt', 'shoes', 'aa', 'bb','yy']\n# p = ['a', 'b', 'c', 'd','shoes']\n# print(jaccard(p, q))\n# print(jaccard(p, p))\n\n# coding=utf-8 #\n'''\n距离求解公式\n'''\n\nimport numpy as np\nimport math\n\n\nclass Distance():\n # 依赖包numpy、python-Levenshtein、scipy\n\n\n def Euclidean(self, vec1, vec2):\n npvec1, npvec2 = np.array(vec1), np.array(vec2)\n return math.sqrt(((npvec1 - npvec2) ** 2).sum())\n\n # euclidean,欧式距离算法,传入参数为两个向量,返回值为欧式距离\n\n\n def Manhattan(self, vec1, vec2):\n npvec1, npvec2 = np.array(vec1), np.array(vec2)\n return np.abs(npvec1 - npvec2).sum()\n\n # Manhattan_Distance,曼哈顿距离\n\n\n def Chebyshev(self, vec1, vec2):\n npvec1, npvec2 = np.array(vec1), np.array(vec2)\n return max(np.abs(npvec1 - npvec2))\n\n # Chebyshev_Distance,切比雪夫距离\n\n\n def Minkowski(self, vec1, vec2, params):\n pass\n\n # MinkowskiDistance 闵可夫斯基距离,其实就是上面三种距离的集合,这里就不重复了。\n\n\n # def Standardized_Euclidean(vec1, vec2, v):\n # from scipy import spatial\n # npvec = np.array([np.array(vec1), np.array(vec2)])\n # return spatial.distance.pdist(npvec, 'seuclidean', V=None)\n # Standardized Euclidean distance,标准化欧氏距离\n # 在对长方体区域进行聚类的时候,普通的距离无法满足要求。\n # 按照普通的距离聚类出的大多是圆形的区域,这时候要采用标准的欧式距离。\n # 参考 标准化欧式距离:http://blog.csdn.net/jinzhichaoshuiping/article/details/51019473\n\n def Mahalanobis(self, vec1, vec2):\n npvec1, npvec2 = np.array(vec1), np.array(vec2)\n npvec = np.array([npvec1, npvec2])\n sub = npvec.T[0] - npvec.T[1]\n inv_sub = np.linalg.inv(np.cov(npvec1, npvec2))\n return math.sqrt(np.dot(inv_sub, sub).dot(sub.T))\n\n # MahalanobisDistance,马氏距离\n\n\n # def Edit_distance_str(self, str1, str2):\n # import Levenshtein\n # edit_distance_distance = Levenshtein.distance(str1, str2)\n # similarity = 1 - (edit_distance_distance / max(len(str1), len(str2)))\n # return {'Distance': edit_distance_distance, 'Similarity': similarity}\n\n # Levenshtein distance,编辑距离,用于计算两个字符串之间的编辑距离,传入参数为两个字符串\n\n\n def Edit_distance_array(self, str_ary1, str_ary2):\n len_str_ary1 = len(str_ary1) + 1\n len_str_ary2 = len(str_ary2) + 1\n matrix = [0 for n in range(len_str_ary1 * len_str_ary2)]\n for i in range(len_str_ary1):\n matrix[i] = i\n for j in range(0, len(matrix), len_str_ary1):\n if j % len_str_ary1 == 0:\n matrix[j] = j // len_str_ary1\n for i in range(1, len_str_ary1):\n for j in range(1, len_str_ary2):\n if str_ary1[i - 1] == str_ary2[j - 1]:\n cost = 0\n else:\n cost = 1\n matrix[j * len_str_ary1 + i] = min(matrix[(j - 1) * len_str_ary1 + i] + 1,\n matrix[j * len_str_ary1 + (i - 1)] + 1,\n matrix[(j - 1) * len_str_ary1 + (i - 1)] + cost)\n distance = int(matrix[-1])\n similarity = 1 - int(matrix[-1]) / max(len(str_ary1), len(str_ary2))\n return {'Distance': distance, 'Similarity': similarity}\n\n # 针对列表改写的编辑距离,在NLP领域中,计算两个文本的相似度,是基于句子中词和词之间的差异。\n # 如果使用传统的编辑距离算法,则计算的为文本中字与字之间的编辑次数。这里根据编辑距离的思维,\n # 将编辑距离中的处理字符串中���字符对象,变成处理list中每个元素\n\n\n def Cosine(self, vec1, vec2):\n npvec1, npvec2 = np.array(vec1), np.array(vec2)\n return npvec1.dot(npvec2) / (math.sqrt((npvec1 ** 2).sum()) * math.sqrt((npvec2 ** 2).sum()))\n # Cosine,余弦夹角\n # 机器学习中借用这一概念来衡量样本向量之间的差异。\n # 也可以使用在余弦相似度算法中\n\n\ndistance = Distance()\nvec1, vec2 = (0, 3), (4, 0)\nprint(distance.Euclidean(vec1,vec2))\nprint(distance.Manhattan(vec1,vec2))\n","sub_path":"Similarity/Jaccard.py","file_name":"Jaccard.py","file_ext":"py","file_size_in_byte":4714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"626783099","text":"def invertedIndex(docList):\n pairSet = set()\n docNumber = 1\n for doc in docList:\n for word in doc.split():\n pairSet.add((word, docNumber))\n docNumber = docNumber + 1\n\n # pairList = sorted(sorted(pairSet, key=lambda x: x[1]), key=lambda x: x[0])\n # print(pairList)\n\n invertedIndex = {}\n for pair in pairSet:\n if pair[0] in invertedIndex.keys():\n invertedIndex[pair[0]].append(pair[1])\n else:\n invertedIndex[pair[0]] = [pair[1]]\n\n for postingList in invertedIndex.values():\n postingList.sort()\n\n # print(invertedIndex)\n # invertedIndex.sort()\n for key in sorted(invertedIndex.keys()):\n # print(\"hello\")\n print(\"%s -> %s\" % (key, invertedIndex[key]))\n\n\nif __name__ == '__main__':\n doc1 = \"new home sale top forecast\"\n doc2 = \"home sale rise in july\"\n doc3 = \"increase in home sale in july\"\n doc4 = \"july new home sales rise\"\n docList = [doc1, doc2, doc3, doc4]\n invertedIndex(docList)\n","sub_path":"text-book/ex1_1.py","file_name":"ex1_1.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"439200222","text":"class Solution:\n def twoSum(self, nums: list[int], target: int) -> list[int]:\n l = len(nums)\n data = {}\n for i in range(l):\n xa = nums[i]\n if xa in data:\n return [data[xa], i]\n xb = target - xa\n data[xb] = i\n return []\n \n def alternate(self, nums: list[int], target: int) -> list[int]:\n l = len(nums)\n for i in range(l - 1):\n for j in range(i + 1, l):\n if nums[i] + nums[j] == target:\n return [i, j]\n return []\n","sub_path":"Random/twoSum.py","file_name":"twoSum.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"30510069","text":"import requests \r\nimport os\r\n\r\nh_num = eval(input(\"请输入下载的话数,只能输入一个:\")) \r\n \r\ntry:\r\n\tos.mkdir('.\\\\mh\\\\'+ h_num)\r\nexcept:\r\n\tprint('目录已存在,正在写入。。。')\r\n# 先让我想想 怎么获取URL\r\nurl = 'https://mh1.ahjsny.com/upload/envhuanghou/34/' \r\npage_num = eval(input(\"请输入页码:\"))\r\n# 用来 对请求的图片地址-->https://mh1.ahjsny.com/upload/envhuanghou/34/xxxxx.jpg\r\n# xxxx格式不一样 处理那个xxxxx的 定位图片的URL\r\nclass picture_n(object):\r\n\tdef __init__(self, n):\r\n\t\tself.n = n\r\n\tdef num(self):\r\n\t\tpage_list = []\r\n\t# 几位数前面加几个零\r\n\t\tfor i in range(self.n):\r\n\t\t\tif i < 10:\r\n\t\t\t\tpage_list.append('0' + str(i))\r\n\t\t\telif 10<= i <100:\r\n\t\t\t\tpage_list.append('00' + str(i))\r\n\t\t\telif i >= 100:\r\n\t\t\t\tpage_list.append('000' + str(i))\r\n\t\t\telse:\r\n\t\t\t\tpass\r\n\t\treturn page_list\r\n\t#只在数字前面加三个零就可以\r\n\tdef num2(self):\r\n\t\tpage_list = []\r\n\t\tfor i in range(self.n):\r\n\t\t\tpage_list.append('000' + str(i))\r\n\t\treturn page_list\r\n\t# 要有其他类型,老子再写\r\n\r\n\r\n# 用来下载图片的函数\r\ndef download(url,num):\r\n\tresponse = requests.get(url)\r\n\ttry:\r\n\t\twith open('.\\\\mh\\\\' + h_num + num + '.jpg', 'wb') as f:\r\n\t\t\tf.write(response.content)\r\n\t\t\tf.close()\r\n\texcept:\r\n\t\tprint('未知错误')\r\n\r\n\r\n# 先用函数写一个生成 图片链接的文档 \r\ndef main():\r\n\tglobal page_num\r\n\tsl_n = a = picture_n(page_num)\r\n\tfor i in sl_n.num2(page_num):\r\n\t\t# 为了让文件名好看\r\n\t\tn_2 = '{:04}'.format(n)\r\n\t\t# 写入数据\r\n\t\tf = open('html_data.txt', 'a', encoding=\"utf-8\")\r\n\t\tf.write('
'+'\\n')\r\n\t\tdownload(url+i+'.jpg',n_2)\r\n\t\tn += 1\r\n\t\tprint('正在下载'+str(int(i)+1)+'页...')\r\n\t# 打开文档 读取内容 把body 填充起来\r\n\tf = open(\"mh37.html\",'w',encoding=\"utf-8\")\r\n\t# 读取文件里的信息\r\n\tf_html_r = open(\"html_data.txt\",'r')\r\n\tf_html_r = f_html_r.read()\r\n\tmessage = \"\"\"\r\n\t\r\n\t\r\n \t \r\n \t恶女皇后漫画_第\"\"\" + h_num + \"\"\"话 \r\n \t

恶女皇后漫画_第\"\"\" + h_num + \"\"\"话

\r\n \r\n\t\r\n\t
\r\n\t\t\"\"\"+ f_html_r +\"\"\"\r\n\t
\r\n\t\r\n\t\r\n\t\"\"\"\r\n\tf.write(message)\r\n\tf.close()\r\n\r\n\r\nmain()\r\n","sub_path":"enhh/general_way.py","file_name":"general_way.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"139483032","text":"# %% -*- coding: utf-8 -*-\n\nfrom PIL import Image\nimport os\nfrom timeit import default_timer as timer\nfrom tqdm import tqdm\n\nimport torch\nimport torch.optim as optim\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader, random_split\nfrom torchvision.utils import save_image\nimport torchvision.transforms as tr\n\nfrom data import TestDataset\nfrom models import UNet\nfrom draw_bbox import generate_bbox\n\ndef predict(model, loader, batch_size, sizes, file_names, masks_path, use_gpu):\n model.eval()\n for batch_idx, image in tqdm(enumerate(loader)):\n if use_gpu:\n image = image.cuda()\n with torch.no_grad():\n image = Variable(image)\n pred = model(image)\n maxes, out = torch.max(pred, 1, keepdim=True)\n\n for i, output in enumerate(out):\n back_img = tr.ToPILImage()(output.type(torch.float32)) \n index = batch_idx*batch_size + i\n back_img = back_img.resize(sizes[index])\n back_img.save(os.path.join(masks_path, file_names[index]))\n\ndef run_pipeline(root_dir, model_path, img_size, batch_size, use_gpu):\n images_path = os.path.join(root_dir, \"images\")\n masks_path = os.path.join(root_dir, \"masks\")\n outputs_path = os.path.join(root_dir, \"outputs\")\n \n sizes = []\n file_names = []\n for f in os.listdir(images_path):\n im = Image.open(os.path.join(images_path, f))\n sizes.append(im.size)\n file_names.append(f)\n \n model = UNet(num_channels=1, num_classes=2)\n use_gpu = use_gpu and torch.cuda.is_available()\n if use_gpu:\n model.cuda()\n model.load_state_dict(torch.load(model_path, map_location='cpu'))\n \n test_dataset = TestDataset(images_path, im_size=[img_size, img_size], transform=tr.ToTensor())\n test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=1)\n print(\"Test Data : \", len(test_loader.dataset))\n start = timer()\n predict(model, test_loader, batch_size, sizes, file_names, masks_path, use_gpu)\n end = timer()\n print(\"Prediction completed in {:0.2f}s\".format(end - start))\n generate_bbox(images_path, masks_path, outputs_path)\n end2 = timer()\n print(\"Bbox generation completed in {:0.2f}s\".format(end2 - end))\n\nif __name__ == '__main__':\n run_pipeline(root_dir='./Data/', model_path='unet-model-binary-dilated-16-100-0.001', img_size=256, batch_size=16, use_gpu=False)\n","sub_path":"prediction-pipeline/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"635370134","text":"import math\r\nimport itertools\r\nfrom tqdm import tqdm\r\n\r\n# Rewrite n^3+pn^2 = k^3 as n^3(1+p/n)=k^3.\r\n# It can be shown that 1+p/n must be a ratio of cubes, or n+p and n are both cubes, or p is a difference of two cubes.\r\n# Writing (n+c)^3-n^3 = 3cn^2+3c^2n+c^3, we see that c must divide p and therefore must be one.\r\n# The problem reduces to checking how many primes we find in the list (n+1)^3-n^3 that are under 1000000\r\n\r\n\r\ndef isPrime(n):\r\n #checks if n is prime\r\n flag = True\r\n if n<2: #1 is a unit, not a prime\r\n flag = False\r\n elif n<4: #2,3 are primes and not 1 mod 6\r\n flag = True\r\n else: #for numbers 4 or more\r\n if n % 2 == 0 or n % 3 ==0: #this eliminates everything not a neighbor of 6\r\n flag = False\r\n else: #only neighbors of 6 left\r\n for i in range(2,int(math.floor(math.sqrt(n)))+1):\r\n if n % i ==0:\r\n flag = False\r\n break\r\n return flag\r\n\r\ngoodPrimes = []\r\n\r\nfor n in range(577):\r\n value = (n+1)**3 - n**3\r\n if isPrime(value):\r\n goodPrimes.append(value)\r\n\r\nprint(len(goodPrimes))\r\n","sub_path":"131.py","file_name":"131.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"132469094","text":"import random\n\nfrom ray.rllib.utils.annotations import override\nfrom ray.rllib.utils.replay_buffers.replay_buffer import ReplayBuffer\nfrom ray.rllib.utils.replay_buffers.utils import warn_replay_buffer_capacity\nfrom ray.rllib.utils.typing import SampleBatchType\n\n\nclass SimpleReplayBuffer(ReplayBuffer):\n \"\"\"Simple replay buffer that operates over entire batches.\"\"\"\n\n def __init__(self, capacity: int, storage_unit: str = \"timesteps\", **kwargs):\n \"\"\"Initialize a SimpleReplayBuffer instance.\"\"\"\n super().__init__(capacity=capacity, storage_unit=\"timesteps\", **kwargs)\n self.replay_batches = []\n self.replay_index = 0\n\n @override(ReplayBuffer)\n def add(self, batch: SampleBatchType, **kwargs) -> None:\n warn_replay_buffer_capacity(item=batch, capacity=self.capacity)\n if self.capacity > 0:\n if len(self.replay_batches) < self.capacity:\n self.replay_batches.append(batch)\n else:\n self.replay_batches[self.replay_index] = batch\n self.replay_index += 1\n self.replay_index %= self.capacity\n\n @override(ReplayBuffer)\n def sample(self, num_items: int, **kwargs) -> SampleBatchType:\n return random.choice(self.replay_batches)\n\n @override(ReplayBuffer)\n def __len__(self):\n return len(self.replay_batches)\n","sub_path":"rllib/utils/replay_buffers/simple_replay_buffer.py","file_name":"simple_replay_buffer.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"296642479","text":"# Задача 3. Енергийни гелове\n# Сезона за изкачване на алпийски върхове започва и всички алпинисти, се запасяват с енергийни гелове за\n# изкачването. Фирма предлага малки и големи разфасовки с по 2 бр. и 5 бр. енергийни гела, като цената на\n# един гел зависи от плодовете, от които е направен. В зависимост от размера на разфасовката, цената за\n# брой енергиен гел е различна. От конзолата се четат плодовете, размерът на опаковката ((малка) 2 бр. или\n# (голяма) 5 бр.), както и колко разфасовки са поръчани. Да се напише програма, която изчислява сумата,\n# която трябва да се плати за поръчката.\n# Диня Манго Ананас Малина\n# 2 броя (small) 56.00 лв./бр. 36.66 лв./бр. 42.10 лв./бр. 20 лв./бр.\n# 5 броя (big) 28.70 лв./бр. 19.60 лв./бр. 24.80 лв./бр. 15.20 лв./бр.\n# При поръчки:\n# • от 400 лв. до 1000 лв. включително има 15% отстъпка\n# • над 1000 лв. има 50% отстъпка\n# Вход\n# От конзолата се четат 3 реда:\n# 1. Плод - текст с възможности: \"Watermelon\", \"Mango\", \"Pineapple\" или \"Raspberry\"\n# 2. Размерът на сета - текст с възможности: \"small\" или \"big\"\n# 3. Брой на поръчаните сетове - цяло число в интервала [1 … 10000]\n# Изход\n# На конзолата се отпечатва 1 ред:\n# • Цената, която трябва да се заплати, форматирана до втория знак след десетичната запетая,\n# в следния формат:\n# \"{цената} lv.\"\n\n# Цената на голям пакет гелове с диня е 5 * 28.70 = 143.50 лв.\n# Цената на 4 сета: 574 лв.\n# 400 <= 574 <= 1000 -> клиентът получава 15% отстъпка\n# 15 % от 574 = 86.1 лв. отстъпка\n# Крайна цена: 574 - 86.1 = 487.9 лв.\n\nprice = 0\ntotal = 0\n\nbooster_type = input()\nbooster_size = input()\nbooster_qty = int(input())\n\n\nif booster_type == \"Watermelon\":\n price = 56 if booster_size == \"small\" else 28.70\n\nif booster_type == \"Mango\":\n price = 36.66 if booster_size == \"small\" else 19.60\n\nif booster_type == \"Pineapple\":\n price = 42.10 if booster_size == \"small\" else 24.80\n\nif booster_type == \"Raspberry\":\n price = 20.00 if booster_size == \"small\" else 15.20\n\nprice *= 2 if booster_size == \"small\" else 5\n\nsub_total = price * booster_qty\n\nif sub_total >= 400 and sub_total <= 1000:\n total = sub_total - (sub_total * 0.15)\nelif sub_total > 1000:\n total = sub_total - (sub_total * 0.5)\nelif sub_total < 400:\n total = sub_total\n\nprint(f\"{total:.2f} lv.\")\n","sub_path":"exams/01 - Programming Basics Online Exam - 28 and 29 March 2020/03-EnergyBooster.py","file_name":"03-EnergyBooster.py","file_ext":"py","file_size_in_byte":3237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"94263947","text":"from pathlib import Path\n\n\ndef parse_data():\n result = {}\n with open(Path(__file__).stem + \".txt\") as fp:\n for line in fp.readlines():\n left, right = line.split(\"->\")\n result[right.strip()] = left.strip()\n return result\n\n\ndef evaluate(variable, lookup):\n if isinstance(variable, int) or variable.isnumeric():\n return int(variable)\n equation = lookup[variable]\n result = None\n if isinstance(equation, int) or equation.isnumeric():\n result = int(equation)\n elif not \" \" in equation:\n result = evaluate(equation, lookup)\n elif equation.startswith(\"NOT\"):\n result = ~evaluate(equation.split()[-1], lookup)\n else:\n left, operator, right = equation.split()\n left = evaluate(left, lookup)\n right = evaluate(right, lookup)\n if operator == \"AND\":\n result = left & right\n elif operator == \"OR\":\n result = left | right\n elif operator == \"LSHIFT\":\n result = left << right\n elif operator == \"RSHIFT\":\n result = left >> right\n lookup[variable] = result\n return result\n\n\ndef main_a(data):\n print(evaluate(\"a\", data))\n\n\ndef main_b(data):\n data[\"b\"] = \"3176\"\n print(evaluate(\"a\", data))\n\n\nif __name__ == \"__main__\":\n data = parse_data()\n print(\"##### Part 1 #####\")\n main_a(data)\n data = parse_data()\n print(\"\\n##### Part 2 #####\")\n main_b(data)\n","sub_path":"2015/a07.py","file_name":"a07.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"22416694","text":"# import importlib\nimport logging\nimport os\nimport pickle\nfrom pathlib import Path\n\n# import numpy as np\nimport numpy as np\nimport pandas as pd\n\nfrom features.f001_suga_yama_features import (EncodingTitles, EventCount,\n EventCount2, GameDurMiss,\n KernelBasics2, PrevAssessAcc,\n PrevAssessAccByTitle,\n PrevAssessResult, SessionTime2,\n Worldcount)\nfrom features.f002_dt_features import dtFeatures\nfrom features.f004_event_code_ratio_features import eventCodeRatioFeatures\nfrom features.f005_event_id_ratio_features import eventIDRatioFeatures\nfrom features.f007_encoding_title_order import encodingTitleOrder\nfrom features.f008_immediately_before_features import immediatelyBeforeFeatures\nfrom features.f009_world_label_encoding_diff import \\\n worldLabelEncodingDiffFeatures\nfrom features.f010_world_numerical_features import worldNumeriacalFeatures\nfrom features.f011_world_assessment_numerical_features import \\\n worldAssessmentNumeriacalFeatures\nfrom features.f012_world_activity_numerical_features import \\\n worldActivityNumeriacalFeatures\nfrom features.f013_world_game_numerical_features import \\\n worldGameNumeriacalFeatures\nfrom features.f014_world_event_data_features1 import worldEventDataFeatures1\nfrom features.f015_world_assessment_numerical_features_revised import \\\n worldNumeriacalFeatures2\nfrom features.f016_current_session_info import currentSessionInfo\nfrom features.f017_same_world_base_features import sameWorldBaseFeatures\nfrom features.f018_world_event_data_features_rolling_5 import \\\n worldEventDataFeaturesRolling5\n# from features.f999_suga_yama_features_fixed import KernelBasics3\nfrom features.f100_suga_yama_features_fixed import KernelBasics3\n# from guchio_utils import guchioValidation\nfrom yamakawa_san_utils import (OptimizedRounder, Validation, base_path,\n log_output, memory_reducer, pickle_load, qwk,\n timer)\n\n# set configs\nEXP_ID = os.path.basename(__file__).split('_')[0]\n\n# CONFIG_MODULE = f'configs.{EXP_ID}_config'\n# CONFIG_DICT = importlib.import_module(CONFIG_MODULE).CONFIG_DICT\n\n\nexp_name = EXP_ID\nlogger, log_path = log_output(exp_name)\n\ntrain_small_dataset = False\nis_debug = False\nis_local = False\n\n\ndef feature_maker(feat_cls, is_overwrite, org_train, org_test,\n train_labels, params, logger, is_local):\n feat_ = feat_cls(train_labels, params, logger)\n feat_name = feat_.name\n datatype = feat_.datatype\n feature_dir = './mnt/inputs/features'\n # feature_dir = os.path.join(os.path.dirname(\"__file__\"), \"../feature\")\n feature_path = Path(feature_dir) / f\"{datatype}\" / f\"{feat_name}.pkl\"\n\n print(f'feature_path: {feature_path}')\n print(f'os.path.exists(feature_path): {os.path.exists(feature_path)}')\n print(f'is_overwrite: {is_overwrite}')\n if os.path.exists(feature_path) and is_overwrite is False:\n f_df = pickle_load(feature_path)\n else:\n f_df = feat_.feature_extract(org_train, org_test)\n\n return f_df\n\n\ndef add_features(use_features, org_train, org_test, train_labels,\n specs, datatype, is_local=False, logger=None):\n feat_params = {\n \"datatype\": datatype,\n \"debug\": True,\n \"is_overwrite\": True,\n }\n\n # base feature\n base_feat = KernelBasics3(train_labels, feat_params, logger)\n feature_dir = './mnt/inputs/features'\n # feature_dir = os.path.join(os.path.dirname(\"__file__\"), \"../feature\")\n feature_path = Path(feature_dir) / f\"{datatype}\" / f\"{base_feat.name}.pkl\"\n\n if os.path.exists(feature_path):\n feat_df = pickle_load(feature_path)\n else:\n feat_df = base_feat.feature_extract(org_train, org_test)\n\n # add event_counts\n for name, feat_condition in use_features.items():\n feat_cls = feat_condition[0]\n is_overwrite = feat_condition[1]\n\n f_df = feature_maker(\n feat_cls,\n is_overwrite,\n org_train,\n org_test,\n train_labels,\n feat_params,\n logger,\n is_local)\n feat_df = pd.merge(\n feat_df, f_df, how=\"left\", on=[\n \"installation_id\", \"game_session\"])\n del f_df\n\n return feat_df\n\n\ndef preprocess_dfs(use_features, is_local=False, logger=None, debug=True):\n # read dataframes\n with timer(\"read datasets\"):\n if debug:\n nrows = 200000\n else:\n nrows = None\n\n sub = pd.read_csv(base_path + '/sample_submission.csv')\n\n if is_local:\n org_train = pickle_load(\"../input/train.pkl\")\n org_test = pickle_load(\"../input/test.pkl\")\n else:\n org_train = pd.read_csv(base_path + \"/train.csv\", nrows=nrows)\n org_test = pd.read_csv(base_path + \"/test.csv\", nrows=nrows)\n\n org_train = memory_reducer(org_train, verbose=True)\n org_test = org_test[org_test.installation_id.isin(sub.installation_id)]\n org_test.sort_values(['installation_id', 'timestamp'], inplace=True)\n org_test.reset_index(inplace=True)\n org_test = memory_reducer(org_test, verbose=True)\n\n train_labels = pd.read_csv(\n base_path + \"/train_labels.csv\", nrows=nrows)\n specs = pd.read_csv(base_path + \"/specs.csv\", nrows=nrows)\n\n # basic preprocess\n org_train[\"timestamp\"] = pd.to_datetime(org_train[\"timestamp\"])\n org_test[\"timestamp\"] = pd.to_datetime(org_test[\"timestamp\"])\n\n with timer(\"merging features\"):\n train_df = add_features(\n use_features,\n org_train,\n org_test,\n train_labels,\n specs,\n datatype=\"train\",\n is_local=is_local,\n logger=None)\n train_df = train_df.reset_index(drop=True)\n test_df = add_features(\n use_features,\n org_train,\n org_test,\n train_labels,\n specs,\n datatype=\"test\",\n is_local=is_local,\n logger=None)\n test_df = test_df.reset_index(drop=True)\n\n# df = pd.concat([df, feat_df], axis=1)\n print(\"preprocess done!!\")\n\n return train_df, test_df\n\n\ndef main():\n # train_df = pd.read_pickle('./mnt/inputs/origin/train.pkl.gz')\n # test_df = pd.read_csv('./mnt/inputs/origin/test.csv')\n\n # ==============================\n # start processing\n # ==============================\n use_feature = {\n \"EventCount\": [EventCount, False], # class, is_overwrite\n # \"EventCount2\": [EventCount2, False], # class, is_overwrite\n # \"Worldcount\": [Worldcount, False],\n # \"SessionTime\": [SessionTime2, False],\n # \"AssessEventCount\": [AssessEventCount, False],\n \"EncodingTitles\": [EncodingTitles, False],\n # \"encodingTitleOrder\": [encodingTitleOrder, False],\n # \"PrevAssessResult\": [PrevAssessResult, False],\n # \"PrevAssessAcc\": [PrevAssessAcc, True],\n # \"PrevAssessAccByTitle\": [PrevAssessAccByTitle, False],\n # \"GameDurMiss\": [GameDurMiss, False],\n # \"dtFeatures\": [dtFeatures, False],\n # \"eventCodeRatioFeatures\": [eventCodeRatioFeatures, False],\n # \"eventIDRatioFeatures\": [eventIDRatioFeatures, False],\n # \"immediatelyBeforeFeatures\": [immediatelyBeforeFeatures, False],\n # \"worldLabelEncodingDiffFeatures\": [worldLabelEncodingDiffFeatures, False],\n # \"worldNumeriacalFeatures\": [worldNumeriacalFeatures, False],\n # \"worldAssessmentNumeriacalFeatures\": [worldAssessmentNumeriacalFeatures, False],\n # \"worldActivityNumeriacalFeatures\": [worldActivityNumeriacalFeatures, False],\n # \"worldGameNumeriacalFeatures\": [worldGameNumeriacalFeatures, False],\n # \"worldEventDataFeatures1\": [worldEventDataFeatures1, False], # to debug! killer features!\n # \"worldEventDataFeaturesRolling5\": [worldEventDataFeaturesRolling5, False],\n # \"worldNumeriacalFeatures2\": [worldNumeriacalFeatures2, False],\n # \"currentSessionInfo\": [currentSessionInfo, False],\n # \"sameWorldBaseFeatures\": [sameWorldBaseFeatures, False],\n }\n\n is_local = False\n\n if is_local:\n base_path = \"../input\" # at local\n train_df, test_df = preprocess_dfs(\n use_feature, is_local=is_local, logger=None, debug=False)\n\n else:\n base_path = './mnt/inputs/origin' # at kaggle kernel\n sub = pd.read_csv(\n f'{base_path}/sample_submission.csv')\n# base_path = '/kaggle/input/data-science-bowl-2019' # at kaggle kernel\n# if len(sub) == 1000:\n if False:\n sub.to_csv('submission.csv', index=False)\n exit(0)\n else:\n train_df, test_df = preprocess_dfs(\n use_feature, is_local=is_local, logger=None, debug=is_debug)\n\n # remove , to avoid error of lgbm\n train_df.columns = [col.replace(',', '_') for col in train_df.columns]\n test_df.columns = [col.replace(',', '_') for col in test_df.columns]\n\n # concat for adv\n train_df['is_train'] = 1\n test_df['is_train'] = 0\n train_df = pd.concat([train_df, test_df], axis=0).reset_index(drop=True)\n\n # train_params = {\n # 'learning_rate': 0.01,\n # 'bagging_fraction': 0.90,\n # 'feature_fraction': 0.85,\n # 'max_depth': 5,\n # 'lambda_l1': 0.7,\n # 'lambda_l2': 0.7,\n # 'metric': 'multiclass',\n # 'objective': 'multiclass',\n # 'num_classes': 4,\n # 'random_state': 773,\n # \"n_estimators\": 3000\n\n # }\n\n train_params = {\n 'learning_rate': 0.01,\n 'boosting_type': 'gbdt',\n 'objective': 'binary',\n # 'objective': 'regression',\n 'metric': 'auc',\n # 'metric': 'rmse',\n 'num_leaves': 64,\n # 'num_leaves': 16,\n 'bagging_fraction': 0.9,\n 'bagging_freq': 1,\n 'feature_fraction': 0.7,\n 'max_depth': -1,\n 'lambda_l1': 0.2,\n 'lambda_l2': 0.4,\n # 'lambda_l1': 1,\n # 'lambda_l2': 1,\n 'seed': 19930802,\n 'n_estimators': 100000,\n 'importance_type': 'gain',\n }\n\n bad_feats = [\n 'prev_gs_duration',\n 'session_intervalrmin',\n 'session_intervalrstd',\n 'session_intervalrmax',\n 'session_interval',\n 'accum_acc_gr_-99',\n 'session_intervalrmean',\n 'ass_session_interval',\n 'prev_gs_durationrmean',\n 'prev_gs_durationrmax',\n 'ev_cnt4070',\n 'prev_gs_durationrstd',\n 'mean_g_duration_meaan',\n 'ev_cnt3010',\n 'g_duration_std',\n 'ev_cnt4030',\n 'ev_cnt3110',\n 'g_duration_mean',\n 'meaan_g_duration_min',\n 'ass_session_interval_rmin',\n 'accum_acc_gr_3',\n 'g_duration_min',\n 'mean_g_duraation_std',\n# 'prev_acc_gr_0',\n# 'prev_acc_gr_1',\n# 'prev_acc_gr_2',\n# 'prev_acc_gr_3',\n# 'accum_acc_gr_0',\n# 'accum_acc_gr_1',\n# 'accum_acc_gr_2',\n# 'accum_acc_gr_3',\n ]\n\n no_use_cols = [\n \"accuracy\",\n \"accuracy_group\",\n \"game_session\",\n \"installation_id\",\n \"title\",\n \"type\",\n \"world\",\n \"pred_y\",\n \"is_train\",\n ] + list(set(train_df.columns) - set(test_df.columns)) + bad_feats\n\n train_cols = [c for c in list(train_df.columns) if c not in no_use_cols]\n\n print(f\"train_df shape: {train_df.shape}\")\n # print(train_cols)\n logger.log(logging.DEBUG, f'---------------------------------------------')\n logger.log(logging.DEBUG, f'train_df.columns : {train_df.columns.tolist()}')\n logger.log(logging.DEBUG, f'---------------------------------------------')\n logger.log(logging.DEBUG, f'no_use_cols : {no_use_cols}')\n\n cat_cols = [\n ]\n\n # logger.log(logging.DEBUG, f\"categorical cols: {cat_cols}\")\n\n target = \"is_train\"\n # target = \"accuracy_group\"\n # target = \"accuracy\"\n\n model_conf = {\n \"predict_type\": \"regressor\",\n \"train_params\": train_params,\n \"train_cols\": train_cols,\n \"cat_cols\": cat_cols,\n \"target\": target,\n \"is_debug\": is_debug,\n }\n\n validation_param = {\n \"model_name\": \"LGBM\",\n }\n\n exp_conf = {\n \"train_small_dataset\": False,\n \"use_feature\": {\n \"sample\": True\n },\n \"train_params\": train_params,\n \"exp_name\": exp_name\n }\n\n # train_df[target] = train_df[target] / 3.\n # train_df.loc[train_df[target] <= 1, target] = 0\n # train_df.loc[train_df[target] > 1, target] = 1\n # print(train_df[target].head())\n v = Validation(validation_param, exp_conf, train_df, test_df, logger)\n clf, oof, prediction, feature_importance_df \\\n = v.do_valid_kfold(model_conf)\n\n optR = OptimizedRounder()\n # optR.fit(oof, train_df['accuracy_group'], [[1.0, 1.5, 2.9]])\n optR.fit(oof, train_df['accuracy_group'], [[1.0, 1.5, 2.0]])\n coefficients = optR.coefficients()\n\n opt_preds = optR.predict(oof, coefficients)\n\n oof_dir = f'./mnt/oofs/{EXP_ID}'\n if not os.path.exists(oof_dir):\n os.mkdir(oof_dir)\n with open(f'{oof_dir}/{EXP_ID}_oof.pkl', 'wb') as fout:\n pickle.dump(oof, fout)\n\n res_qwk = qwk(train_df['accuracy_group'], opt_preds)\n print(f'res_qwk : {res_qwk}')\n logger.log(\n logging.DEBUG,\n f'qwk -- {res_qwk}'\n )\n\n# print(f'qwk -- {np.mean(valid_qwks)} +- {np.std(valid_qwks)}')\n# logger.log(\n# logging.DEBUG,\n# f'qwk -- {np.mean(valid_qwks)} +- {np.std(valid_qwks)}')\n\n # save info\n feature_importance_df.to_csv(\n f'./mnt/importances/{EXP_ID}.csv', index=False)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/e025_adversarial_validation.py","file_name":"e025_adversarial_validation.py","file_ext":"py","file_size_in_byte":13875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"401503330","text":"import hashlib\nimport os\nimport sys\nsys.path.append(\"./tests\")\nimport segemehl_data as sd\n\n\ndef create_tmp_fasta_file(fasta_file_path, content):\n fasta_fh = open(fasta_file_path, \"w\")\n fasta_fh.write(content)\n fasta_fh.close()\n\n\ndef sha1_of_file(file_path):\n fh = open(file_path, \"rb\")\n content = fh.read()\n fh.close()\n return hashlib.sha1(content).hexdigest()\n\n\ndef setup_function(function):\n sd.data_segemehl()\n create_tmp_fasta_file(sd.fasta_file_path, sd.genome_fasta_upper)\n sd.segemehl.build_index([sd.fasta_file_path], sd.index_file_path)\n\n\ndef teardown_function(function):\n for file_path in [sd.fasta_file_path, sd.index_file_path]:\n if os.path.exists(file_path):\n os.remove(file_path)\n\n\n# Test segemehl index building\ndef test_build_index_lower_letters():\n create_tmp_fasta_file(sd.fasta_file_path, sd.genome_fasta_lower)\n sd.segemehl.build_index([sd.fasta_file_path], sd.index_file_path)\n assert sha1_of_file(\n sd.index_file_path) == \"78668505720e53735f807bb5485b0b38cc3cbc22\"\n\n \ndef test_build_index_upper_letters():\n # create_tmp_fasta_file(sd.fasta_file_path, sd.genome_fasta_upper)\n sd.segemehl.build_index([sd.fasta_file_path], sd.index_file_path)\n assert sha1_of_file(\n sd.index_file_path) == \"78668505720e53735f807bb5485b0b38cc3cbc22\"\n\n\n# Test segemehl aligning\ndef test_align_reads_single_read_perfect_match():\n \"\"\"\n ACAACATCCATGAACCGCATCAGCACCACCACCATTACCACCATCACCATTACCACAGGT\n ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\n ACAACATCCATGAACCGCATCAGCACCACCACCATTACCACCATCACCATTACCACAGGT\n \"\"\"\n read_file_content = (\n \">read_01\\n\" +\n \"ACAACATCCATGAACCGCATCAGCACCACCACCATTACCACCATCACCATTACCACAGGT\"\n + \"\\n\")\n assert align_reads_and_give_result(\n read_file_content) == sd.sam_result_aligned_1\n\n\ndef test_map_reads_single_read_not_matching():\n \"\"\"\n ACAACATCCATGAACCGCATCAGCACCACCACCATTACCACCATCACCATTACCACAGGT\n | | ||| || | | || | ||\n ATGTACCACATGAGAGAGATAGAGAGAGATTGACAACCACACACGAGAGAGAGAGAGAGT\n \"\"\"\n read_file_content = (\n \">read_02\\n\" +\n \"ATGTACCACATGAGAGAGATAGAGAGAGATTGACAACCACACACGAGAGAGAGAGAGAGT\"\n + \"\\n\")\n assert align_reads_and_give_result(\n read_file_content) == sd.sam_result_no_aligned\n\n\ndef test_map_reads_single_read_one_mismatch():\n \"\"\"A 20 nt long read with 1 mismatch at 95% accu should be\n mapped.\n GCTTTTTTTTCGACCAGAGA\n |||||||||||||||||| |\n GCTTTTTTTTCGACCAGACA\n \"\"\"\n read_file_content = (\n \">read_03\\nGCTTTTTTTTCGACCAGACA\\n\")\n assert align_reads_and_give_result(\n read_file_content) == sd.sam_result_aligned_2\n\n\ndef test_map_reads_single_read_two_mismatches_95():\n \"\"\"A 20 nt long read with 2 mismatches at 95% accuracy should\n not be mapped.\n GCTTTTTTTTCGACCAGAGA\n ||||||||||||||||| |\n GCTTTTTTTTCGACCAGTCA\n \"\"\"\n read_file_content = (\n \">read_04\\nGCTTTTTTTTCGACCAGTCA\\n\")\n assert align_reads_and_give_result(\n read_file_content) == sd.sam_result_no_aligned\n\n\ndef test_map_reads_single_read_two_mismatches_90():\n \"\"\"A 20 nt long read with 2 mismatches at 90% accuracy should\n be mapped.\n GCTTTTTTTTCGACCAGAGA\n ||||||||||||||||| |\n GCTTTTTTTTCGACCAGTCA\n \"\"\"\n read_file_content = (\n \">read_05\\nGCTTTTTTTTCGACCAGTCA\\n\")\n assert align_reads_and_give_result(\n read_file_content, accuracy=90) == sd.sam_result_aligned_3\n\n\ndef test_map_reads_single_read_three_mismatches():\n \"\"\"A 20 nt long read with 3 mismatches at 90% accuracy should\n not be mapped.\n GCTTTTTTTTCGACCAGAGA\n ||||| ||||||||||| |\n GCTTTATTTTCGACCAGTCA\n \"\"\"\n read_file_content = (\n \">read_06\\nGCTTTTTTTTCGACCAGTCA\\n\")\n assert align_reads_and_give_result(\n read_file_content) == sd.sam_result_no_aligned\n\n\ndef test_map_reads_single_too_short_read():\n \"\"\"Reads that are too short should be mapped\n \"\"\"\n read_file_content = (\n \">read_07\\nGCTTTTTTT\\n\")\n assert align_reads_and_give_result(\n read_file_content) == sd.sam_result_no_aligned\n\n\ndef align_reads_and_give_result(read_file_content, **kwargs):\n \"\"\"\n - read_file_content: the content of a read file (in fasta format)\n - **kwargs: are directly given to map_reads()\n \"\"\"\n create_tmp_fasta_file(\n sd.read_fasta_file_path, read_file_content)\n sd.segemehl.run_alignment(sd.read_fasta_file_path, sd.index_file_path,\n [sd.fasta_file_path], sd.aligning_result_path,\n sd.unmapped_reads_path, **kwargs)\n result_fh = open(sd.aligning_result_path)\n result = result_fh.read()\n result_fh.close()\n if '--silent' in result:\n map_spec, reads = result.split(\"--silent\", 1)\n return reads\n \n","sub_path":"tests/test_segemehl.py","file_name":"test_segemehl.py","file_ext":"py","file_size_in_byte":4841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"237591201","text":"import json\nimport requests\nfrom app import current_app\nfrom flask_babel import _\n\n\ndef translate(text, source_language, dest_language):\n if 'MS_TRANSLATOR_KEY' not in current_app.load_json or \\\n not current_app.load_json['MS_TRANSLATOR_KEY']:\n return _('Error: the translation service is not configured')\n auth = {'Ocp-Apim-Subscription-Key': current_app.load_json['MS_TRANSLATOR_KEY']}\n request = requests.get('https://api.microsofttranslator.com/v2/Ajax.svc''/Translate?text={}&from={}&to={}'.format(text, source_language, dest_language),\n headers=auth)\n if request.status_code != 200:\n return _('Error: the translation service failed.')\n return json.loads(request.content.decode('utf-8-sig'))\n","sub_path":"app/translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"216265866","text":"#!/usr/bin/env python\n# coding=utf-8\nimport geojson\nimport logging\nfrom datetime import datetime, date\nfrom numbers import Real\n\nimport numpy as np\n\nN = Real\nL = logging.getLogger(__name__) # noqa\n\n\ndef isfixedlength(lst, length):\n if not isinstance(lst, (list, tuple)):\n raise ValueError('Required: list/tuple, Got: {}'.format(type(lst)))\n\n if len(lst) != length:\n raise ValueError(\n 'Incorrect list/tuple length for {}. Required: {}, Got: {}'.format(\n lst,\n length,\n len(lst)\n )\n )\n\n return True\n\n\ndef isnan(v):\n return (\n v is None or\n v is np.nan or\n v is np.ma.masked\n )\n\n\ndef check_timestamps(times, max_time_interval = None):\n \"\"\"Sanity checks for timestamp arrays\n\n Checks that the times supplied are in monotonically increasing\n chronological order, and optionally that time intervals between\n measurements do not exceed a value `max_time_interval`. Note that this is\n not a QARTOD test, but rather a utility test to make sure times are in the\n proper order and optionally do not have large gaps prior to processing the\n data.\n\n Args:\n times: Input array of timestamps\n max_time_interval: The interval between values should not exceed this\n value. [optional]\n \"\"\"\n\n time_diff = np.diff(times)\n sort_diff = np.diff(sorted(times))\n # Check if there are differences between sorted and unsorted, and then\n # see if if there are any duplicate times. Then check that none of the\n # diffs exceeds the sorted time.\n zero = np.array(0, dtype=time_diff.dtype)\n if not np.array_equal(time_diff, sort_diff) or np.any(sort_diff == zero):\n return False\n elif (max_time_interval is not None and\n np.any(sort_diff > max_time_interval)):\n return False\n else:\n return True\n\n\ndef dict_update(d, u):\n # http://stackoverflow.com/a/3233356\n from collections import Mapping\n for k, v in u.items():\n if isinstance(d, Mapping):\n if isinstance(v, Mapping):\n r = dict_update(d.get(k, {}), v)\n d[k] = r\n else:\n d[k] = u[k]\n else:\n d = {k: u[k] }\n return d\n\n\ndef cf_safe_name(name):\n import re\n if isinstance(name, str):\n if re.match('^[0-9_]', name):\n # Add a letter to the front\n name = \"v_{}\".format(name)\n return re.sub(r'[^_a-zA-Z0-9]', \"_\", name)\n\n raise ValueError('Could not convert \"{}\" to a safe name'.format(name))\n\n\nclass GeoNumpyDateEncoder(geojson.GeoJSONEncoder):\n\n def default(self, obj):\n \"\"\"If input object is an ndarray it will be converted into a list\n \"\"\"\n if isinstance(obj, np.ndarray):\n return obj.tolist()\n elif isinstance(obj, np.generic):\n return obj.item()\n # elif isinstance(obj, pd.Timestamp):\n # return obj.to_pydatetime().isoformat()\n elif isinstance(obj, (datetime, date)):\n return obj.isoformat()\n elif np.isnan(obj):\n return None\n\n return geojson.factory.GeoJSON.to_instance(obj)\n","sub_path":"ioos_qc/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"114743618","text":"\ndef prepare_search(inputtext, language):\n\timport spacy #code: pip install spacy\n\ttry:\n\t\timport languageload\n\texcept ImportError:\n\t\tfrom learny import languageload\n\n\t# variables and lists used\n\tnoun_list = [] # list of nouns that will be part of the cloze\n\n\tnlp = languageload.language_load(language)\n\tdocnlp = nlp(inputtext) #load to spacy\n\n\tfor token in docnlp:\n\t\tif 'NOUN' in token.pos_:\n\t\t\tnoun_list.append(str(token.lemma_))# complete list of nouns\n\treturn noun_list\n\ndef get_categories(searchquery=\"\", resultDict={}):\n\t\n\timport wptools\n\t#https://github.com/siznax/wptools/wiki/Examples#get-a-representative-image\n\timport requests\n\timport os\n\n\t#https://github.com/siznax/wptools/wiki/Examples#get-wikidata\n\tpage = wptools.page(searchquery, lang=\"de\")\n\tnumber = page.get_wikidata()\n\tgivenid = page.data['wikibase']\n\tprint(\"id:\", givenid)\n\n\n\t#https://towardsdatascience.com/where-do-mayors-come-from-querying-wikidata-with-python-and-sparql-91f3c0af22e2\n\turl = 'https://query.wikidata.org/sparql'\n\tquery = f\"\"\"\n\tSELECT ?item ?itemLabel\n\tWHERE\n\t{{\n\t wd:{givenid} wdt:P279/wdt:P31* ?item.\n\t SERVICE wikibase:label {{ bd:serviceParam wikibase:language \"[AUTO_LANGUAGE],de\". }}\n\t}}\n\n\t\"\"\"\n\tfile_path = os.path.join(os.path.expanduser('~'),'learny', 'learny', 'learny', 'b1.txt')\n\n\twith open(file_path) as f:\n\t grundwortschatz = f.readlines()\n\tresultDict[searchquery] = []\n\tgrundwortschatz = \" \".join(grundwortschatz)\n\t#https://www.datacamp.com/community/tutorials/f-string-formatting-in-python\n\tr = requests.get(url, params = {'format': 'json', 'query': query})\n\tdata = r.json()\n\tfor i in range(len(data[\"results\"][\"bindings\"])):\n\t\tvalue = data[\"results\"][\"bindings\"][i][\"itemLabel\"][\"value\"]\n\t\t\"\"\"\n\t\tif \"Meta\" in value or value == \"\":\n\t\t\tprint(\"something with meta\")\n\t\telse:\n\t\t\tprint(\"data: \", value)\n\t\t\tresultDict[searchquery].append(value)\n\t\t\tprint(resultDict)\n\t\t\"\"\"\n\t\tvalue.strip(\" \")\n\t\tif value in grundwortschatz and value != \"\":\n\t\t\tprint(\"data: \", value)\n\t\t\tresultDict[searchquery].append(value)\n\t\t\tprint(resultDict)\n\t\telse:\n\t\t\tprint(value, \"not in grundwortschatz\")\n\t\t\tvaluelist = value.split(\" \")\n\t\t\twordexists = False\n\t\t\tfor word in valuelist:\n\t\t\t\tif word in grundwortschatz and word != \"\":\n\t\t\t\t\tprint(word, \"exists\")\n\t\t\t\t\twordexists = True\n\t\t\t\telse:\n\t\t\t\t\twordexists = False\n\t\t\t\t\tprint(word, \"doesn't exist\")\n\t\t\t\t\tbreak\n\t\t\tif wordexists == True:\n\t\t\t\tresultDict[searchquery].append(value)\n\t\t\t\tprint(resultDict)\n\n\n\n\n\treturn resultDict\n\ninput= \"\"\"\n\nPascal sitzt im Bus in der zweitletzten Reihe .\n Ein großer Junge mit einer Wasserflasche\n setzt sich hinter ihn , nimmt einen Schluck\n Wasser aus der Flasche und spuckt es ihm auf\n den Kopf . Haare und Klamotten sind nass .\n\n Der 14-jährige Kevin sitzt im Rollstuhl . Jeden\n Morgen wartet er auf das Taxi und wird von\n einigen Jugendlichen gemobbt . Sie stellen sich\n in den Weg , sodass er auf dem Bürgersteig\n nicht mehr weiter kann . „ Hast du ein Problem ? ” ,\n fragt ihn einer . Die anderen lachen .\n\n\"\"\"\n\nlist = prepare_search(input, language=\"\")\nprint(list)\n\nfor word in list:\n\ttry:\n\t\t\tresultDict = get_categories(word)\n\texcept:\n\t\t\tprint(f\"Error!! Couldn't get result category searching with: {word}\")\n\t\t\tcontinue\n#get_categories(\"Ritter\")\nfor key in resultDict:\n\tif resultDict[key] != []:\n\t\tprint(key,\": \")\n\t\tprint(\", \".join(resultDict[key]))\n","sub_path":"learny/getcategories.py","file_name":"getcategories.py","file_ext":"py","file_size_in_byte":3317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"621604811","text":"from ortools.linear_solver import pywraplp\n\n\ndef create_data_model():\n \"\"\"Create the data for the example.\"\"\"\n data = {}\n weights = [48, 30, 42, 36, 36, 42, 42, 36, 24, 30, 30, 36, 36,98,90,10]\n values = [10, 30, 25, 50, 35, 15, 40, 30, 35, 45, 10, 30, 25,40,45,30]\n data['weights'] = weights\n data['values'] = values\n data['items'] = list(range(len(weights)))\n data['num_items'] = len(weights)\n num_bins = 125\n data['bins'] = list(range(num_bins))\n data['bin_capacities'] = [100 for i in range(126)] #[A0-C0-R0,A0-C0-R1...]\n return data\n\n\n\ndef main():\n data = create_data_model()\n\n nbin=[]\n for a in range(1,6):\n for c in range(1,6):\n for r in range(1,6):\n s=''\n s+='A'+str(a)+'-C'+str(c)+'-R'+str(r)\n nbin.append(s)\n #print(data['bin_capacities'])\n\n ll=list(zip(data['bin_capacities'],nbin))\n #print(ll)\n\n # Create the mip solver with the SCIP backend.\n solver = pywraplp.Solver.CreateSolver('SCIP')\n print(\"nbin\",nbin)\n\n # Variables\n # x[i, j] = 1 if item i is packed in bin j.\n x = {}\n for i in data['items']:\n for j in data['bins']:\n x[(i, j)] = solver.IntVar(0, 1, 'x_%i_%i' % (i, j))\n\n # Constraints\n # Each item can be in at most one bin.\n for i in data['items']:\n solver.Add(sum(x[i, j] for j in data['bins']) <= 1)\n # The amount packed in each bin cannot exceed its capacity.\n for j in data['bins']:\n solver.Add(\n sum(x[(i, j)] * data['weights'][i]\n for i in data['items']) <= data['bin_capacities'][j])\n\n # Objective\n objective = solver.Objective()\n\n for i in data['items']:\n for j in data['bins']:\n objective.SetCoefficient(x[(i, j)], data['values'][i])\n objective.SetMaximization()\n\n status = solver.Solve()\n\n if status == pywraplp.Solver.OPTIMAL:\n df={}\n #print('Total packed value:', objective.Value())\n total_weight = 0\n for j in data['bins']:\n subd={}\n bin_weight = 0\n bin_value = 0\n subd['bin']=nbin[j]\n #print('Bin ', nbin[j], '\\n')\n t=[]\n for i in data['items']: \n if x[i, j].solution_value() > 0:\n t.append(i)\n #print('Item', i, '- weight:', data['weights'][i], ' value:',data['values'][i])\n bin_weight += data['weights'][i]\n bin_value += data['values'][i]\n subd['items']=t\n subd['packed wt']=bin_weight\n subd['packed val']=bin_value\n #print('Packed bin weight:', bin_weight)\n #print('Packed bin value:', bin_value)\n #print()\n total_weight += bin_weight\n if(bin_weight!=0):\n df[j+1]=subd\n #print('Total packed weight:', total_weight)\n df[0]=[int(objective.Value()),total_weight]\n print(\"==================================================================\",df) \n else:\n print('The problem does not have an optimal solution.')\n \nif __name__ == '__main__':\n main()\n","sub_path":"calc/tp3.py","file_name":"tp3.py","file_ext":"py","file_size_in_byte":3178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"445952204","text":"def readInputTextFile(filename):\n \"\"\"Read input file(filename) and return list of int\n\n Arguments:\n filename {[string]} -- [name of input file]\n\n Returns:\n [list of int] -- [input list]\n \"\"\"\n with open(filename, 'r') as f:\n line = f.read()\n str_int_list = line.split()\n int_list = []\n for i in str_int_list:\n int_list.append(int(i))\n return int_list\n","sub_path":"exercise/readInputTextFile.py","file_name":"readInputTextFile.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"534815851","text":"import sys\n\nimport numpy as np\nimport torch\nfrom PIL import Image\n\nfrom _model_base import ModelBase, handle_alpha\n\nyuv_from_rgb_mat = np.array([\n [0.299, 0.587, 0.114],\n [-0.14714119, -0.28886916, 0.43601035],\n [0.61497538, -0.51496512, -0.10001026]\n])\n\n\ndef yuv2rgb(yuv):\n rgb_from_yuv = np.linalg.inv(yuv_from_rgb_mat)\n return np.dot(yuv, rgb_from_yuv.T.copy())\n\n\ndef to_grayscale(rgb):\n return np.dot(rgb, yuv_from_rgb_mat[0, None].T)\n\n\nclass NeuralColorization(ModelBase):\n def __init__(self):\n super().__init__()\n self.hub_repo = 'valgur/neural-colorization:pytorch'\n\n def load_model(self):\n G = torch.hub.load(self.hub_repo, 'generator',\n pretrained=True, map_location=self.device)\n G.to(self.device)\n return G\n\n @handle_alpha\n @torch.no_grad()\n def predict(self, img):\n h, w, d = img.shape\n if d == 3:\n img = to_grayscale(img)\n\n G = self.model\n\n input_image = img[..., 0]\n H, W = input_image.shape\n infimg = input_image[None, None, ...].astype(np.float32) / 255.\n img_variable = torch.from_numpy(infimg) - 0.5\n img_variable = img_variable.to(self.device)\n res = G(img_variable)\n uv = res.cpu().numpy()[0]\n uv[0, :, :] *= 0.436\n uv[1, :, :] *= 0.615\n u = np.array(Image.fromarray(uv[0]).resize((W, H), Image.BILINEAR))[None, ...]\n v = np.array(Image.fromarray(uv[1]).resize((W, H), Image.BILINEAR))[None, ...]\n yuv = np.concatenate([infimg[0], u, v], axis=0).transpose(1, 2, 0)\n\n rgb = yuv2rgb(yuv * 255)\n rgb = rgb.clip(0, 255).astype(np.uint8)\n return rgb\n\n\nmodel = NeuralColorization()\n\nif __name__ == '__main__':\n rpc_url = sys.argv[1]\n model.process_rpc(rpc_url)\n","sub_path":"models/NeuralColorization.py","file_name":"NeuralColorization.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"577711896","text":"from twisted.trial.unittest import TestCase\nfrom mocks import MockProcessInductor\n\nstdout, stderr = 1, 2\nfauxProcessData = [(stdout, 'some output'),\n (stderr, 'error message'),\n (stdout, 'info message'),\n (stderr, 'os failure')]\n\n\nclass InductorTest(TestCase):\n def test_run(self):\n inductor = MockProcessInductor(None, fauxProcessData)\n result = inductor.run(command='foo')\n @result.addCallback\n def check_result(result):\n expected_stdout = ''.join([data for fd, data in fauxProcessData\n if fd is stdout])\n expected_stderr = ''.join([data for fd, data in fauxProcessData\n if fd is stderr])\n expected_result = (expected_stdout, expected_stderr, 0)\n self.assertEqual(result, expected_result)\n return result\n\n def test_getOutput(self):\n inductor = MockProcessInductor(None, fauxProcessData)\n output = inductor.getOutput(command='foo')\n @output.addCallback\n def check_output(result):\n expected_stdout = ''.join([data for fd, data in fauxProcessData\n if fd is stdout])\n self.assertEqual(result, expected_stdout)\n return output\n\n def test_getExitCode(self):\n expectedExitCode = 47\n inductor = MockProcessInductor(None, fauxProcessData, exitCode=expectedExitCode)\n output = inductor.getExitCode(command='foo')\n @output.addCallback\n def checkExitCode(exitCode):\n self.assertEqual(exitCode, expectedExitCode)\n return output\n","sub_path":"test/unit/test_inductor.py","file_name":"test_inductor.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"515291879","text":"# ----------------------------------------------------------------------------\n# Copyright (c) 2017 Massachusetts Institute of Technology (MIT)\n# All rights reserved.\n#\n# Distributed under the terms of the BSD 3-clause license.\n#\n# The full license is in the LICENSE file, distributed with this software.\n# ----------------------------------------------------------------------------\n\"\"\"Utility functions for Digital RF and Digital Metadata.\"\"\"\nimport ast\nimport datetime\n\nimport dateutil.parser\nimport numpy as np\nimport pytz\nimport six\n\n__all__ = ('parse_sample_identifier',)\n\n\ndef parse_sample_identifier(iden, samples_per_second=None, ref_index=None):\n \"\"\"Get a sample index from different forms of identifiers.\n\n Parameters\n ----------\n\n iden : None | int/long | float | string\n If None or '', None is returned to indicate that the index should\n be automatically determined.\n If an integer, it is returned as the sample index.\n If a float, it is interpreted as a timestamp (seconds since epoch)\n and the corresponding sample index is returned.\n If a string, three forms are permitted:\n 1) a string which can be evaluated to an integer/float and\n interpreted as above,\n 2) a string beginning with '+' and followed by an integer\n (float) expression, interpreted as samples (seconds) from\n `ref_index`, and\n 3) a time in ISO8601 format, e.g. '2016-01-01T16:24:00Z'\n\n samples_per_second : numpy.longdouble, required for float and time `iden`\n Sample rate in Hz used to convert a time to a sample index.\n\n ref_index : int/long, required for '+' string form of `iden`\n Reference index from which string `iden` beginning with '+' are\n offset.\n\n\n Returns\n -------\n\n sample_index : long | None\n Index to the identified sample given in the number of samples since\n the epoch (time_since_epoch*sample_per_second).\n\n \"\"\"\n is_relative = False\n if iden is None or iden == '':\n return None\n elif isinstance(iden, six.string_types):\n if iden.startswith('+'):\n is_relative = True\n iden = iden.lstrip('+')\n try:\n # int/long or float\n iden = ast.literal_eval(iden)\n except (ValueError, SyntaxError):\n # convert datetime to float\n dt = dateutil.parser.parse(iden)\n epoch = datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)\n iden = (dt - epoch).total_seconds()\n\n if isinstance(iden, float):\n if samples_per_second is None:\n raise ValueError(\n 'samples_per_second required when time identifier is used.'\n )\n idx = long(np.uint64(iden*samples_per_second))\n else:\n idx = long(iden)\n\n if is_relative:\n if ref_index is None:\n raise ValueError(\n 'ref_index required when relative \"+\" identifier is used.'\n )\n return idx + ref_index\n else:\n return idx\n","sub_path":"python/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"263860889","text":"# 115 - Crie um pequeno sistema modularizado que permita cadastrar pessoas pelo seu nome e idade em um arquivo de texto\n# simples. O sistema só vai ter 2 opções: cadastrar uma nova pessoa e listar todas as pessoas cadastradas.\n\ndef leiaInt(msg):\n while True:\n try:\n valor = int(input(msg))\n print('valor = int(input(msg)) Vim aqui')\n except (ValueError, TypeError):\n print(f'\\033[1;31mErro!\\033[m')\n continue\n except KeyboardInterrupt:\n print('Sair')\n return 3\n else:\n print('retornei o valor')\n return valor\n\n\n\ndef linha(tam=42):\n return '-'* tam\n\n\ndef cabeçalho(txt):\n print(linha())\n print(txt.center(42))\n print(linha())\n\n\ndef menu(lista):\n cabeçalho('Menu Principal')\n c = 1\n for item in lista:\n print(f'{c} - {item}') \n c += 1\n print(linha())\n op = leiaInt('Sua opção: ')\n return op\n\n","sub_path":"Mundo3/Ex115/lib/interface/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"287639346","text":"from botlog import BotLog\nfrom botcandlestick import BotCandlestick\nfrom botindicators import BotIndicators\nfrom bottrade import BotTrade\nimport time\n\n\nclass BotStrategy(object):\n def __init__(self, startingBal):\n self.output = BotLog()\n self.trades = []\n self.candlesticks = []\n self.indicators = BotIndicators()\n self.currentBal = startingBal\n\n def evaluatePositions(self):\n prices = []\n over_last_n_periods = 15\n lastCandlestick = self.candlesticks[-1]\n\n for i in range(1, over_last_n_periods + 1):\n prices.append(self.candlesticks[-i].priceAverage)\n\n if (self.trades and self.trades[-1].status == \"CLOSED\") or not self.trades:\n # buy\n if lastCandlestick.priceAverage < self.indicators.movingAverage(prices):\n currentTrade = BotTrade(self.trades.__len__() + 1, lastCandlestick.close, lastCandlestick.date, self.currentBal)\n self.trades.append(currentTrade)\n # currentTrade.logBuy()\n\n if self.trades and self.trades[-1].status == \"OPEN\":\n lastTrade = self.trades[-1]\n # sell\n if lastCandlestick.priceAverage > self.indicators.movingAverage(prices):\n lastTrade.close(lastCandlestick.close, lastCandlestick.date)\n # lastTrade.logSell()\n self.currentBal = lastTrade.currentBal\n\n def showPositions(self, startingInvestment, displayTradeDetails):\n investment = startingInvestment\n tradeNum = 1\n for trade in self.trades:\n if trade.exitPrice != '':\n invAtStartOfTrade = investment\n buyTax = investment * -0.0025\n investment = investment + buyTax # amount of currency bought\n tradeProfit = investment * (float(trade.exitPrice) / float(trade.entryPrice)) - investment\n investment = investment * (float(trade.exitPrice) / float(trade.entryPrice))\n sellTax = investment * -0.0025\n investment = investment + sellTax\n net = investment - invAtStartOfTrade\n\n if displayTradeDetails:\n # color code net\n if net > 0:\n netStr = \"\\033[92m$\" + str(format(net, ',.2f')) + \"\\033[0m\"\n else:\n netStr = \"\\033[91m$\" + str(format(net, ',.2f')) + \"\\033[0m\"\n\n print(\"--------------------\" + \"Trade #\" + str(format(tradeNum, ',')) + \" | \" +\n time.strftime('%m/%d/%Y %H:%M:%S', time.localtime(trade.timeTradeStart)) +\n \" - \" + time.strftime('%H:%M:%S', time.localtime(trade.timeTradeEnd)) +\n \"--------------------\")\n trade.showTrade()\n print(\"\\t\\t Buy tax: $\" + str(buyTax))\n print(\"\\t\\t Sell tax: $\" + str(sellTax))\n print(\"\\t\\t Profit from trade: $\" + str(tradeProfit))\n print(\"\\t\\t Before Trade: $\" + str(invAtStartOfTrade))\n print(\"\\t\\t After Trade: $\" + str(investment))\n print(\"\\t\\t Net: \" + netStr)\n tradeNum += 1\n\n # color code investment\n if investment > startingInvestment:\n endStr = \"\\033[92m$\" + str(format(investment, ',.2f')) + \"\\033[0m\"\n else:\n endStr = \"\\033[91m$\" + str(format(investment, ',.2f')) + \"\\033[0m\"\n print(\"\\nStart: $\" + str(format(startingInvestment, ',.2f')))\n print(\"End: \" + endStr)\n\n","sub_path":"botstrategy.py","file_name":"botstrategy.py","file_ext":"py","file_size_in_byte":3669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"207948181","text":"# Copyright DataStax, 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 astrapy.collections import create_client, AstraCollection\nimport uuid\nimport pytest\nimport logging\nimport os\n\nlogger = logging.getLogger(__name__)\n\nASTRA_DB_ID = os.environ.get('ASTRA_DB_ID')\nASTRA_DB_REGION = os.environ.get('ASTRA_DB_REGION')\nASTRA_DB_APPLICATION_TOKEN = os.environ.get('ASTRA_DB_APPLICATION_TOKEN')\nASTRA_DB_KEYSPACE = os.environ.get('ASTRA_DB_KEYSPACE')\n\nTEST_COLLECTION_NAME = \"test\"\n\n\n@pytest.fixture\ndef test_collection():\n astra_client = create_client(astra_database_id=ASTRA_DB_ID,\n astra_database_region=ASTRA_DB_REGION,\n astra_application_token=ASTRA_DB_APPLICATION_TOKEN)\n\n return astra_client.namespace(ASTRA_DB_KEYSPACE).collection(TEST_COLLECTION_NAME)\n\n\n@pytest.fixture\ndef cliff_uuid():\n return str(uuid.uuid4())\n\n\n@pytest.mark.it('should initialize an AstraDB Collections Client')\ndef test_connect(test_collection):\n assert type(test_collection) is AstraCollection\n\n\n@pytest.mark.it('should create a document')\ndef test_create_document(test_collection, cliff_uuid):\n test_collection.create(path=cliff_uuid, document={\n \"first_name\": \"Cliff\",\n \"last_name\": \"Wicklow\",\n })\n document = test_collection.get(path=cliff_uuid)\n assert document[\"first_name\"] == \"Cliff\"\n\n\n@pytest.mark.it('should create a subdocument')\ndef test_create_subdocument(test_collection, cliff_uuid):\n test_collection.create(path=f\"{cliff_uuid}/addresses\", document={\n \"home\": {\n \"city\": \"New York\",\n \"state\": \"NY\",\n }\n })\n document = test_collection.get(path=f\"{cliff_uuid}/addresses\")\n assert document[\"home\"][\"state\"] == \"NY\"\n\n\n@pytest.mark.it('should create a document without an ID')\ndef test_create_document_without_id(test_collection):\n response = test_collection.create(document={\n \"first_name\": \"New\",\n \"last_name\": \"Guy\",\n })\n document = test_collection.get(path=response[\"documentId\"])\n assert document[\"first_name\"] == \"New\"\n\n\n@pytest.mark.it('should udpate a document')\ndef test_update_document(test_collection, cliff_uuid):\n test_collection.update(path=cliff_uuid, document={\n \"first_name\": \"Dang\",\n })\n document = test_collection.get(path=cliff_uuid)\n assert document[\"first_name\"] == \"Dang\"\n\n\n@pytest.mark.it('replace a subdocument')\ndef test_replace_subdocument(test_collection, cliff_uuid):\n test_collection.replace(path=f\"{cliff_uuid}/addresses\", document={\n \"work\": {\n \"city\": \"New York\",\n \"state\": \"NY\",\n }\n })\n document = test_collection.get(path=f\"{cliff_uuid}/addresses/work\")\n assert document[\"state\"] == \"NY\"\n document_2 = test_collection.get(path=f\"{cliff_uuid}/addresses/home\")\n assert document_2 is None\n\n\n@pytest.mark.it('should delete a subdocument')\ndef test_delete_subdocument(test_collection, cliff_uuid):\n test_collection.delete(path=f\"{cliff_uuid}/addresses\")\n document = test_collection.get(path=f\"{cliff_uuid}/addresses\")\n assert document is None\n\n\n@pytest.mark.it('should delete a document')\ndef test_delete_document(test_collection, cliff_uuid):\n test_collection.delete(path=cliff_uuid)\n document = test_collection.get(path=cliff_uuid)\n assert document is None\n\n\n@pytest.mark.it('should find documents')\ndef test_find_documents(test_collection):\n user_id = str(uuid.uuid4())\n test_collection.create(path=user_id, document={\n \"first_name\": f\"Cliff-{user_id}\",\n \"last_name\": \"Wicklow\",\n })\n user_id_2 = str(uuid.uuid4())\n test_collection.create(path=user_id_2, document={\n \"first_name\": f\"Cliff-{user_id}\",\n \"last_name\": \"Danger\",\n })\n documents = test_collection.find(query={\n \"first_name\": {\"$eq\": f\"Cliff-{user_id}\"},\n })\n assert len(documents.keys()) == 2\n assert documents[user_id][\"last_name\"] == \"Wicklow\"\n assert documents[user_id_2][\"last_name\"] == \"Danger\"\n\n\n@pytest.mark.it('should find a single document')\ndef test_find_one_document(test_collection):\n user_id = str(uuid.uuid4())\n test_collection.create(path=user_id, document={\n \"first_name\": f\"Cliff-{user_id}\",\n \"last_name\": \"Wicklow\",\n })\n user_id_2 = str(uuid.uuid4())\n test_collection.create(path=user_id_2, document={\n \"first_name\": f\"Cliff-{user_id}\",\n \"last_name\": \"Danger\",\n })\n document = test_collection.find_one(query={\n \"first_name\": {\"$eq\": f\"Cliff-{user_id}\"},\n })\n assert document[\"first_name\"] == f\"Cliff-{user_id}\"\n","sub_path":"tests/astrapy/test_collections.py","file_name":"test_collections.py","file_ext":"py","file_size_in_byte":5108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"355184200","text":"#!/usr/bin/env python \n# -*- coding:utf-8 -*-\nclass Solution:\n # matrix类型为二维列表,需要返回列表\n def printMatrix(self, matrix):\n # write code here\n result = []\n while matrix:\n # print('matrix',matrix)\n # pop(0)删除列表中第一个元素,xtend添加元素后,result中不会出现列表形式的元素,和+等效\n result.extend(matrix.pop(0))\n matrix = self.turn(matrix)\n # print('result',result)\n return result\n\n #逆时针90度旋转矩阵\n def turn(self,matrix):\n turned_matrix = []\n if matrix:\n row,col = len(matrix),len(matrix[0])\n for j in range(col-1,-1,-1):\n col_list = []\n for i in range(row):\n # print('%d %d %d'%(i,j,matrix[i][j]))\n col_list.append(matrix[i][j])\n # print('col_list',col_list)\n turned_matrix.append(col_list)\n # print('turned_matrix',turned_matrix)\n return turned_matrix\n\nif __name__ == '__main__':\n s = Solution()\n a = [[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],[13, 14, 15, 16]]\n # b = [i for i in range(1,17)]\n # print(b)\n # b = s.turn(a)\n # print('b',b)\n # print(a.pop(0))\n # a.reverse()\n # print(a)\n s.printMatrix(a) #1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.\n","sub_path":"jz_offer/顺时针打印矩阵.py","file_name":"顺时针打印矩阵.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"451642389","text":"import serial\nimport time\nimport multiprocessing\n\n\n## Change this to match your local settings\nPORT = '/dev/ttyUSB0'\nBAUDRATE = 9600\nPARITY=serial.PARITY_EVEN\nSTOPBITS=serial.STOPBITS_ONE\nBYTESIZE=serial.SEVENBITS\n\n #voltageCommand = chr(0x2F) + chr(0x3F) + chr(0x21) + chr(0x01) + chr(0x52) + chr(0x31) + chr(0x02) + chr(0x56) + chr(0x4F)+chr(0x4C)+chr(0x54)+ chr(0x41)+chr(0x28)+ chr(0x29)+chr(0x03)+chr(0x5F)\n # currentCommand = chr(0x2F) + chr(0x3F) + chr(0x21) + chr(0x01) + chr(0x52) + chr(0x31) + chr(0x02) + chr(0x43) + chr(0x55)+ chr(0x52)+ chr(0x52)+chr(0x45)+chr(0x28)+chr(0x29)+chr(0x03)+chr(0x5A)\n # powerCoefCommand = chr(0x2F) + chr(0x3F) + chr(0x21) + chr(0x01) + chr(0x52) + chr(0x31) + chr(0x02) + chr(0x43) + chr(0x4f)+ chr(0x53)+ chr(0x5f)+chr(0x66)+chr(0x28)+chr(0x29)+chr(0x03)+chr(0x83)\n # powerCommand = chr(0x2F) + chr(0x3F) + chr(0x21) + chr(0x01) + chr(0x52) + chr(0x31) + chr(0x02) + chr(0x50) + chr(0x4F)+ chr(0x57) + chr(0x50) + chr(0x50) + chr(0x28) + chr(0x29) + chr(0x03) + chr(0x6F)\n # totalCosumedPowerCommand = chr(0x2F) + chr(0x3F) + chr(0x21) + chr(0x01) + chr(0x52) + chr(0x31) + chr(0x02) + chr(0x50) + chr(0x4f)+ chr(0x57)+ chr(0x45)+chr(0x50)+chr(0x28)+chr(0x29)+chr(0x03)+chr(0x64)\n # numeratorPowerCommand = chr(0x2F) + chr(0x3F) + chr(0x21) + chr(0x01) + chr(0x52) + chr(0x31) + chr(0x02) + chr(0x45) + chr(0x54)+ chr(0x30)+ chr(0x50)+chr(0x45)+chr(0x28)+chr(0x29)+chr(0x03)+chr(0x37)\n#message_command =chr(0x2F) + chr(0x3F) + chr(0x21) + chr(0x01) + chr(0x52) + chr(0x31) + chr(0x02) + chr(0x56) + chr(0x4F)+chr(0x4C)+chr(0x54)+ chr(0x41)+chr(0x28)+ chr(0x29)+chr(0x03)+chr(0x5F)\nmessage_command_volt = chr(0x2F) + chr(0x3F) + chr(0x21) + chr(0x01) + chr(0x52) + chr(0x31) + chr(0x02) + chr(0x56) + chr(0x4F)+chr(0x4C)+chr(0x54)+ chr(0x41)+chr(0x28)+ chr(0x29)+chr(0x03)+chr(0x5F)\nmessage_command_amp = chr(0x2F) + chr(0x3F) + chr(0x21) + chr(0x01) + chr(0x52) + chr(0x31) + chr(0x02) + chr(0x43) + chr(0x55)+ chr(0x52)+ chr(0x52)+chr(0x45)+chr(0x28)+chr(0x29)+chr(0x03)+chr(0x5A)\n\n#print(message_command2)\n\nclass SerialProcess(multiprocessing.Process):\n \n def __init__(self, input_queue, output_queue, parity=PARITY, stopbits=STOPBITS, bytesize=BYTESIZE, baudrate=BAUDRATE, timeout=1):\n multiprocessing.Process.__init__(self, target=self.serial_con, args=(PORT, BAUDRATE, PARITY, STOPBITS, BYTESIZE, 1))\n self.input_queue = input_queue\n self.output_queue = output_queue\n self.result = bytes()\n \n #self.sp = serial.Serial(PORT, parity=PARITY, stopbits=STOPBITS, bytesize=BYTESIZE, baudrate=BAUDRATE, timeout=1)\n \n def serial_con(self, PORT=PORT, baudrate=BAUDRATE, bytesize=BYTESIZE, parity=PARITY, stopbits=STOPBITS, timeout=1):\n self.ser = serial.Serial(PORT, baudrate, bytesize, parity, stopbits, timeout=1)\n self.save_ser(self.ser)\n \n def save_ser(self, obj=None):\n if obj:\n self.sp = obj\n else:\n return self.sp\n\n def close(self):\n self.sp.close()\n \n def writeSerial(self, data):\n #self.sp.open()\n if data == 'volt':\n #time.sleep(0.1)\n self.sp.write(message_command_volt.encode())\n elif data == 'amp':\n self.sp.write(message_command_amp.encode())\n elif data == 'none':\n pass\n else:\n sent_data = data.encode()\n print(self.sp)\n self.sp.write(sent_data) \n \n def readSerial(self):\n #return self.sp.readline().replace(\"\\n\", \"\")\n print('reading')\n self.result = self.sp.read_until('+')\n #self.result = self.sp.read_all()\n print(len(self.result))\n \n #x = result.rstrip(b\",.\\/#-\\\\)-*&$!%^@+0123456789\\\\'\\\\(|{}\\\"\")\n now = time.strftime(\"%Y/%m/%d %H:%M:%S\")\n x = self.result[:-2]\n x += ('

received on: '+now).encode()\n #result = self.sp.read(100)\n #print(x.decode())\n #print(result)\n return x\n \n \n \n def run(self):\n self.serial_con()\n self.sp = self.save_ser()\n #self.sp.flushInput()\n #print(dir(self.sp))\n while True:\n\n # look for incoming tornado request\n \n if not self.input_queue.empty():\n data = self.input_queue.get()\n #print('data incoming')\n # send it to the serial device\n #print(type(data.encode('ascii')))\n #self.sp.write(data.encode())\n self.writeSerial(data)\n print(\"writing to serial: \", data)\n #x = self.sp.readline().decode()\n #self.output_queue.put(x)\n # look for incoming serial data\n #print(self.sp.readline())\n #print(self.output_queue.get())\n #self.output_queue.put('response from console')\n #self.output_queue.put('response')\n #self.sp.open()\n if (self.sp.in_waiting > 0):\n response = self.readSerial()\n # send it back to tornado\n self.output_queue.put(response.decode())\n #print(self.output_queue)\n time.sleep(0.09)\n\n\n#voltage commands for ec2\n#chr(0x2F) + chr(0x3F) + chr(0x21) + chr(0x01) + chr(0x52) + chr(0x31) + chr(0x02) + chr(0x56) + chr(0x4F)+chr(0x4C)+chr(0x54)+ chr(0x41)+chr(0x28)+ chr(0x29)+chr(0x03)+chr(0x5F)\n","sub_path":"worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":5426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"297006477","text":"# -*- coding: utf-8 -*-\n# Copyright 2023 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfrom .data import (\n AdBreak,\n AudioStream,\n EditAtom,\n ElementaryStream,\n Input,\n Job,\n JobConfig,\n JobEventData,\n JobTemplate,\n JobTemplateEventData,\n Manifest,\n MuxStream,\n Output,\n Overlay,\n PreprocessingConfig,\n PubsubDestination,\n SegmentSettings,\n SpriteSheet,\n TextStream,\n VideoStream,\n)\n\n__all__ = (\n 'AdBreak',\n 'AudioStream',\n 'EditAtom',\n 'ElementaryStream',\n 'Input',\n 'Job',\n 'JobConfig',\n 'JobEventData',\n 'JobTemplate',\n 'JobTemplateEventData',\n 'Manifest',\n 'MuxStream',\n 'Output',\n 'Overlay',\n 'PreprocessingConfig',\n 'PubsubDestination',\n 'SegmentSettings',\n 'SpriteSheet',\n 'TextStream',\n 'VideoStream',\n)\n","sub_path":"src/google/events/cloud/video/transcoder_v1/types/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"474884230","text":"import scipy as sp\nfrom scipy import pi, sin, cos, tan, arcsin, meshgrid, linspace, sqrt\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\ndef sec(x):\n return 1 / cos(x) # 関数 sec を定義\n\n\nu = linspace(0, 0.4 * pi, 20) # メッシュ作成の変数方位角 θ 周り 0 から 0.4π,20 等分\nv = linspace(0, 2 * pi, 20) # メッシュ作成の変数方位角 φ 周り 0 から 2π,20 等分\n\nepz = 3 # z 方向の誘電率(正の値)\nepx = 5 # x 方向の誘電率の絶対値(負の値)\n\nuu, vv = meshgrid(u, v) # メッシュの作成\n\nx1 = sqrt(epz) * tan(uu) * cos(vv) # 屈折率楕円体 x 方向(z が正の範囲)\ny1 = sqrt(epz) * tan(uu) * sin(vv) # 屈折率楕円体 y 方向(z が正の範囲)\nz1 = sqrt(epx) * sec(uu) # 屈折率楕円体 z 方向(z が正の範囲)\n\nx2 = sqrt(epz) * tan(uu) * cos(vv) # 屈折率楕円体 x 方向(z が負の範囲)\ny2 = sqrt(epz) * tan(uu) * sin(vv) # 屈折率楕円体 y 方向(z が負の範囲)\nz2 = -sqrt(epx) * sec(uu) # 屈折率楕円体 z 方向(z が負の範囲)\n\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nax.plot_wireframe(x1, y1, z1) # ワイヤフレームのプロット\nax.plot_wireframe(x2, y2, z2) # ワイヤフレームのプロット\n\nax.set_xlabel('X') # x 方向ラベル\nax.set_ylabel('Y') # y 方向ラベル\nax.set_zlabel('Z') # z 方向ラベル\n\nax.set_xlim3d(-6, 6) # x 方向プロット範囲\nax.set_ylim3d(-6, 6) # y 方向プロット範囲\nax.set_zlim3d(-7, 7) # z 方向プロット範囲\n\nplt.show() # グラフの表示\n","sub_path":"org-code/1-10.py","file_name":"1-10.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"83624198","text":"# coding=utf-8\r\nimport os\r\nimport gc\r\nimport time\r\nimport warnings\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn.metrics import f1_score\r\nfrom m_rpca import fit, md_rpca_prediction, sd_rpca_prediction, kd_rpca_prediction\r\nfrom utils_ctu_13 import data_splitting_50_33, ctu13_data_cleasing, ctu13_raw_column_types\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\ncol_list = ['State', 'dTos', 'Dport', 'Sport', 'TotPkts', 'TotBytes', 'SrcBytes']\r\n\r\nstart_time = time.time()\r\nraw_path = os.path.join('data/ctu_13/raw_clean_pkl/')\r\nraw_directory = os.fsencode(raw_path)\r\npkl_path = os.path.join('data/ctu_13/raw_clean_pkl/')\r\npkl_directory = os.fsencode(pkl_path)\r\nfile_list = os.listdir(pkl_directory)\r\ntest_robpca_path = 'data/ctu_13/raw_clean_test_robpca_csv/'\r\n\r\nm_f1_list = []\r\ns_f1_list = []\r\nk_f1_list = []\r\n# for each scenario\r\nfor sample_file in file_list:\r\n\r\n # read pickle file with pandas or...\r\n pkl_file_path = os.path.join(pkl_directory, sample_file).decode('utf-8')\r\n if os.path.isfile(pkl_file_path):\r\n print(\"## Sample File: \", pkl_file_path)\r\n df = pd.read_pickle(pkl_file_path)\r\n else: # load raw file and save clean data into pickles\r\n raw_file_path = os.path.join(raw_directory, sample_file).decode('utf-8')\r\n print(\"## Sample File: \", raw_file_path)\r\n raw_df = pd.read_csv(raw_file_path, header=0, dtype=ctu13_raw_column_types)\r\n df = ctu13_data_cleasing(raw_df)\r\n df.to_pickle(pkl_file_path)\r\n gc.collect()\r\n\r\n # data splitting\r\n norm_train_df, test_df, test_label_df = data_splitting_50_33(df, col_list)\r\n\r\n test_robpca_file_path = '%s/33_%s' % (test_robpca_path, sample_file)\r\n print(test_robpca_file_path)\r\n if not os.path.isfile(test_robpca_file_path):\r\n test_label_robpca_file_path = '%s/label_33_%s' % (test_robpca_path, sample_file)\r\n test_df.to_csv(test_robpca_file_path)\r\n test_label_df.to_csv(test_label_robpca_file_path)\r\n\r\n # Train\r\n L, rob_mean, rob_cov, rob_dist, rob_precision, rob_skew, rob_skew_dist, rob_kurt, rob_kurt_dist = fit(\r\n np.array(norm_train_df, dtype=float))\r\n\r\n # Cross-Validation for best_contamination\r\n test_label_vc = test_label_df.value_counts()\r\n ones = test_label_vc.get(1)\r\n if ones == 0:\r\n continue\r\n zeros = test_label_vc.get(0)\r\n best_contamination = ones/(ones + zeros)\r\n if best_contamination > 0.5:\r\n best_contamination = 0.5\r\n print('### Cross-Validation. Contamination:', best_contamination)\r\n\r\n # Testing md-rpca\r\n md_pred_label = md_rpca_prediction(test_df, rob_mean, rob_precision, best_contamination)\r\n m_f1 = f1_score(test_label_df, md_pred_label)\r\n m_f1_list.append(m_f1)\r\n print('%s - md_rpca_prediction - F1: %f' % (sample_file, m_f1))\r\n\r\n # Testing sd-rpca\r\n sd_pred_label = sd_rpca_prediction(test_df, rob_skew, rob_precision, best_contamination)\r\n s_f1 = f1_score(test_label_df, sd_pred_label)\r\n s_f1_list.append(s_f1)\r\n print('%s - sd_rpca_prediction - F1: %f' % (sample_file, s_f1))\r\n\r\n # Testing kd-rpca\r\n kd_pred_label = kd_rpca_prediction(test_df, rob_kurt, rob_precision, best_contamination)\r\n k_f1 = f1_score(test_label_df, kd_pred_label)\r\n k_f1_list.append(k_f1)\r\n print('%s - kd_rpca_prediction - F1: %f' % (sample_file, k_f1))\r\n\r\nprint('l_mean:', np.mean(m_f1_list))\r\nprint('s_mean:', np.mean(s_f1_list))\r\nprint('k_mean:', np.mean(k_f1_list))\r\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\r\n","sub_path":"network-attack-detection/m_rpca_test_ctu_13.py","file_name":"m_rpca_test_ctu_13.py","file_ext":"py","file_size_in_byte":3485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"554884588","text":"# django imports\nfrom django.conf.urls import url\n# local imports\nfrom rent import views\n\n\napp_name = 'rent'\nurlpatterns = [\n url(\n r'^home/$',\n views.get_homepage,\n name='homepage',\n ),\n url(\n r'^add-property/$',\n views.AddProperty.as_view(),\n name='add_property',\n ),\n url(\n r'^rented-properties/$',\n views.ListRentedProperties.as_view(),\n name='list_rented_properties',\n ),\n url(\n r'^vacant-properties/$',\n views.ListVacantProperties.as_view(),\n name='vacant_properties',\n ),\n]\n","sub_path":"django/rent/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"598387036","text":"\"\"\"\nDay 3\n\nYou probably know the \"like\" system from Facebook and other pages. People can \"like\" blog\nposts, pictures or other items. We want to create the text that should be displayed next\nto such an item.\n\nImplement the function which takes an array containing the names of people that\nlike an item. It must return the display text as shown in the examples:\n\n[] --> \"no one likes this\"\n[\"Peter\"] --> \"Peter likes this\"\n[\"Jacob\", \"Alex\"] --> \"Jacob and Alex like this\"\n[\"Max\", \"John\", \"Mark\"] --> \"Max, John and Mark like this\"\n[\"Alex\", \"Jacob\", \"Mark\", \"Max\"] --> \"Alex, Jacob and 2 others like this\"\nNote: For 4 or more names, the number in \"and 2 others\" simply increases.\n\"\"\"\n\n\n# My Solution\ndef likes(names):\n likecount = len(names)\n if likecount == 0:\n return \"no one likes this\"\n elif likecount < 3:\n return \" and \".join(names) + f\" {'likes' if likecount == 1 else 'like'} this\"\n elif likecount == 3:\n return f\"{names[0]}, {names[1]} and {names[2]} like this\"\n else:\n return \", \".join(names[:2]) + f\" and {likecount-2} others like this\"\n\n\n# Highest rated solution on CodeWars\ndef likes_sol(names):\n n = len(names)\n return {\n 0: 'no one likes this',\n 1: '{} likes this',\n 2: '{} and {} like this',\n 3: '{}, {} and {} like this',\n 4: '{}, {} and {others} others like this'\n }[min(4, n)].format(*names[:3], others=n-2)\n","sub_path":"Kata_3.py","file_name":"Kata_3.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"197788524","text":"import os\nimport pandas as pd\nimport numpy as np\nfrom sklearn.linear_model import SGDClassifier # linear svm by default\nfrom sklearn.calibration import CalibratedClassifierCV\n\nfrom scopeAL_and_SMR.src.utils import get_init_training_data_idx, \\\n load_data, Vectorizer, CrowdSimulator, MetricsMixin\nfrom scopeAL_and_SMR.src.active_learning import Learner, ScreeningActiveLearner\nfrom scopeAL_and_SMR.src.sm_run.shortest_multi_run import ShortestMultiRun\nfrom scopeAL_and_SMR.src.policy import PointSwitchPolicy\n\n\ndef run_experiment(params):\n # parameters for crowd simulation\n crowd_acc = params['crowd_acc']\n crowd_votes_per_pred_al = params['crowd_votes_per_pred_al']\n predicates = params['predicates']\n screening_out_threshold_machines = 0.7\n\n df_to_print = pd.DataFrame()\n for budget_per_item in params['budget_per_item']:\n B = params['dataset_size'] * budget_per_item\n for switch_point in params['policy_switch_point']:\n print('Policy switch point: {}'.format(switch_point))\n print('Budget per item: {}'.format(budget_per_item))\n print('************************************')\n results_list = []\n for experiment_id in range(params['experiment_nums']):\n policy = PointSwitchPolicy(B, switch_point)\n\n X, y_screening, y_predicate = load_data(params['dataset_file_name'], predicates, params['path_to_project'])\n vectorizer = Vectorizer()\n vectorizer.fit(X)\n\n items_num = y_screening.shape[0]\n item_predicate_gt = {}\n for pr in predicates:\n item_predicate_gt[pr] = {item_id: gt_val for item_id, gt_val in zip(list(range(items_num)), y_predicate[pr])}\n item_ids_helper = {pr: np.arange(items_num) for pr in predicates} # helper to track item ids\n crowd_votes_counts, prior_prob = {}, {}\n for item_id in range(items_num):\n crowd_votes_counts[item_id] = {pr: {'in': 0, 'out': 0} for pr in predicates}\n item_labels = {item_id: 1 for item_id in range(items_num)} # classify all items as in by default\n y_screening_dict = {item_id: label for item_id, label in zip(list(range(items_num)), y_screening)}\n\n params.update({\n 'X': X,\n 'y_screening': y_screening,\n 'y_predicate': y_predicate,\n 'vectorizer': vectorizer\n })\n\n # if Available Budget for Active Learniong is available then Do Run Active Learning Box\n if switch_point != 0:\n SAL = configure_al_box(params, item_ids_helper, crowd_votes_counts, item_labels)\n policy.update_budget_al(params['size_init_train_data']*len(predicates)*crowd_votes_per_pred_al)\n SAL.screening_out_threshold = screening_out_threshold_machines\n while policy.is_continue_al:\n # SAL.update_stat() # uncomment if use predicate selection feature\n\n # pr = SAL.select_predicate()\n query_idx = SAL.query()\n if len(query_idx) == 0:\n # exit the loop if we crowdsourced all the items\n break\n # crowdsource sampled items\n gt_items_queried = {}\n for pr in predicates:\n gt_items_queried[pr] = y_predicate[pr][query_idx]\n y_predicate[pr] = np.delete(y_predicate[pr], query_idx)\n\n y_crowdsourced = CrowdSimulator.crowdsource_items_scope_mode(item_ids_helper[predicates[0]][query_idx], gt_items_queried, predicates,\n crowd_acc, crowd_votes_per_pred_al, crowd_votes_counts)\n SAL.teach(query_idx, y_crowdsourced)\n for pr in predicates:\n item_ids_helper[pr] = np.delete(item_ids_helper[pr], query_idx)\n\n policy.update_budget_al(SAL.n_instances_query*crowd_votes_per_pred_al*len(predicates))\n\n unclassified_item_ids = np.arange(items_num)\n # Get prior from machines\n for item_id in range(items_num):\n prior_prob[item_id] = {}\n for pr in predicates:\n prediction = SAL.predict_proba(vectorizer.transform([X[item_id]]))[0]\n prior_prob[item_id][pr] = {'in': prediction[1], 'out': prediction[0]}\n print('experiment_id {}'.format(experiment_id), end=', ')\n\n # if Available Budget for Crowd-Box DO SM-RUN\n if policy.B_crowd:\n policy.B_crowd = policy.B - policy.B_al_spent\n estimated_predicate_accuracy = {}\n estimated_predicate_selectivity = {}\n for pr in predicates:\n estimated_predicate_accuracy[pr] = sum(crowd_acc[pr]) / 2\n estimated_predicate_selectivity[pr] = sum(item_predicate_gt[pr].values()) / len(item_predicate_gt[pr].values())\n smr_params = {\n 'estimated_predicate_accuracy': estimated_predicate_accuracy,\n 'estimated_predicate_selectivity': estimated_predicate_selectivity,\n 'predicates': predicates,\n 'item_predicate_gt': item_predicate_gt,\n 'clf_threshold': params['screening_out_threshold'],\n 'stop_score': params['stop_score'],\n 'crowd_acc': crowd_acc,\n 'prior_prob': prior_prob\n }\n SMR = ShortestMultiRun(smr_params)\n unclassified_item_ids = np.arange(items_num)\n # crowdsource items for SM-Run base-round in case poor SM-Run used\n if switch_point == 0:\n baseround_item_num = 50 # since 50 used in WWW2018 Krivosheev et.al\n items_baseround = unclassified_item_ids[:baseround_item_num]\n for pr in predicates:\n gt_items_baseround = {item_id: item_predicate_gt[pr][item_id] for item_id in items_baseround}\n CrowdSimulator.crowdsource_items(items_baseround, gt_items_baseround, pr, crowd_acc[pr],\n crowd_votes_per_pred_al, crowd_votes_counts)\n policy.update_budget_crowd(baseround_item_num * crowd_votes_per_pred_al)\n unclassified_item_ids = SMR.classify_items(unclassified_item_ids, crowd_votes_counts, item_labels)\n\n while policy.is_continue_crowd and unclassified_item_ids.any():\n # Check money\n if (policy.B_crowd - policy.B_crowd_spent) < len(unclassified_item_ids):\n unclassified_item_ids = unclassified_item_ids[:(policy.B_crowd - policy.B_crowd_spent)]\n unclassified_item_ids, budget_round = SMR.do_round(crowd_votes_counts, unclassified_item_ids, item_labels)\n policy.update_budget_crowd(budget_round)\n # print('Crowd-Box finished')\n\n # if budget is over and we did the AL part then classify the rest of the items via machines\n if unclassified_item_ids.any() and switch_point != 0:\n predicted = SAL.predict(vectorizer.transform(X[unclassified_item_ids]))\n item_labels.update(dict(zip(unclassified_item_ids, predicted)))\n\n # compute metrics and pint results to csv\n metrics = MetricsMixin.compute_screening_metrics(y_screening_dict, item_labels, params['lr'], params['beta'])\n pre, rec, f_beta, loss, fn_count, fp_count = metrics\n budget_spent_item = (policy.B_al_spent + policy.B_crowd_spent) / items_num\n results_list.append([budget_per_item, budget_spent_item, pre, rec, f_beta, loss, fn_count,\n fp_count, switch_point])\n\n print('budget spent per item: {:1.3f}, loss: {:1.3f}, fbeta: {:1.3f}, '\n 'recall: {:1.3f}, precisoin: {:1.3f}'\n .format(budget_spent_item, loss, f_beta, rec, pre))\n print('--------------------------------------------------------------')\n\n df = pd.DataFrame(results_list, columns=['budget_per_item', 'budget_spent_per_item',\n 'precision', 'recall', 'f{}'.format(params['beta']), 'loss',\n 'fn_count', 'fp_count', 'AL_switch_point'])\n df = compute_mean_std(df)\n df['active_learning_strategy'] = params['sampling_strategy'].__name__ if switch_point != 0 else ''\n df['screening_out_threshold'] = params['screening_out_threshold']\n df_to_print = df_to_print.append(df, ignore_index=True)\n\n file_name = params['dataset_file_name'][:-4] + '_experiment_nums_{}_ninstq_{}'.format(params['experiment_nums'], params['n_instances_query'])\n if len(predicates) == 1:\n file_name = 'binary_' + file_name\n path = params['path_to_project'] + 'scopeAL_and_SMR/output/'\n if os.path.isfile(path + '{}.csv'.format(file_name)):\n df_prev = pd.read_csv(path + '{}.csv'.format(file_name))\n df_new = df_prev.append(df_to_print, ignore_index=True)\n df_new.to_csv(path + '{}.csv'.format(file_name), index=False)\n else:\n df_to_print.to_csv(path + '{}.csv'.format(file_name), index=False)\n\n\n# set up active learning box\ndef configure_al_box(params, item_ids_helper, crowd_votes_counts, item_labels):\n y_screening, y_predicate = params['y_screening'], params['y_predicate']\n size_init_train_data = params['size_init_train_data']\n predicates = params['predicates']\n\n X_pool = params['vectorizer'].transform(params['X'])\n # creating balanced init training data\n train_idx = get_init_training_data_idx(y_screening, y_predicate, size_init_train_data)\n\n y_predicate_train_init = {}\n X_train_init = X_pool[train_idx]\n X_pool = np.delete(X_pool, train_idx, axis=0)\n y_screening_train_init = y_screening[train_idx]\n y_screening_pool = np.delete(y_screening, train_idx)\n for pr in predicates:\n y_predicate_train_init[pr] = y_predicate[pr][train_idx]\n y_predicate[pr] = np.delete(y_predicate[pr], train_idx)\n item_ids_helper[pr] = np.delete(item_ids_helper[pr], train_idx)\n for item_id, label in zip(train_idx, y_predicate_train_init[pr]):\n if label == 1:\n crowd_votes_counts[item_id][pr]['in'] = params['crowd_votes_per_pred_al']\n else:\n crowd_votes_counts[item_id][pr]['out'] = params['crowd_votes_per_pred_al']\n\n # dict of active learners per predicate\n learner_params = {\n 'clf': CalibratedClassifierCV(SGDClassifier(class_weight='balanced', max_iter=1000, tol=1e-3, n_jobs=-1)),\n 'sampling_strategy': params['sampling_strategy'],\n }\n learner = Learner(learner_params)\n learner.setup_active_learner(X_train_init, y_screening_train_init, X_pool, y_screening_pool)\n\n params.update({'learner': learner})\n SAL = ScreeningActiveLearner(params)\n # SAL.init_stat() # initialize statistic for predicates, uncomment if use predicate selection feature\n\n return SAL\n\n\ndef compute_mean_std(df):\n columns_mean = [c + '_mean' for c in df.columns]\n columns_median = [c + '_median' for c in df.columns]\n columns_std = [c + '_std' for c in df.columns]\n old_columns = df.columns.values\n df_mean = df.mean().rename(dict(zip(old_columns, columns_mean)))\n df_std = df.std().rename(dict(zip(old_columns, columns_std)))\n df_median = df.median().rename(dict(zip(old_columns, columns_median)))\n\n return pd.concat([df_mean, df_std, df_median])\n","sub_path":"scopeAL_and_SMR/src/experiment_handler.py","file_name":"experiment_handler.py","file_ext":"py","file_size_in_byte":12264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"391917902","text":"import math\n\nclass Node:\n children = list()\n label = \"\"\n splitsOn = \"\"\n prediction = \"\"\n\n def __init__(self):\n self.children = list()\n self.label = \"\"\n self.splitsOn = \"\"\n self.prediction = \"\"\n\n\ndef ID3_Train(S, Attributes, Split, MaxDepth=None):\n splitFunc = None\n if Split == \"InfoGain\":\n splitFunc = InfoGain\n elif Split == \"MajorityError\":\n splitFunc = MajorityError\n elif Split == \"GiniIndex\":\n splitFunc = GiniIndex\n else:\n raise ValueError(\"Invalid Split function passed to ID3\")\n\n return id3_main(S, Attributes, splitFunc, MaxDepth, 0)\n\n\ndef id3_main(S, Attributes, Split, MaxDepth, depth):\n # check if max depth reached\n if depth == MaxDepth:\n return mostCommonLabelLeaf(S)\n\n # check if all labels are the same\n labelCheck = S[0][\"Label\"]\n allSame = True\n for s in S:\n if s[\"Label\"] != labelCheck:\n allSame = False\n break\n\n if allSame:\n # return a leaf node with the label\n leaf = Node()\n leaf.prediction = labelCheck\n return leaf\n\n # check if all attributes have been used\n if len(Attributes) == 0:\n return mostCommonLabelLeaf(S)\n\n # get attribute A that best splits S\n A = Split(S, Attributes)\n\n #create a root node for tree\n root = Node()\n root.splitsOn = A\n\n for v in Attributes[A]:\n Sv = getSv(S, A, v)\n\n if len(Sv) == 0:\n # add leaf node w/ most common value of Label in S\n leaf = mostCommonLabelLeaf(S, v)\n root.children.append(leaf)\n else:\n tempAttr = dict(Attributes)\n tempAttr.pop(A)\n subtree = id3_main(Sv, tempAttr, Split, MaxDepth, depth+1)\n subtree.label = v\n root.children.append(subtree)\n\n return root\n\n\ndef mostCommonLabelLeaf(S, v=None):\n labels = {}\n for s in S:\n label = s[\"Label\"]\n if label not in labels:\n labels[label] = 0\n labels[label] += 1\n\n maxNum = 0\n maxLabel = \"\"\n for label, num in labels.items():\n if num > maxNum:\n maxNum = num\n maxLabel = label\n\n leaf = Node()\n leaf.prediction = maxLabel\n leaf.label = v\n return leaf\n\n\ndef getSv(S, A, v):\n \"\"\"Gets a list of every s in S where s[A] has value v\"\"\"\n return [s for s in S if s[A] == v]\n\n\ndef values(Attributes, A):\n \"\"\"gets every value that attribute A takes\"\"\"\n return Attributes[A]\n\n\ndef MajorityError(S, Attributes):\n \"\"\"gets the attribute with the lowest majority error\"\"\"\n ME = ME_calc(S)\n\n maxGain = -1 # in case purity gain is 0 across the board\n maxAttr = \"\"\n for A in Attributes:\n gain = ME_helper(S, Attributes, A, ME)\n if gain > maxGain:\n maxGain = gain\n maxAttr = A\n\n return maxAttr\n\n\ndef ME_helper(S, Attributes, A, ME):\n \"\"\"\"\"\"\n newME = 0.0\n for v in Attributes[A]:\n # creates a list of examples where attr A has value v\n Sv = getSv(S, A, v)\n ratio = len(Sv)/float(len(S))\n me = ME_calc(Sv)\n newME += ratio * me\n\n return ME - newME\n\n\ndef ME_calc(S):\n \"\"\"gets the majority error of S\"\"\"\n if len(S) == 0:\n return 0\n\n labels = {}\n for s in S:\n label = s[\"Label\"]\n if label not in labels:\n labels[label] = 0\n labels[label] += 1\n\n numLabel = 0\n for label, num in labels.items():\n if num > numLabel:\n numLabel = num\n\n return 1 - numLabel/float(len(S))\n\n\ndef InfoGain(S, Attributes):\n \"\"\"gets the attribute with the best information gain\"\"\"\n entropy = ent_calc(S)\n\n maxInfo = -1\n maxAttr = \"\"\n for A in Attributes:\n infoGain = infohelper(S, Attributes, A, entropy)\n if infoGain > maxInfo:\n maxInfo = infoGain\n maxAttr = A\n\n return maxAttr\n\n\ndef infohelper(S, Attributes, A, entropy):\n \"\"\"calculates the info gain of a specific attribute\"\"\"\n newEnt = 0.0\n for v in Attributes[A]:\n # creates a list of examples where attr A has value v\n Sv = getSv(S, A, v)\n ratio = len(Sv)/float(len(S))\n ent = ent_calc(Sv)\n newEnt += ratio * ent\n\n return entropy - newEnt\n\n\ndef ent_calc(S):\n \"\"\"calculates the entropy of S\"\"\"\n if len(S) == 0:\n return 0\n\n labels = {}\n for s in S:\n label = s[\"Label\"]\n if label not in labels:\n labels[label] = 0\n labels[label] += 1\n\n entropy = 0.0\n norm = len(S) # normalizing value\n for (label, quant) in labels.items():\n ratio = quant/float(norm)\n entropy -= math.log((ratio), 2) * (ratio)\n\n return entropy\n\n\ndef GiniIndex(S, Attributes):\n \"\"\"gets the attribute with the lowest Gini Index\"\"\"\n initialGini = GI_calc(S)\n\n maxInfo = -1\n maxAttr = \"\"\n for A in Attributes:\n infoGain = ginihelper(S, Attributes, A, initialGini)\n if infoGain > maxInfo:\n maxInfo = infoGain\n maxAttr = A\n\n return maxAttr\n\n\ndef ginihelper(S, Attributes, A, gini):\n \"\"\"calculates the new gini index of splitting on a specific attribute\"\"\"\n newGI = 0.0\n for v in Attributes[A]:\n # creates a list of examples where attr A has value v\n Sv = getSv(S, A, v)\n ratio = len(Sv)/float(len(S))\n gi = GI_calc(Sv)\n newGI += ratio * gi\n\n return gini - newGI\n\n\ndef GI_calc(S):\n \"\"\"calculates the Gini Index of S\"\"\"\n if len(S) == 0:\n return 0\n\n labels = {}\n for s in S:\n label = s[\"Label\"]\n if label not in labels:\n labels[label] = 0\n labels[label] += 1\n\n gini = 1.0\n norm = len(S) # normalizing value\n for (label, quant) in labels.items():\n ratio = quant/float(norm)\n gini -= ratio**2\n\n return gini\n\n\ndef ID3_Test(Tree, S):\n wrong = 0\n for s in S:\n label = get_label(s, Tree)\n if label != s[\"Label\"]:\n wrong += 1\n return wrong/float(len(S))\n\n\ndef get_label(s, Tree):\n if Tree.prediction != \"\":\n return Tree.prediction\n \n newTree = None\n for node in Tree.children:\n if node.label == s[Tree.splitsOn]:\n newTree = node\n break\n\n return get_label(s, newTree)","sub_path":"DecisionTree/id3.py","file_name":"id3.py","file_ext":"py","file_size_in_byte":6268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"42266908","text":"from django.urls import path, include\r\nfrom django.conf.urls import url, include\r\nfrom apps.estructura.views import PrimerNivelList, PrimerNivelUpdate, SegundoNivelList, SegundoNivelUpdate, \\\r\n SegundoNivelCreate, SegundoNivelDelete, TercerNivelCreate, TercerNivelUpdate, TercerNivelList, TercerNivelDelete, \\\r\n CuartoNivelList, CuartoNivelCreate, CuartoNivelUpdate, CuartoNivelDelete\r\nfrom django.contrib.auth.decorators import login_required\r\n\r\nurlpatterns = [\r\n\r\n # url(r'listar', primernivel_list, name='PrimerNivelListar'),\r\n url('listar/1', login_required(PrimerNivelList.as_view()), name='PrimerNivelListar'),\r\n url('editar/1/(?P\\d+)/$', login_required(PrimerNivelUpdate.as_view()), name='PrimerNivelEditar'),\r\n\r\n url(r'crear/2', login_required(SegundoNivelCreate.as_view()), name='SegundoNivelCrear'),\r\n url(r'listar/2', login_required(SegundoNivelList.as_view()), name='SegundoNivelListar'),\r\n url('editar/2/(?P\\d+)/$', login_required(SegundoNivelUpdate.as_view()), name='SegundoNivelEditar'),\r\n url('eliminar/2/(?P\\d+)/$', login_required(SegundoNivelDelete.as_view()), name='SegundoNivelDelete'),\r\n\r\n url(r'crear/3', login_required(TercerNivelCreate.as_view()), name='TercerNivelCrear'),\r\n url(r'listar/3', login_required(TercerNivelList.as_view()), name='TercerNivelListar'),\r\n url('editar/3/(?P\\d+)/$', login_required(TercerNivelUpdate.as_view()), name='TercerNivelEditar'),\r\n url('eliminar/3/(?P\\d+)/$', login_required(TercerNivelDelete.as_view()), name='TercerNivelDelete'),\r\n\r\n url(r'crear/4', login_required(CuartoNivelCreate.as_view()), name='CuartoNivelCrear'),\r\n url(r'listar/4', login_required(CuartoNivelList.as_view()), name='CuartoNivelListar'),\r\n url('editar/4/(?P\\d+)/$', login_required(CuartoNivelUpdate.as_view()), name='CuartoNivelEditar'),\r\n url('eliminar/4/(?P\\d+)/$', login_required(CuartoNivelDelete.as_view()), name='CuartoNivelDelete'),\r\n\r\n #url('editar/2/(?P\\d+)/$', SegundoNivelUpdate, name='SegundoNivelEditar'),\r\n\r\n]","sub_path":"apps/estructura/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"59615228","text":"import mido\nimport matplotlib.pyplot as plt\n# import cv2\n# import re\n# import os\nimport argparse\n# import subprocess\nimport numpy as np\nfrom PIL import Image\n\n# extract information from midi file\ndef getTempo(MetaMsg):\n # further updates are needed for multiple tempo files\n for track in MetaMsg:\n for msg in track:\n if msg.type == 'set_tempo':\n tempo = msg.tempo\n try: tempo\n except NameError: tempo = 500000\n return tempo\n\n\ndef getScale(mid):\n numTracks = len(mid.tracks)\n durations = [0] * numTracks\n numChannel = set({})\n for index, track in enumerate(mid.tracks):\n for msg in track:\n durations[index] += msg.time\n if msg.type == 'note_on':\n numChannel.add(msg.channel)\n # print(len(numChannel))\n return list(numChannel), max(durations), 128\n\n\ndef getMetaMessage(mid):\n numTracks = len(mid.tracks)\n MetaMessage = [[]] * numTracks\n for index, track in enumerate(mid.tracks):\n for msg in track:\n if type(msg) == mido.midifiles.meta.MetaMessage:\n MetaMessage[index].append(msg)\n return MetaMessage\n\n\ndef midiMatrix(filepath):\n mid = mido.MidiFile(filepath)\n MetaMsg = getMetaMessage(mid)\n tempo = getTempo(MetaMsg)\n numChannel, length, width = getScale(mid)\n print('\\n\\n####The size of the midi matrix is {0}, {1}, {2}####\\n\\n'.format(numChannel, length, width))\n midiMat = np.zeros((len(numChannel), length, width), dtype = 'int8')\n for trackIndex, track in enumerate(mid.tracks):\n noteRegister = [-1] * 128\n currentTime = 0\n for msg in track:\n # print(msg)\n currentTime += msg.time\n if msg.type == 'note_on':\n if msg.velocity == 0:\n if noteRegister[msg.note] != -1:\n # print(currentTime - noteRegister[msg.note])\n for slot in [currentTime-x for x in range(currentTime-noteRegister[msg.note])]:\n midiMat[numChannel.index(msg.channel), slot-1, msg.note] = 1\n noteRegister[msg.note] = -1\n else:\n if noteRegister[msg.note] == -1:\n noteRegister[msg.note] = currentTime\n else:\n print(noteRegister[msg.note] == -1)\n for slot in [currentTime-x for x in range(currentTime-noteRegister[msg.note])]:\n midiMat[numChannel.index(msg.channel), slot-1, msg.note] = 1\n noteRegister[msg.note] = currentTime\n\n if msg.type == 'note_off':\n if noteRegister[msg.note] != -1:\n for slot in [currentTime-x for x in range(currentTime-noteRegister[msg.note])]:\n midiMat[numChannel.index(msg.channel), slot-1, msg.note] = 1\n noteRegister[msg.note] = -1\n\n print('the non-zero elements count {0} in the midi matrax\\n\\n'.format(np.count_nonzero(midiMat)))\n return midiMat, tempo, mid.ticks_per_beat\n\n\ndef printFrame(midiMat,filepath):\n im = Image.fromarray(np.flipud(np.transpose(midiMat))*25, mode ='L')\n im.save(filepath.replace('.mid', '.bmp'), 'bmp')\n\n\ndef melodyKernel(midiMat):\n melodyStart = 1780\n # melodyStart = 0\n while midiMat[:,melodyStart,:].sum()==0:\n melodyStart += 1\n melodyEnd = melodyStart\n print('melody starts at {}'.format(melodyEnd))\n while midiMat[:,melodyEnd,:].sum()<=10:\n melodyEnd += 1\n print('melody ends at {}'.format(melodyEnd))\n melodyBlock = midiMat[:,melodyStart: melodyEnd,:]\n # print(melodyBlock.amax)\n for chann in melodyBlock:\n if chann.sum() > 100:\n melody = chann\n if_note = melody.sum(axis=0)\n top = 0\n bottom = 127\n while if_note[top] == 0:\n top += 1\n while if_note[bottom] == 0:\n bottom -= 1\n # get the index of 1 so the upper limit and the botton limit can be set\n kernel = melody[:,top:bottom+1 ]\n print(kernel)\n print('bottom is {}, top is {}'.format(bottom, top))\n bias = np.ones((np.size(kernel,0),np.size(kernel,1)),dtype = 'int8')\n melody = kernel *2 - bias*10\n return melody, (melody*kernel).sum()\n\n\ndef convolutionMap(midiMat, melodyKernel):\n width_midimat = np.size(midiMat, 2)\n width_kernel = np.size(melodyKernel, 1)\n print(width_kernel)\n length_midimat = np.size(midiMat, 1)\n length_kernel = np.size(melodyKernel, 0)\n conMap = np.empty((np.size(midiMat,0), length_midimat-length_kernel, width_midimat-width_kernel), dtype = 'int32')\n for i in range(np.size(conMap,0)):\n for j in range(np.size(conMap,1)):\n for k in range(np.size(conMap,2)):\n # if j == 0 and k ==15:\n # print(np.size(midiMat[j:j+length_kernel,k:k+width_kernel],1))\n # print((melodyKernel*midiMat[j:j+length_kernel,k:k+width_kernel]).sum())\n conMap[i,j,k] = (melodyKernel*midiMat[i,j:j+length_kernel,k:k+width_kernel]).sum()\n return conMap\n\n\ndef findPeak(map, threshold):\n peakIndex = []\n for i in range(np.size(map,0)):\n for j in range(np.size(map,1)-1):\n for k in range(np.size(map,2)):\n if map[i,j,k] > 2000:\n if map[i,j,k]>map[i,j,k-1] and map[i,j,k]>map[i,j,k+1] and map[i,j,k]>map[i,j-1,k] and map[i,j,k]>map[i,j+1,k]:\n peakIndex.append([i, j, k, map[i,j,k]])\n return peakIndex\n\n\ndef showfoundmelody(peakindex, midiMat, melodyKernel):\n labeledMat = np.amax(midiMat, axis=0)\n Ashape = np.array([[1,1,0,0,0],[0,1,1,0,0],[0,1,0,1,0],[1,1,1,1,1],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]])\n Bshape = np.array([[1,1,1,1,1],[1,0,1,0,1],[1,0,1,0,1],[0,1,0,1,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]])\n Cshape = np.array([[0,1,1,1,0],[1,0,0,0,1],[1,0,0,0,1],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]])\n Dshape = np.array([[1,1,1,1,1],[1,0,0,0,1],[0,1,1,1,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]])\n Eshape = np.array([[1,1,1,1,1],[1,0,1,0,1],[1,0,1,0,1],[1,0,1,0,1],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]])\n Fshape = np.array([[1,1,1,1,1],[0,0,1,0,1],[0,0,1,0,1],[0,0,1,0,1],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]])\n Gshape = np.array([[1,1,1,1,1],[1,0,0,0,1],[1,1,1,0,1],[0,0,0,0,1],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]])\n Asshape = np.array([[1,1,0,0,0],[0,1,1,0,0],[0,1,0,1,0],[1,1,1,1,1],[0,0,0,1,1],[0,0,1,0,0],[0,1,1,1,0],[0,0,1,0,0]])\n Bsshape = np.array([[1,1,1,1,1],[1,0,1,0,1],[1,0,1,0,1],[0,1,0,1,0],[0,0,0,1,1],[0,0,1,0,0],[0,1,1,1,0],[0,0,1,0,0]])\n Csshape = np.array([[0,1,1,1,0],[1,0,0,0,1],[1,0,0,0,1],[0,0,0,1,0],[0,0,0,1,1],[0,0,1,0,0],[0,1,1,1,0],[0,0,1,0,0]])\n Dsshape = np.array([[1,1,1,1,1],[1,0,0,0,1],[0,1,1,1,0],[0,0,0,0,0],[0,0,0,1,1],[0,0,1,0,0],[0,1,1,1,0],[0,0,1,0,0]])\n Esshape = np.array([[1,1,1,1,1],[1,0,1,0,1],[1,0,1,0,1],[1,0,1,0,1],[0,0,0,1,1],[0,0,1,0,0],[0,1,1,1,0],[0,0,1,0,0]])\n Fsshape = np.array([[1,1,1,1,1],[0,0,1,0,1],[0,0,1,0,1],[0,0,1,0,1],[0,0,0,1,1],[0,0,1,0,0],[0,1,1,1,0],[0,0,1,0,0]])\n Gsshape = np.array([[1,1,1,1,1],[1,0,0,0,1],[1,1,1,0,1],[0,0,0,0,1],[0,0,0,1,1],[0,0,1,0,0],[0,1,1,1,0],[0,0,1,0,0]])\n notes_translator=[Ashape,Asshape,Bshape,Cshape,Csshape,Dshape,Dsshape,Eshape,Fshape,Fsshape,Gshape,Gsshape]\n for peak in peakindex:\n notes = peak[2]+np.nonzero(midiMat[peak[0], peak[1]:peak[1]+np.size(melodyKernel, 0), peak[2]:peak[2]+np.size(melodyKernel, 1)])[1]\n notes = np.sort(np.array(list(set(notes))))\n the_note = (notes[0]-21) % 12\n major_or_minor = notes[2]- notes[1]\n # 1 -> minor, 2 -> major\n labeledMat[peak[1]:peak[1]+np.size(melodyKernel, 0), peak[2]-1] = 5\n labeledMat[peak[1]:peak[1]+np.size(melodyKernel, 0), peak[2]+np.size(melodyKernel, 1)] = 5\n labeledMat[peak[1], 0:peak[2]+np.size(melodyKernel, 1)] = 5\n labeledMat[peak[1]+np.size(melodyKernel, 0), peak[2]:peak[2]+np.size(melodyKernel, 1)] = 5\n the_label = notes_translator[the_note]\n if major_or_minor == 1:\n the_label[4,0:2] = 1\n labeledMat[peak[1]:peak[1]+5, 0:5] = the_label*5\n return labeledMat\n\ndef showplausiblemelody(peakindex, midiMat, melodyKernel):\n labeledMat = np.amax(midiMat, axis=0)\n Ashape = np.array([[1,1,0,0,0],[0,1,1,0,0],[0,1,0,1,0],[1,1,1,1,1],[0,0,0,0,0]])\n Bshape = np.array([[1,1,1,1,1],[1,0,1,0,1],[1,0,1,0,1],[0,1,0,1,0],[0,0,0,0,0]])\n Cshape = np.array([[0,1,1,1,0],[1,0,0,0,1],[1,0,0,0,1],[0,0,0,0,0],[0,0,0,0,0]])\n Dshape = np.array([[1,1,1,1,1],[1,0,0,0,1],[0,1,1,1,0],[0,0,0,0,0],[0,0,0,0,0]])\n Eshape = np.array([[1,1,1,1,1],[1,0,1,0,1],[1,0,1,0,1],[1,0,1,0,1],[0,0,0,0,0]])\n Fshape = np.array([[1,1,1,1,1],[0,0,1,0,1],[0,0,1,0,1],[0,0,1,0,1],[0,0,0,0,0]])\n Gshape = np.array([[1,1,1,1,1],[1,0,0,0,1],[1,1,1,0,1],[0,0,0,0,1],[0,0,0,0,0]])\n Asshape = np.array([[1,1,0,0,0],[0,1,1,0,0],[0,1,0,1,0],[1,1,1,1,1],[0,0,0,1,1]])\n Bsshape = np.array([[1,1,1,1,1],[1,0,1,0,1],[1,0,1,0,1],[0,1,0,1,0],[0,0,0,1,1]])\n Csshape = np.array([[0,1,1,1,0],[1,0,0,0,1],[1,0,0,0,1],[0,0,0,1,0],[0,0,0,1,1]])\n Dsshape = np.array([[1,1,1,1,1],[1,0,0,0,1],[0,1,1,1,0],[0,0,0,0,0],[0,0,0,1,1]])\n Esshape = np.array([[1,1,1,1,1],[1,0,1,0,1],[1,0,1,0,1],[1,0,1,0,1],[0,0,0,1,1]])\n Fsshape = np.array([[1,1,1,1,1],[0,0,1,0,1],[0,0,1,0,1],[0,0,1,0,1],[0,0,0,1,1]])\n Gsshape = np.array([[1,1,1,1,1],[1,0,0,0,1],[1,1,1,0,1],[0,0,0,0,1],[0,0,0,1,1]])\n notes_translator=[Ashape,Asshape,Bshape,Cshape,Csshape,Dshape,Dsshape,Eshape,Fshape,Fsshape,Gshape,Gsshape]\n for peak in peakindex:\n notes = peak[2]+np.nonzero(midiMat[peak[0], peak[1]:peak[1]+np.size(melodyKernel, 0), peak[2]:peak[2]+np.size(melodyKernel, 1)])[1]\n # notes = np.array(list(set(notes)))\n the_note = (notes[0]-21) % 12\n major_or_minor = 1\n # 1 -> minor, 2 -> major\n labeledMat[peak[1]:peak[1]+np.size(melodyKernel, 0), peak[2]-1] = 5\n labeledMat[peak[1]:peak[1]+np.size(melodyKernel, 0), peak[2]+np.size(melodyKernel, 1)] = 5\n labeledMat[peak[1], 0:peak[2]+np.size(melodyKernel, 1)] = 5\n labeledMat[peak[1]+np.size(melodyKernel, 0), peak[2]:peak[2]+np.size(melodyKernel, 1)] = 5\n the_label = notes_translator[the_note]\n if major_or_minor == 1:\n the_label[4,0:2] = 1\n labeledMat[peak[1]:peak[1]+5, 0:5] = the_label*5\n return labeledMat\n\n\ndef matWithLabel(peakindex, midiMat, melodyKernel):\n labeledMat = np.amax(midiMat, axis=0)\n for peak in peakindex:\n # threshold\n # print(np.size(melodyKernel,1))\n labeledMat[peak[1]:peak[1]+np.size(melodyKernel, 0), peak[2]-1] = 5\n labeledMat[peak[1]:peak[1]+np.size(melodyKernel, 0), peak[2]+np.size(melodyKernel, 1)] = 5\n labeledMat[peak[1], peak[2]:peak[2]+np.size(melodyKernel, 1)] = 5\n labeledMat[peak[1]+np.size(melodyKernel, 0), peak[2]:peak[2]+np.size(melodyKernel, 1)] = 5\n return labeledMat\n\n\ndef tenTimesShorter(mat):\n numChannel = np.size(mat, 0)\n length = np.size(mat, 1)\n width = np.size(mat, 2)\n newMat = np.empty((numChannel, length//10+1, width), dtype = 'int8')\n for i in range(np.size(newMat,0)):\n for j in range(np.size(newMat,1)):\n for k in range(np.size(newMat,2)):\n newMat[i,j,k] = mat[i,10*j:10*j+10, k].sum()\n return newMat\n\n\ndef showchords(midiMat, peaks):\n # notelist = ['A','A#','B','C','C#','D','D#','E','F','F#','G','G#']\n Ashape = np.array([[1,1,0,0,0],[0,1,1,0,0],[0,1,0,1,0],[1,1,1,1,1],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]])\n Bshape = np.array([[1,1,1,1,1],[1,0,1,0,1],[1,0,1,0,1],[0,1,0,1,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]])\n Cshape = np.array([[0,1,1,1,0],[1,0,0,0,1],[1,0,0,0,1],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]])\n Dshape = np.array([[1,1,1,1,1],[1,0,0,0,1],[0,1,1,1,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]])\n Eshape = np.array([[1,1,1,1,1],[1,0,1,0,1],[1,0,1,0,1],[1,0,1,0,1],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]])\n Fshape = np.array([[1,1,1,1,1],[0,0,1,0,1],[0,0,1,0,1],[0,0,1,0,1],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]])\n Gshape = np.array([[1,1,1,1,1],[1,0,0,0,1],[1,1,1,0,1],[0,0,0,0,1],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]])\n Asshape = np.array([[1,1,0,0,0],[0,1,1,0,0],[0,1,0,1,0],[1,1,1,1,1],[0,0,0,0,0],[0,0,1,0,0],[0,1,1,1,0],[0,0,1,0,0]])\n Bsshape = np.array([[1,1,1,1,1],[1,0,1,0,1],[1,0,1,0,1],[0,1,0,1,0],[0,0,0,0,0],[0,0,1,0,0],[0,1,1,1,0],[0,0,1,0,0]])\n Csshape = np.array([[0,1,1,1,0],[1,0,0,0,1],[1,0,0,0,1],[0,0,0,1,0],[0,0,0,0,0],[0,0,1,0,0],[0,1,1,1,0],[0,0,1,0,0]])\n Dsshape = np.array([[1,1,1,1,1],[1,0,0,0,1],[0,1,1,1,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,1,0,0],[0,1,1,1,0],[0,0,1,0,0]])\n Esshape = np.array([[1,1,1,1,1],[1,0,1,0,1],[1,0,1,0,1],[1,0,1,0,1],[0,0,0,0,0],[0,0,1,0,0],[0,1,1,1,0],[0,0,1,0,0]])\n Fsshape = np.array([[1,1,1,1,1],[0,0,1,0,1],[0,0,1,0,1],[0,0,1,0,1],[0,0,0,0,0],[0,0,1,0,0],[0,1,1,1,0],[0,0,1,0,0]])\n Gsshape = np.array([[1,1,1,1,1],[1,0,0,0,1],[1,1,1,0,1],[0,0,0,0,1],[0,0,0,0,0],[0,0,1,0,0],[0,1,1,1,0],[0,0,1,0,0]])\n notes_translator=[Ashape,Asshape,Bshape,Cshape,Csshape,Dshape,Dsshape,Eshape,Fshape,Fsshape,Gshape,Gsshape]\n chordMat = np.amax(midiMat, axis=0)\n chords = []\n print(peaks)\n # print(chordMat)\n for peak in peaks:\n # chords.append(np.nonzero(chordMat[peak[1]])[0])\n chords.append([peak[1], np.nonzero(chordMat[peak[1]+1])[0]])\n chordMat[peak[1]] += 5\n # print(chordMat[peak[1]:peak[1]+20])\n # for i in range(len(chords)):\n # chords[i] = (chords[i] - 21) % 12\n # print(chordMat)\n for i in chords:\n i[1] = (i[1]-21)%12\n for chord in chords:\n # for each in chord[1]:\n # rootnote = each\n # rootnote = chord[0]\n # the_label = notes_translator[rootnote]\n # if (rootnote+3-21)%12 in chord[1]:\n # print('minor')\n # if (rootnote+4-21)%12 in chord[1]:\n # print('major')\n chord[1] = list(set(list(chord[1])))\n for i in range(len(chord[1])):\n chordMat[chord[0]+1:chord[0]+9, 6*i:6*i+5] = notes_translator[chord[1][i]]*5\n return chordMat\n\n # chordsnote = []\n # for i in chords:\n # buffer = []\n # for j in i:\n # buffer.append(notelist[j])\n # buffer = list(set(buffer))\n # chordsnote.append([buffer])\n # print(chordsnote)\n\n # for i,\n\n# def translateNote(melodyKernel, peaks):\n# notes = []\n# note = np.nonzero(melodyKernel > 0)\n# print(note[1])\n# for peak in peaks:\n# if peak[2] > 2000:\n# melodyNote = set({})\n# for key in note[1]:\n# melodyNote.add(peak[1]+key)\n# notes.append(list(melodyNote))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='turn a midi file in to a graph')\n parser.add_argument('midi_file', nargs='?', help = 'path to midi file', default = 'IMSLP211238-WIMA.3540-1047(I)Sco.mid')\n parser.add_argument('whether_video', nargs='?', help = 'whether to output video', default = 'No')\n args = parser.parse_args()\n # end of -- listening to the parameters\n\n np.set_printoptions(threshold=np.inf)\n np.set_printoptions(linewidth=np.inf)\n # end of -- set print options for matrix # print(midikernel)\n # print(midiMat.sum(axis=0))\n\n spf = 1\n # this is second per frame\n\n try:\n midiMat = np.load(args.midi_file.replace('.mid', '.npy'))\n with open(args.midi_file.replace('.mid', '.txt'), 'r') as file:\n content = file.readlines()\n tempo = int(content[0].strip())\n ticks_per_beat = int(content[1])\n except FileNotFoundError:\n midiMat, tempo, ticks_per_beat = midiMatrix(args.midi_file)\n with open(args.midi_file.replace('.mid', '.txt'), 'w') as file:\n file.write(str(tempo))\n file.write('\\n')\n file.write(str(ticks_per_beat))\n np.save(args.midi_file.replace('.mid', '.npy'), midiMat)\n\n midiMat = tenTimesShorter(midiMat)\n # for chann in midiMat:\n # print(chann)\n print(np.size(midiMat,1))\n print(np.size(midiMat,1))\n midikernel, threshold = melodyKernel(midiMat)\n print(threshold)\n threshold = 1*threshold/3\n # print(midikernel)\n # print(midiMat.sum(axis=0))\n try:\n conMap = np.load(args.midi_file.replace('.mid', '_con.npy'))\n except FileNotFoundError:\n conMap = convolutionMap(midiMat,midikernel)\n np.save(args.midi_file.replace('.mid', '_con.npy'), conMap)\n # print(conMap[0])\n # # print(conMap)\n # # print(conMap)\n peaks = findPeak(conMap, threshold)\n print(peaks)\n chordMat = showchords(midiMat, peaks)\n printFrame(chordMat, args.midi_file)\n # showchords(midiMat, peaks)\n # labeledMat = matWithLabel(peaks, midiMat, midikernel)\n\n # print(np.size(midiMat.sum(axis=0),1))\n # labeledMat = showplausiblemelody(peaks, midiMat, midikernel)\n # labeledMat is a 2D array\n # printFrame(labeledMat, args.midi_file)\n # print(labeledMat)\n # showfoundmelody(peaks, midiMat, midikernel)\n","sub_path":"utils/chord.py","file_name":"chord.py","file_ext":"py","file_size_in_byte":17371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"494050358","text":"import random\nimport sys\nimport traceback\nimport battlecode as bc\nfrom collections import deque\nfrom .GraphNode import GraphNode\n\n# Given a robot and destination, determines the best route to take\n# Returns an array of directions to the calling robot\n# Robot will follow the given directions until it determines that it needs to recalculate its path\n# This is far more efficient than running Pathfinding every turn and more adaptive than \\\n# running it once only\n# May implement multiple pathfinding methods and determine which to use based upon what's \\\n# needed or the distance\nclass PathfindingController:\n\n\tdef __init__(self, gameController, mapController):\n\t\tself.gameController = gameController\n\t\tself.mapController = mapController\n\t\t#Possible directions, only using 4 to make it alittle simpler\n\t\tself.Directions = [bc.Direction.North, bc.Direction.East, bc.Direction.South, bc.Direction.West]\n\t\t#The nodes that are blocked either by map obstacles \n\t\tself.earthBlockedNodes = []\n\n\tdef FindPathTo(self, planet, currentLocation, destination):\n\t\t#First step is to find all of the blocked nodes on the map\n\t\tself.earthBlockedNodes = self.blockEarthNodes()\n\t\t#create the path object that will be returned\n\t\tpath = []\n\t\t#create the explored object that will hold all of the nodes we have explored so far\n\t\texplored = []\n\t\t#create the frontier object that will hold all of the nodes we have found but not explored so far\n\t\tfrontier = deque([])\n\t\t#set the starting location node\n\t\tstartingLocation = self.mapController.GetNode(planet, currentLocation.x, currentLocation.y)\n\t\t#set the goal location, where we want to get to\n\t\tendingLocation = self.mapController.GetNode(planet, destination.x, destination.y)\n\t\t#create a starting GraphNode that holds the starting location and has no parent and no action\n\t\tnode = GraphNode(startingLocation, None, None)\n\t\t#creates the ending GraphNode\n\t\tendNode = GraphNode(endingLocation, None, None)\n\t\t#Create the list of nodes that will be blocked by units\n\t\tblockedLocations = []\n\t\t#Get all visible units on the map\n\t\tunits = self.gameController.units()\n\t\t#Interate through the units\n\t\tfor unit in units:\n\t\t\tunitMapLoc = unit.location.map_location()\n\t\t\t#Added nodes with units to the list of blocked nodes\n\t\t\tblockedLocations.append(self.mapController.GetNode(unitMapLoc.planet, unitMapLoc.x, unitMapLoc.y))\n\t\t#add the starting node to the frontier so we know where to start from\n\t\tfrontier.append(node)\n\t\twhile True:\n\t\t\t#check if the frontier is empty if it is no path was found to the goal and we need to break out\n\t\t\tif len(frontier) == 0:\n\t\t\t\treturn\n\t\t\telse:\n\t\t\t\t#using popleft from the frontier deque to get the first node that was push in \n\t\t\t\tnode = frontier.popleft()\n\t\t\t#Take the node we just popped out of the frontier and call the explore method with it\n\t\t\tnewNodes = self.Explore(planet, node)\n\t\t\t#Add the current node to the explored nodes so we don't explore it again\n\t\t\texplored.append(node.room)\n\t\t\t#For the newly discovered nodes check to see if they have already been explored, \n\t\t\t# are ready in the frontier, are blocked if not then add them to the frontier \n\t\t\tfor nodes in newNodes:\n\t\t\t\t#if it is already explored do nothing\n\t\t\t\tif self.AlreadyExplored(nodes, explored):\n\t\t\t\t\tpass\n\t\t\t\telse:\n\t\t\t\t\t#check if it is already in the frontier if so do nothing\n\t\t\t\t\tif self.AlreadyFrontier(nodes, frontier):\n\t\t\t\t\t\t#check if node is open\n\t\t\t\t\t\tif self.IsNodeOpen(nodes, blockedLocations):\n\t\t\t\t\t\t\t#if the node is not explored, in the frontier, or blocked add it to the frontier\n\t\t\t\t\t\t\tfrontier.append(nodes)\n\t\t\t#If the current node is the room we are looking for break out we are done\n\t\t\tif node.room == endNode.room:\n\t\t\t\tbreak\n\t\t#once we have found the goal node we need to go back through all of the nodes and record the actions that go us to the goal node\n\t\twhile node.Parent is not None:\n\t\t\t#Append the node action, the direction we went to get to this node to the path\n\t\t\tpath.append(node.Action)\n\t\t\t#Set the node to be the parent node, once we reach a node with no parent we know we are at the start node\n\t\t\tnode = node.Parent\n\t\tif path is None:\n\t\t\t#print(\"no path found\")\n\t\t\tpass\n\t\t#print(path)\n\t\t#return the path to the calling method \n\t\treturn path\n\n\tdef Explore (self, planet, node):\n\t\t#Creating the discovered object to hold newly discovered nodes \n\t\tdiscovered = []\n\t\t#Interate through the directions to find new nodes\n\t\tfor direction in self.Directions:\n\t\t\t#for each direction we are going to transition to the node in that direction if it exist and isn't blocked\n\t\t\tnewNode = self.Transition(planet, node , direction)\n\t\t\t#if there node exist add it to the discovered object to be returned once we have went through all of the directions\n\t\t\tif newNode is not None:\n\t\t\t\tdiscovered.append(newNode)\n\t\t#return the discovered nodes \n\t\treturn discovered\n\n\tdef Transition(self, planet, node, direction):\n\t\tcurrentnode = node\n\t\t#Check which direction we are going and transition to that node if it exist\n\t\tif direction == bc.Direction.North:\n\t\t\tnewNode = self.mapController.GetNode(planet, currentnode.room[\"x\"], currentnode.room[\"y\"] + 1)\n\t\telif direction == bc.Direction.East:\n\t\t\tnewNode = self.mapController.GetNode(planet, currentnode.room[\"x\"] + 1, currentnode.room[\"y\"])\n\t\telif direction == bc.Direction.South:\n\t\t\tnewNode = self.mapController.GetNode(planet, currentnode.room[\"x\"], currentnode.room[\"y\"] - 1)\n\t\telif direction == bc.Direction.West:\n\t\t\tnewNode = self.mapController.GetNode(planet, currentnode.room[\"x\"] - 1, currentnode.room[\"y\"])\n\t\tnewRoom = None\n\t\t#if the node exist create a new Graphnode with the node, its parent node, and the action we took to get here\n\t\tif (newNode is not None):\n\t\t\tnewRoom = GraphNode(newNode, node, direction)\n\t\t#return the new GraphNode \n\t\treturn newRoom\n\t\t\n\tdef AlreadyExplored(self, node, explored):\n\t\tisExplored = False\n\t\t#Interate through the explored nodes to see if the current node is there if it is return true\n\t\tfor item in explored:\n\t\t\tif node.room[\"hash\"] == item[\"hash\"]:\n\t\t\t\tisExplored = True\n\t\t\t\tbreak\n\t\treturn isExplored\n\n\tdef AlreadyFrontier(self, node, frontier):\n\t\tnotInFrontier = True \n\t\t#Interate through the frontier to see if the current node is there if it is return true\n\t\tfor item in frontier:\n\t\t\tif node.room[\"hash\"] == item.room[\"hash\"]:\n\t\t\t\tnotInFrontier = False\n\t\t\t\tbreak\n\t\treturn notInFrontier\n\n\tdef IsNodeOpen(self, node, blockedLocations):\n\t\t#default node is open to true\n\t\tnodeOpen = True\n\t\t#interate through the nodes that are blocked on the map\n\t\tfor nodes in self.earthBlockedNodes:\n\t\t\t#the room[\"hash\"] is a unique hash of the x and y coordantes so we can check and see if we are looking at the same node easily\n\t\t\tif node.room[\"hash\"] == nodes[\"hash\"] :\n\t\t\t\t#if the node is in the earthblockednodes return false because it a blocked node\n\t\t\t\treturn False\n\t\tfor nodes in blockedLocations:\n\t\t\t#if the node is in the blocked locations return false because the node is currently blocked by a robot or structure\n\t\t\tif node.room[\"hash\"] == nodes[\"hash\"] :\n\t\t\t\treturn False\n\t\t#return True if node is not in the earthblocked or the robot blocked list\n\t\treturn nodeOpen\n\n\tdef blockEarthNodes(self):\n\t\tblockedNodes = []\n\t\t#the map is a 2d array of nodes you have to interate through all of the Y coordinates for each of the X coordinates\n\t\tfor xNodes in self.mapController.earth_map:\n\t\t\tfor node in xNodes:\n\t\t\t\t#check if the node is passable\n\t\t\t\tif not node[\"isPassable\"]:\n\t\t\t\t\t#if not add it to the blocked nodes\n\t\t\t\t\tblockedNodes.append(node)\n\t\t#return the list of blocked nodes\n\t\treturn blockedNodes\n","sub_path":"bc18-scaffold/OnshoreBattlebot2018/Controllers/PathfindingController.py","file_name":"PathfindingController.py","file_ext":"py","file_size_in_byte":7532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"261663641","text":"'''\n File name: wrapper.py\n Authors: Brian Barrows, Zachary Fisher, Michael Woc\n Date created: 10/31/2019\n'''\n\n'''\n File clarification:\n This is the test script to execute all of the \".py\" files in this folder.\n Adjust input images here if needed. \n \n'''\n\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nfrom corner_detector import *\nfrom anms import *\nfrom feat_desc import *\nfrom feat_match import *\nfrom ransac_est_homography import *\nfrom mymosaic import *\nfrom helper import *\n\n# Import Images\nimgL = cv2.imread('bubble_left.jpg')\nimgM = cv2.imread('bubble_middle.jpg')\nimgR = cv2.imread('bubble_right.jpg')\n\n# Image Resizing\nscale_percent = 640/imgL.shape[1]*100 # percent of original size\nwidth = int(imgL.shape[1] * scale_percent / 100)\nheight = int(imgL.shape[0] * scale_percent / 100)\ndim = (width, height)\nimgL = cv2.resize(imgL, dim, interpolation = cv2.INTER_AREA)\nimgM = cv2.resize(imgM, dim, interpolation = cv2.INTER_AREA)\nimgR = cv2.resize(imgR, dim, interpolation = cv2.INTER_AREA)\n\n# Grayscale\ngrayL = cv2.cvtColor(imgL, cv2.COLOR_BGR2GRAY)\ngrayM = cv2.cvtColor(imgM, cv2.COLOR_BGR2GRAY)\ngrayR = cv2.cvtColor(imgR, cv2.COLOR_BGR2GRAY)\n\nprint(\"preprocessing complete\")\n\n#%% Feature Detection\n\n# run function\ncimgL = corner_detector(grayL)\ncimgM = corner_detector(grayM)\ncimgR = corner_detector(grayR)\n\n# plot results\n#left\ncd_L = plt.imshow(cimgL,cmap='gray')\nplt.show()\n# middle\ncd_M = plt.imshow(cimgM,cmap='gray')\nplt.show()\n# right\ncd_R = plt.imshow(cimgR,cmap='gray')\nplt.show()\n\nprint(\"corner detector complete\")\n\n#%% ANMS\n\n# call functions\nmax_pts = 300\nxL,yL,rmaxL = anms(cimgL, max_pts)\nxM,yM,rmaxM = anms(cimgM, max_pts)\nxR,yR,rmaxR = anms(cimgR, max_pts)\n\n# ignore features near edge\nxL,yL = ignore_edge_pts(xL,yL,height,width,20)\nxM,yM = ignore_edge_pts(xM,yM,height,width,20)\nxR,yR = ignore_edge_pts(xR,yR,height,width,20)\n\n# plot results\n# left\nanmsL = plt.imshow(imgL[:,:,[2,1,0]])\nplt.scatter(x=xL, y=yL, c='r', s=5)\nplt.show()\n# middle\nanmsM = plt.imshow(imgM[:,:,[2,1,0]])\nplt.scatter(x=xM, y=yM, c='r', s=5)\nplt.show()\n# right\nanmsR = plt.imshow(imgR[:,:,[2,1,0]])\nplt.scatter(x=xR, y=yR, c='r', s=5)\nplt.show()\n\nprint(\"anms complete\")\n\n#%% Feature Descriptors\n\ndescsLR = feat_desc(imgL[:,:,0], xL, yL)\ndescsLG = feat_desc(imgL[:,:,1], xL, yL)\ndescsLB = feat_desc(imgL[:,:,2], xL, yL)\ndescsL = np.concatenate((descsLR,descsLG,descsLB),axis=0)\ndescsMR = feat_desc(imgM[:,:,0], xM, yM)\ndescsMG = feat_desc(imgM[:,:,1], xM, yM)\ndescsMB = feat_desc(imgM[:,:,2], xM, yM)\ndescsM = np.concatenate((descsMR,descsMG,descsMB),axis=0)\ndescsRR = feat_desc(imgR[:,:,0], xR, yR)\ndescsRG = feat_desc(imgR[:,:,1], xR, yR)\ndescsRB = feat_desc(imgR[:,:,2], xR, yR)\ndescsR = np.concatenate((descsRR,descsRG,descsRB),axis=0)\n\nprint(\"decriptors complete\")\n\n#%% Feature Matching\n\n# Call function\nmatchL = feat_match(descsM, descsL)\nmatchR = feat_match(descsM, descsR)\n\n# Get feature coordiantes\nx1ML = []\ny1ML = []\nx2L = []\ny2L = []\nx1MR = []\ny1MR = []\nx2R = []\ny2R = []\nfor i in range(len(matchL)):\n if (matchL[i] != -1):\n x1ML.append(xM[int(i)])\n y1ML.append(yM[int(i)])\n x2L.append(xL[int(matchL[i])])\n y2L.append(yL[int(matchL[i])])\n if (matchR[i] != -1):\n x1MR.append(xM[int(i)])\n y1MR.append(yM[int(i)])\n x2R.append(xR[int(matchR[i])])\n y2R.append(yR[int(matchR[i])])\n\n# Plot results\n# Left & middle\nplt.figure(figsize=(16,9))\ncorrespLM = plt.imshow(np.concatenate((imgL,imgM),axis=1)[:,:,[2,1,0]])\nplt.scatter(x=xL, y=yL, c='r', s=5)\nplt.scatter(x=xM+width, y=yM, c='r', s=5)\nfor i in range(len(x1ML)):\n plt.plot([x2L[i],x1ML[i]+width],[y2L[i],y1ML[i]],'-',linewidth=1)\nplt.show()\n# Middle & right\nplt.figure(figsize=(16,9))\ncorrespMR = plt.imshow(np.concatenate((imgM,imgR),axis=1)[:,:,[2,1,0]])\nplt.scatter(x=xM, y=yM, c='r', s=5)\nplt.scatter(x=xR+width, y=yR, c='r', s=5)\nfor i in range(len(x1MR)):\n plt.plot([x2R[i]+width,x1MR[i]],[y2R[i],y1MR[i]],'-',linewidth=1)\nplt.show()\n\n## one-by-one (left & middle)\n#for i in range(len(x1ML)):\n# print(\"left & middle #\" + str(i))\n# plt.figure(figsize=(16,9))\n# correspLM = plt.imshow(np.concatenate((imgL,imgM),axis=1)[:,:,[2,1,0]])\n# plt.scatter(x=xL, y=yL, c='r', s=5)\n# plt.scatter(x=xM+width, y=yM, c='r', s=5)\n# plt.plot([x2L[i],x1ML[i]+width],[y2L[i],y1ML[i]],'y-',linewidth=2)\n# plt.show()\n# print()\n#print(\"- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\")\n## one-by-one (middle & right)\n#for i in range(len(x1MR)):\n# print(\"middle and right #\" + str(i))\n# plt.figure(figsize=(16,9))\n# correspMR = plt.imshow(np.concatenate((imgM,imgR),axis=1)[:,:,[2,1,0]])\n# plt.scatter(x=xM, y=yM, c='r', s=5)\n# plt.scatter(x=xR+width, y=yR, c='r', s=5)\n# plt.plot([x2R[i]+width,x1MR[i]],[y2R[i],y1MR[i]],'y-',linewidth=2)\n# plt.show()\n# print()\n\nprint(\"feature matching complete\")\n\n#%% Random Sampling Consensus (RANSAC)\n\n# Call functions\nthreshL = 1\nthreshR = 1\nHL, inlier_indL = ransac_est_homography(x2L, y2L, x1ML, y1ML, threshL)\nHR, inlier_indR = ransac_est_homography(x2R, y2R, x1MR, y1MR, threshR)\n\n# Plot results\n# Left & middle\nplt.figure(figsize=(16,9))\ncorrespLM = plt.imshow(np.concatenate((imgL,imgM),axis=1)[:,:,[2,1,0]])\nplt.scatter(x=xL, y=yL, c='b', s=5)\nplt.scatter(x=xM+width, y=yM, c='b', s=5)\nfor i in range(len(x1ML)):\n if inlier_indL[i]==1:\n plt.plot([x2L[i],x1ML[i]+width],[y2L[i],y1ML[i]],'-',linewidth=1)\n plt.scatter(x=x2L[i], y=y2L[i], c='r', s=5)\n plt.scatter(x=x1ML[i]+width, y=y1ML[i], c='r', s=5)\nplt.show()\n# Middle & right\nplt.figure(figsize=(16,9))\ncorrespMR = plt.imshow(np.concatenate((imgM,imgR),axis=1)[:,:,[2,1,0]])\nplt.scatter(x=xM, y=yM, c='b', s=5)\nplt.scatter(x=xR+width, y=yR, c='b', s=5)\nfor i in range(len(x1MR)):\n if inlier_indR[i]==1:\n plt.plot([x2R[i]+width,x1MR[i]],[y2R[i],y1MR[i]],'-',linewidth=1)\n plt.scatter(x=x2R[i]+width, y=y2R[i], c='r', s=5)\n plt.scatter(x=x1MR[i], y=y1MR[i], c='r', s=5)\nplt.show()\n\n## one-by-one (left & middle)\n#count = 1\n#for i in range(len(x1ML)):\n# if inlier_indL[i]==1:\n# print(\"left & middle #\" + str(count))\n# plt.figure(figsize=(16,9))\n# correspLM = plt.imshow(np.concatenate((imgL,imgM),axis=1)[:,:,[2,1,0]])\n# plt.scatter(x=xL, y=yL, c='r', s=5)\n# plt.scatter(x=xM+width, y=yM, c='r', s=5)\n# plt.plot([x2L[i],x1ML[i]+width],[y2L[i],y1ML[i]],'y-',linewidth=2)\n# plt.show()\n# count += 1\n# print()\n#print(\"- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\")\n## one-by-one (middle & right)\n#count = 1\n#for i in range(len(x1MR)):\n# if inlier_indR[i]==1:\n# print(\"middle and right #\" + str(count))\n# plt.figure(figsize=(16,9))\n# correspMR = plt.imshow(np.concatenate((imgM,imgR),axis=1)[:,:,[2,1,0]])\n# plt.scatter(x=xM, y=yM, c='r', s=5)\n# plt.scatter(x=xR+width, y=yR, c='r', s=5)\n# plt.plot([x2R[i]+width,x1MR[i]],[y2R[i],y1MR[i]],'y-',linewidth=2)\n# plt.show()\n# count += 1\n# print()\n\nprint(\"HL:\")\nprint(HL)\nprint(\"HR:\")\nprint(HR)\nprint(\"ransac complete\")\n\n#%% Frame Mosaicing\n\n# Call function\nimg_mosaic = mymosaic(imgL,imgM,imgR,HL,HR)\nprint(\"mosaic complete\")\n\n# Show Mosaic\ncv2.namedWindow('Mosaic', cv2.WINDOW_NORMAL)\ncv2.resizeWindow('Mosaic', 1200, 400)\ncv2.imshow('Mosaic', img_mosaic.astype(np.uint8))\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"wrapper_bubble.py","file_name":"wrapper_bubble.py","file_ext":"py","file_size_in_byte":7487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"354361797","text":"# game.py\n# a basic rock paper scissors game in python\nfrom classes import Player, Roll\nfrom data_reader import read_rolls\nfrom random import choice\n\n\ndef print_header():\n print('\\n---------------------------------')\n print(' Rock Paper Scissors')\n print('---------------------------------')\n print()\n\n\ndef build_all_the_rolls():\n results = read_rolls()\n rolls = []\n for k, v in results.items():\n rolls.append(Roll(k, v[0], v[1]))\n return rolls\n\n\ndef get_players_name():\n name = input(\"What's your name? \")\n while name.isdigit():\n print(\"Names don't have numbers in them\")\n name = input(\"What's your name? \")\n return name\n\n\ndef game_loop(player1, player2, rolls):\n count = 0\n while count < 3:\n options = [roll.name for roll in rolls]\n p2_roll = choice(rolls)\n p1_roll = input(f\"\\nChoose your roll \\nYour options are {options} \")\n\n while p1_roll not in [roll.name for roll in rolls]:\n p1_roll = input(f\"Try again: \")\n\n for roll in rolls:\n if p1_roll == roll.name:\n p1_roll = roll\n\n outcome = p1_roll.can_defeat(p2_roll)\n\n print(f'You chose {p1_roll.name}. The computer chose {p2_roll.name}')\n\n if p1_roll == p2_roll:\n print(\"It's a tie!\")\n else:\n if outcome:\n print(f'{player1.name} wins the round!')\n player1.add_point()\n else:\n print(f'{player2.name} wins the round!')\n player2.add_point()\n\n if p1_roll != p2_roll:\n count += 1\n\n # Winner of the game\n if player1.get_points() == player2.get_points():\n print(\"\\nIt's a tie!\")\n else:\n if player1.get_points() > player2.get_points():\n print(f\"\\n{player1.name} wins with {player1.get_points()} points!\")\n else:\n print(f\"\\n{player2.name} wins with {player2.get_points()} points!\")\n\n\ndef main():\n print_header()\n rolls = build_all_the_rolls()\n\n name = get_players_name()\n\n player1 = Player(name)\n player2 = Player('The Computer')\n\n game_loop(player1, player2, rolls)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"days/13-15-text-games/rock_paper_scissors/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"117675767","text":"\"\"\"Test the contacts class\"\"\"\n\nfrom hubspyt import HubSpot\n\nAPI_KEY = 'demo'\n\ndef test_all():\n \"\"\"Test fetching all contacts\"\"\"\n\n hubspot = HubSpot(API_KEY)\n contacts = hubspot.contacts.all(count=20)\n length = len(contacts)\n\n assert length == 20\n\ndef test_contact_object():\n \"\"\"Test that a contact instance is given with each item\"\"\"\n\n hubspot = HubSpot(API_KEY)\n contacts = hubspot.contacts.all(count=2)\n\n contact = contacts[0]\n\n assert contact.vid is not None\n\ndef test_batch():\n \"\"\"Test that you can provide a list of contacts to be updated/created\"\"\"\n\n hubspot = HubSpot(API_KEY)\n contacts = hubspot.contacts.all(count=2)\n\n contact1 = contacts[0]\n contact2 = contacts[1]\n\n contact1.first_name = 'John'\n contact2.first_name = 'John'\n\n response = hubspot.contacts.batch_modify([contact1, contact2])\n\n assert response is True\n","sub_path":"tests/test_contacts.py","file_name":"test_contacts.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"455689217","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import annotations\n\nimport logging\nimport random\n\nimport networkx as nx\n\nlogger = logging.getLogger(__name__)\n\n\ndef shuffle_graph_edges(g: nx.Graph) -> nx.Graph:\n \"\"\"Shuffle the nodes in the graph.\"\"\"\n if not g.name:\n raise NameError('graph needs a name')\n\n import xswap\n\n edges = list(g.edges())\n\n permuted_edges, permutation_statistics = xswap.permute_edge_list(\n edges,\n allow_self_loops=False,\n allow_antiparallel=False,\n multiplier=10,\n )\n logger.info(f'permutation statistics: {permutation_statistics}')\n rv = nx.Graph(permuted_edges)\n rv.name = f'permuted {g.name}'\n return rv\n\ndef shuffle_graph_nodes(reference_graph: nx.Graph, g: nx.Graph) -> nx.Graph:\n _shuffled_nodes = list(reference_graph.nodes())\n random.shuffle(_shuffled_nodes)\n _mapping = dict(zip(reference_graph.nodes(), _shuffled_nodes))\n return nx.relabel_nodes(g, _mapping)\n","sub_path":"src/lpe/shufflers.py","file_name":"shufflers.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"314412291","text":"#import important packages\n\nfrom tkinter import *\nimport time\nfrom tkinter import font\nimport tkinter.messagebox as messagebox\nimport serial\nfrom time import sleep \nimport RPi.GPIO as GPIO\nimport board\nimport busio\nimport adafruit_bmp280\nimport ventilator_functions2 as mm\nimport board\nimport busio\nimport adafruit_bmp280\nimport datetime as dt\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n#Initialize Raspberry pi pins for solenoids\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\nGPIO.setup(17, GPIO.OUT) #inhale solenoid\nGPIO.setup(4, GPIO.OUT) #exhale solenoid\n\n# Initialize communication with sensor\ni2c = busio.I2C(board.SCL,board.SDA)\nsensor = adafruit_bmp280.Adafruit_BMP280_I2C(i2c)\n\n\n\nclass Window(Frame):\n\n\n def __init__(self, master=None):\n Frame.__init__(self, master)\n self.master = master\n self.init_window()\n\n\n\n#Create init_window\n def init_window(self):\n\n# Define title of master widget\n self.master.title(\"Ventilator Control\")\n\n\n# Allow the widget to take the full space of the root window\n self.pack(fill=BOTH, expand=2)\n \n# Create font family:\n Timestitle = font.Font(family=\"Myriad Pro\", size=30, weight='bold')\n Buttons = font.Font(family = 'Myriad Pro', size = 15)\n MainButtons = font.Font(family = 'Myriad Pro', size = 35, weight = 'bold')\n ButtonsLarger = font.Font(family = 'Myriad Pro', size = 30, weight = 'bold')\n Labels = font.Font(family = 'Myriad Pro', size = 12)\n \n#Create labels\n\n self.title = Label(root, text='The VentiVader', fg = 'Black', font = Timestitle )\n\n self.title.place(x=230,y=0)\n\n\n self.lvarie = Label(root,text = 'I/E ratio (1:x)', fg='Purple',\n font = Labels)\n self.lvarie.place(x=350, y=100)\n \n self.lvarie = Label(root,text = 'Hold time (s)', fg='Purple',\n font = Labels)\n self.lvarie.place(x=350, y=150)\n \n self.lvarbpm = Label(root,text = 'Respiration rate (BPM)', fg='Purple',\n font = Labels)\n self.lvarbpm.place(x=350, y=200)\n \n self.lvarVc = Label(root,text = 'Ventilation cycles (#)', fg='Green',\n font = Labels) \n self.lvarVc.place(x=350, y=250)\n\n\n#create entry variables\n\n \n varIE = Entry(root)\n varHt = Entry(root)\n varBPM = Entry(root) \n varVc = Entry(root)\n \n \n# Create figure for plotting\n x = []\n y = []\n func_id = None\n\n\n# Define functions\n \n #Function to constantly read pressure sensor data and plot in a new background window\n def read_data():\n global func_id\n plt.ion()\n new_value = int(round(sensor.pressure, 4))*1.02\n if new_value == '':\n pass\n else:\n y.append(new_value)\n x.append(dt.datetime.now().strftime('%H:%M:%S'))\n # Format plot\n plt.xticks(rotation=45, ha='right')\n plt.subplots_adjust(bottom=0.30)\n plt.title('Pressure data')\n plt.ylabel('Pressure (cm H2O)')\n plt.plot(x,y,'r-')\n plt.show()\n plt.pause(0.0001)\n func_id = root.after(100, read_data)\n \n #Function to ventilate by cylcing inhale and exhale solenoids as many times as given by ventilation cycles\n def ventilate():\n IE= varIE.get()\n ie = float(IE)\n BPM = varBPM.get()\n bpm = float(BPM)\n Ht = varHt.get()\n ht = float(Ht)\n Vc = varVc.get()\n vc = int(Vc)\n time = (60/bpm)*vc\n j= 1\n for j in range(1,vc+1):\n print('Breath {}:'.format(j))\n mm.breathe(ie,bpm,ht)\n # Print critical information\n print('Breaths per minute: {} bpm'.format(bpm))\n print('I/E ratio: {}'.format(ie))\n print('Total time: {} s'.format(time))\n\n #Function to clean GPIO pin assignments after ventilation\n def clean():\n GPIO.cleanup()\n \n #Function to close pressure sensor data plot\n def closeplot():\n global func_id\n root.after_cancel(func_id)\n plt.close()\n global x,y\n del x[:]\n del y[:]\n \n\n# Create buttons\n\n\n ventilatorButton = Button(self, text='Ventilate', font = MainButtons,\n command = ventilate)\n cleanButton = Button(self, text='Clean', font = ButtonsLarger,\n command = clean)\n exitButton = Button(self, text='Exit', font = ButtonsLarger,\n command = root.destroy)\n plotButton = Button(self, text = 'Plot', font = Buttons, command = read_data)\n closeplotButton = Button(self, text = 'Close Plot', font = Buttons, command = closeplot)\n\n# Place the buttons\n varIE.place(x=550,y=100)\n varHt.place(x=550,y=150)\n varBPM.place(x=550, y=200)\n varVc.place(x=550, y=250)\n\n \n plotButton.place(x = 50, y = 280)\n closeplotButton.place(x = 50, y = 330)\n \n ventilatorButton.place(x = 250, y = 400)\n \n \n \n exitButton.place(x = 600, y = 500)\n cleanButton.place(x=50, y=500)\n\n\n\nglobal root\n\nroot = Tk()\n\n#size of the window\nroot.geometry(\"800x800\")\n\napp = Window(root)\nroot.mainloop()\n\n","sub_path":"ventilator_gui2.py","file_name":"ventilator_gui2.py","file_ext":"py","file_size_in_byte":5605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"115409158","text":"# -*- mode: python; coding: utf-8 -*-\n# Copyright 2013-2022 Chris Beaumont and the AAS WorldWide Telescope project\n# Licensed under the MIT License.\n\n\"\"\"Computations for the TOAST projection scheme and tile pyramid format.\n\nFor all TOAST maps, the north pole is in the dead center of the virtual image\nsquare, the south pole is at all four of its corners, and the equator is a\ndiamond connecting the midpoints of the four sides of the square. (See Figure 3\nof McGlynn+ 2019, DOI:10.3847/1538-4365/aaf79e).\n\nFor TOAST maps of the sky, the line of RA (lon) = 0 in the northern hemisphere\nextends from the center of the square to the right, as in the Figure 3 mentioned\nabove. The RA = 90 line goes from the center up, and so on counter-clockwise\naround the square.\n\nFor TOAST planetary maps, the lon = 0 line in the northern hemisphere extends\nfrom the center of the square to the *left*. The lon = 90 line extends\ndownwards, and increasing longitude results in counter-clockwise motion around\nthe square as for sky maps. In other words, the longitudinal orientation is\nrotated by 180 degrees.\n\n\"\"\"\n\n__all__ = \"\"\"\ncount_tiles_matching_filter\ncreate_single_tile\ngenerate_tiles\ngenerate_tiles_filtered\nsample_layer\nsample_layer_filtered\nTile\nToastCoordinateSystem\nToastSampler\ntoast_pixel_for_point\ntoast_tile_area\ntoast_tile_for_point\ntoast_tile_get_coords\n\"\"\".split()\n\nfrom collections import namedtuple\nfrom enum import Enum\nimport numpy as np\n\nfrom ._libtoasty import subsample, mid\nfrom .image import Image\nfrom .progress import progress_bar\nfrom .pyramid import Pos, tiles_at_depth\n\nHALFPI = 0.5 * np.pi\nTHREEHALFPI = 1.5 * np.pi\nTWOPI = 2 * np.pi\n\n\ndef _arclength(lat1, lon1, lat2, lon2):\n \"\"\"Compute the length of an arc along the great circle defined by spherical\n latitude and longitude coordinates. Inputs and return value are all in\n radians.\n\n \"\"\"\n c = np.sin(lat1) * np.sin(lat2) + np.cos(lon1 - lon2) * np.cos(lat1) * np.cos(lat2)\n return np.arccos(c)\n\n\ndef _spherical_triangle_area(lat1, lon1, lat2, lon2, lat3, lon3):\n \"\"\"Compute the area of the specified spherical triangle in steradians. Inputs\n are in radians. From https://math.stackexchange.com/a/66731 . My initial\n implementation used unit vectors on the sphere instead of latitudes and\n longitudes; there might be a faster way to do things in lat/lon land.\n\n \"\"\"\n c = _arclength(lat1, lon1, lat2, lon2)\n a = _arclength(lat2, lon2, lat3, lon3)\n b = _arclength(lat3, lon3, lat1, lon1)\n s = 0.5 * (a + b + c)\n tane4 = np.sqrt(\n np.tan(0.5 * s)\n * np.tan(0.5 * (s - a))\n * np.tan(0.5 * (s - b))\n * np.tan(0.5 * (s - c))\n )\n e = 4 * np.arctan(tane4)\n return e\n\n\nclass ToastCoordinateSystem(Enum):\n \"\"\"\n Different TOAST coordinate systems that are in use.\n \"\"\"\n\n ASTRONOMICAL = \"astronomical\"\n \"\"\"The default TOAST coordinate system, where the ``lat = lon = 0`` point\n lies at the middle right edge of the TOAST projection square.\"\"\"\n\n PLANETARY = \"planetary\"\n \"\"\"The planetary TOAST coordinate system. This is rotated 180 degrees in\n longitude from the astronomical system, such that the ``lat = lon = 0``\n point lies at the middle left edge of the TOAST projection square.\"\"\"\n\n\nTile = namedtuple(\"Tile\", \"pos corners increasing\")\n\n_level1_astronomical_lonlats = np.radians(\n [\n [(0, -90), (90, 0), (0, 90), (180, 0)],\n [(90, 0), (0, -90), (0, 0), (0, 90)],\n [(180, 0), (0, 90), (270, 0), (0, -90)],\n [(0, 90), (0, 0), (0, -90), (270, 0)],\n ]\n)\n_level1_astronomical_lonlats.flags.writeable = False\n\n\ndef _create_level1_tiles(coordsys):\n lonlats = _level1_astronomical_lonlats\n\n if coordsys == ToastCoordinateSystem.PLANETARY:\n lonlats = lonlats.copy()\n lonlats[..., 0] = (lonlats[..., 0] + np.pi) % TWOPI\n\n return [\n Tile(Pos(n=1, x=0, y=0), lonlats[0], True),\n Tile(Pos(n=1, x=1, y=0), lonlats[1], False),\n Tile(Pos(n=1, x=0, y=1), lonlats[2], False),\n Tile(Pos(n=1, x=1, y=1), lonlats[3], True),\n ]\n\n\ndef toast_tile_area(tile):\n \"\"\"Calculate the area of a TOAST tile in steradians.\n\n Parameters\n ----------\n tile : :class:`Tile`\n A TOAST tile.\n\n Returns\n -------\n The area of the tile in steradians.\n\n Notes\n -----\n This computation is not very fast.\n\n \"\"\"\n ul, ur, lr, ll = tile.corners\n\n if tile.increasing:\n a1 = _spherical_triangle_area(ul[1], ul[0], ur[1], ur[0], ll[1], ll[0])\n a2 = _spherical_triangle_area(ur[1], ur[0], lr[1], lr[0], ll[1], ll[0])\n else:\n a1 = _spherical_triangle_area(ul[1], ul[0], ur[1], ur[0], lr[1], lr[0])\n a2 = _spherical_triangle_area(ul[1], ul[0], ll[1], ll[0], lr[1], lr[0])\n\n return a1 + a2\n\n\ndef _equ_to_xyz(lat, lon):\n \"\"\"\n Convert equatorial to cartesian coordinates. Lat and lon are in radians.\n Output is on the unit sphere.\n\n \"\"\"\n clat = np.cos(lat)\n return np.array(\n [\n np.cos(lon) * clat,\n np.sin(lat),\n np.sin(lon) * clat,\n ]\n )\n\n\ndef _left_of_half_space_score(point_a, point_b, test_point):\n \"\"\"\n A variant of WWT Window's IsLeftOfHalfSpace.\n\n When determining which tile a given RA/Dec lives in, it is inevitable that\n rounding errors can make seem that certain coordinates are not contained by\n *any* tile. Unlike IsLeftOfHalf space, which returns a boolean based on the\n dot product calculated here, we return a number <= 0, where 0 indicates that\n the test point is *definitely* in the left half-space defined by the A and B\n points. Negative values tell us how far into the right space the point is;\n when rounding errors are biting us, that value might be something like\n -1e-16.\n\n \"\"\"\n return min(np.dot(np.cross(point_a, point_b), test_point), 0)\n\n\ndef _toast_tile_containment_score(tile, lat, lon):\n \"\"\"\n Assess whether a TOAST tile contains a given point.\n\n Parameters\n ----------\n tile : :class:`Tile`\n A TOAST tile\n lat : number\n The latitude (declination) of the point, in radians.\n lon : number\n The longitude (RA) of the point, in radians. This value must\n have already been normalied to lie within the range [0, 2pi]\n (inclusive on both ends.)\n\n Returns\n -------\n A floating-point \"containment score\" number. If this number is zero, the\n point definitely lies within the tile. Otherwise, the number will be\n negative, with more negative values indicating a greater distance from the\n point to the nearest tile boundary. Due to inevitable roundoff errors, there\n are situations where, given a certain point and tile, the point \"should\" be\n contained in the tile, but due to roundoff errors, its score will not be\n exactly zero.\n\n \"\"\"\n # Derived from ToastTile.IsPointInTile.\n\n if tile.pos.n == 0:\n return 0\n\n # Note that our labeling scheme is different than that used in WWT proper.\n if tile.pos.n == 1:\n if lon >= 0 and lon <= HALFPI and tile.pos.x == 1 and tile.pos.y == 0:\n return 0\n if lon > HALFPI and lon <= np.pi and tile.pos.x == 0 and tile.pos.y == 0:\n return 0\n if lon > np.pi and lon < THREEHALFPI and tile.pos.x == 0 and tile.pos.y == 1:\n return 0\n if lon >= THREEHALFPI and lon <= TWOPI and tile.pos.x == 1 and tile.pos.y == 1:\n return 0\n return -100\n\n test_point = _equ_to_xyz(lat, lon)\n ul = _equ_to_xyz(tile.corners[0][1], tile.corners[0][0])\n ur = _equ_to_xyz(tile.corners[1][1], tile.corners[1][0])\n lr = _equ_to_xyz(tile.corners[2][1], tile.corners[2][0])\n ll = _equ_to_xyz(tile.corners[3][1], tile.corners[3][0])\n\n upper = _left_of_half_space_score(ul, ur, test_point)\n right = _left_of_half_space_score(ur, lr, test_point)\n lower = _left_of_half_space_score(lr, ll, test_point)\n left = _left_of_half_space_score(ll, ul, test_point)\n return upper + right + lower + left\n\n\ndef toast_tile_for_point(depth, lat, lon, coordsys=ToastCoordinateSystem.ASTRONOMICAL):\n \"\"\"\n Identify the TOAST tile at a given depth that contains the given point.\n\n Parameters\n ----------\n depth : non-negative integer\n The TOAST tile pyramid depth to drill down to. For any given depth,\n there exists a tile containing the input point. As the depth gets\n larger, the precision of the location gets more precise.\n lat : number\n The latitude (declination) of the point, in radians.\n lon : number\n The longitude (RA) of the point, in radians. This value must\n have already been normalized to lie within the range [0, 2pi]\n (inclusive on both ends.)\n coordsys : optional :class:`ToastCoordinateSystem`\n The TOAST coordinate system to use. Default is\n :attr:`ToastCoordinateSystem.ASTRONOMICAL`.\n\n Returns\n -------\n The :class:`Tile` at the given depth that best contains the specified\n point.\n\n \"\"\"\n lon = lon % TWOPI\n\n if depth == 0:\n return Tile(Pos(n=0, x=0, y=0), (None, None, None, None), False)\n\n for tile in _create_level1_tiles(coordsys):\n if _toast_tile_containment_score(tile, lat, lon) == 0.0:\n break\n\n while tile.pos.n < depth:\n # Due to inevitable roundoff errors in the tile construction process, it\n # can arise that we find that the point is contained in a certain tile\n # but not contained in any of its children. We deal with this reality by\n # using the \"containment score\" rather than a binary in/out\n # classification. If no sub-tile has a containment score of zero, we\n # choose whichever tile has the least negative score. In typical\n # roundoff situations that score will be something like -1e-16.\n best_score = -np.inf\n\n for child in _div4(tile):\n score = _toast_tile_containment_score(child, lat, lon)\n\n if score == 0.0:\n tile = child\n break\n\n if score > best_score:\n tile = child\n best_score = score\n\n return tile\n\n\ndef toast_tile_get_coords(tile):\n \"\"\"\n Get the coordinates of the pixel centers of a TOAST Tile.\n\n Parameters\n ----------\n tile : :class:`Tile`\n A TOAST tile\n\n Returns\n -------\n A tuple ``(lons, lats)``, each of which is a 256x256 array of longitudes and\n latitudes of the tile pixel centers, in radians.\n \"\"\"\n\n return subsample(\n tile.corners[0],\n tile.corners[1],\n tile.corners[2],\n tile.corners[3],\n 256,\n tile.increasing,\n )\n\n\ndef toast_pixel_for_point(depth, lat, lon, coordsys=ToastCoordinateSystem.ASTRONOMICAL):\n \"\"\"\n Identify the pixel within a TOAST tile at a given depth that contains the\n given point.\n\n Parameters\n ----------\n depth : non-negative integer\n The TOAST tile pyramid depth to drill down to. For any given depth,\n there exists a tile containing the input point. As the depth gets\n larger, the precision of the location gets more precise.\n lat : number\n The latitude (declination) of the point, in radians.\n lon : number\n The longitude (RA) of the point, in radians. This value must\n have already been normalized to lie within the range [0, 2pi]\n (inclusive on both ends.)\n coordsys : optional :class:`ToastCoordinateSystem`\n The TOAST coordinate system to use. Default is\n :attr:`ToastCoordinateSystem.ASTRONOMICAL`.\n\n Returns\n -------\n A tuple ``(tile, x, y)``. The *tile* is the :class:`Tile` at the given depth\n that best contains the specified point. The *x* and *y* values are\n floating-point numbers giving the pixel location within the 256×256 tile.\n The returned values are derived from a quadratic fit to the TOAST\n coordinates of the pixels nearest the specified coordinates *lat* and *lon*.\n\n \"\"\"\n tile = toast_tile_for_point(depth, lat, lon, coordsys=coordsys)\n\n # Now that we have the tile, get its pixel locations and identify the pixel\n # that is closest to the input position.\n\n lons, lats = toast_tile_get_coords(tile)\n dist2 = (lons - lon) ** 2 + (lats - lat) ** 2\n min_y, min_x = np.unravel_index(np.argmin(dist2), (256, 256))\n\n # Now, identify a postage stamp around that best-fit pixel and fit a biquadratic\n # mapping lat/lon to y/x.\n\n halfsize = 4\n x0 = max(min_x - halfsize, 0)\n y0 = max(min_y - halfsize, 0)\n x1 = min(min_x + halfsize + 1, 256)\n y1 = min(min_y + halfsize + 1, 256)\n\n dist2_stamp = dist2[y0:y1, x0:x1]\n lons_stamp = lons[y0:y1, x0:x1]\n lats_stamp = lats[y0:y1, x0:x1]\n\n flat_lons = lons_stamp.flatten()\n flat_lats = lats_stamp.flatten()\n\n A = np.array(\n [\n flat_lons * 0 + 1,\n flat_lons,\n flat_lats,\n flat_lons**2,\n flat_lons * flat_lats,\n flat_lats**2,\n ]\n ).T\n\n ygrid, xgrid = np.indices(dist2_stamp.shape)\n x_coeff, _r, _rank, _s = np.linalg.lstsq(A, xgrid.flatten(), rcond=None)\n y_coeff, _r, _rank, _s = np.linalg.lstsq(A, ygrid.flatten(), rcond=None)\n\n # Evaluate the polynomial to get the refined pixel coordinates.\n\n pt = np.array(\n [\n 1,\n lon,\n lat,\n lon**2,\n lon * lat,\n lat**2,\n ]\n )\n x = np.dot(x_coeff, pt)\n y = np.dot(y_coeff, pt)\n return tile, x0 + x, y0 + y\n\n\ndef _postfix_corner(tile, depth, filter, bottom_only):\n \"\"\"\n Yield subtiles of a given tile, in postfix (deepest-first) order.\n\n Parameters\n ----------\n tile : Tile\n Parameters of the current tile.\n depth : int\n The depth to descend to.\n filter : function(Tile)->bool\n A filter function; only tiles for which the function returns True will\n be investigated.\n bottom_only : bool\n If True, only yield tiles at max_depth.\n\n \"\"\"\n n = tile.pos.n\n if n > depth:\n return\n\n if n > 1 and not filter(tile):\n return\n\n for child in _div4(tile):\n for item in _postfix_corner(child, depth, filter, bottom_only):\n yield item\n\n if n == depth or not bottom_only:\n yield tile\n\n\ndef _div4(tile):\n \"\"\"Return the four child tiles of an input tile.\"\"\"\n n, x, y = tile.pos.n, tile.pos.x, tile.pos.y\n ul, ur, lr, ll = tile.corners\n increasing = tile.increasing\n\n to = mid(ul, ur)\n ri = mid(ur, lr)\n bo = mid(lr, ll)\n le = mid(ll, ul)\n ce = mid(ll, ur) if increasing else mid(ul, lr)\n\n n += 1\n x *= 2\n y *= 2\n\n return [\n Tile(Pos(n=n, x=x, y=y), (ul, to, ce, le), increasing),\n Tile(Pos(n=n, x=x + 1, y=y), (to, ur, ri, ce), increasing),\n Tile(Pos(n=n, x=x, y=y + 1), (le, ce, bo, ll), increasing),\n Tile(Pos(n=n, x=x + 1, y=y + 1), (ce, ri, lr, bo), increasing),\n ]\n\n\ndef create_single_tile(pos, coordsys=ToastCoordinateSystem.ASTRONOMICAL):\n \"\"\"\n Create a single TOAST tile.\n\n Parameters\n ----------\n pos : :class:`~toasty.pyramid.Pos`\n The position of the tile that will be created. The depth of the\n tile must be at least 1.\n coordsys : optional :class:`ToastCoordinateSystem`\n The TOAST coordinate system to use. Default is\n :attr:`ToastCoordinateSystem.ASTRONOMICAL`.\n\n Returns\n -------\n :class:`Tile`\n\n Notes\n -----\n This function should only be used for one-off investigations and debugging.\n It is much more efficient to use :func:`generate_tiles` for bulk computations.\n \"\"\"\n\n if pos.n == 0:\n raise ValueError(\"cannot create a Tile for the n=0 tile\")\n\n children = _create_level1_tiles(coordsys)\n cur_n = 0\n\n while True:\n cur_n += 1\n ix = (pos.x >> (pos.n - cur_n)) & 0x1\n iy = (pos.y >> (pos.n - cur_n)) & 0x1\n tile = children[iy * 2 + ix]\n\n if cur_n == pos.n:\n return tile\n\n children = _div4(tile)\n\n\ndef generate_tiles(\n depth, bottom_only=True, coordsys=ToastCoordinateSystem.ASTRONOMICAL\n):\n \"\"\"Generate a pyramid of TOAST tiles in deepest-first order.\n\n Parameters\n ----------\n depth : int\n The tile depth to recurse to.\n bottom_only : bool\n If True, then only the lowest tiles will be yielded.\n coordsys : optional :class:`ToastCoordinateSystem`\n The TOAST coordinate system to use. Default is\n :attr:`ToastCoordinateSystem.ASTRONOMICAL`.\n\n Yields\n ------\n tile : Tile\n An individual tile to process. Tiles are yielded deepest-first.\n\n The ``n = 0`` depth is not included.\n\n \"\"\"\n return generate_tiles_filtered(\n depth, lambda t: True, bottom_only, coordsys=coordsys\n )\n\n\ndef generate_tiles_filtered(\n depth, filter, bottom_only=True, coordsys=ToastCoordinateSystem.ASTRONOMICAL\n):\n \"\"\"Generate a pyramid of TOAST tiles in deepest-first order, filtering out subtrees.\n\n Parameters\n ----------\n depth : int\n The tile depth to recurse to.\n filter : function(Tile)->bool\n A filter function; only tiles for which the function returns True will\n be investigated.\n bottom_only : optional bool\n If True, then only the lowest tiles will be yielded.\n coordsys : optional :class:`ToastCoordinateSystem`\n The TOAST coordinate system to use. Default is\n :attr:`ToastCoordinateSystem.ASTRONOMICAL`.\n\n Yields\n ------\n tile : Tile\n An individual tile to process. Tiles are yielded deepest-first.\n\n The ``n = 0`` depth is not included.\n\n \"\"\"\n for t in _create_level1_tiles(coordsys):\n if filter(t):\n for item in _postfix_corner(t, depth, filter, bottom_only):\n yield item\n\n\ndef count_tiles_matching_filter(\n depth, filter, bottom_only=True, coordsys=ToastCoordinateSystem.ASTRONOMICAL\n):\n \"\"\"\n Count the number of tiles matching a filter.\n\n Parameters\n ----------\n depth : int\n The tile depth to recurse to.\n filter : function(Tile)->bool\n A filter function; only tiles for which the function returns True will\n be investigated.\n bottom_only : bool\n If True, then only the lowest tiles will be processed.\n coordsys : optional :class:`ToastCoordinateSystem`\n The TOAST coordinate system to use. Default is\n :attr:`ToastCoordinateSystem.ASTRONOMICAL`.\n\n Returns\n -------\n The number of tiles matching the filter. Even if ``bottom_only`` is false,\n the ``n = 0`` tile is not counted.\n\n Notes\n -----\n This function's call signature and tree-exploration semantics match\n :func:`generate_tiles_filtered`.\n \"\"\"\n # With a generic filter function, brute force is our only option:\n n = 0\n\n for _tile in generate_tiles_filtered(\n depth, filter, bottom_only=bottom_only, coordsys=coordsys\n ):\n n += 1\n\n return n\n\n\ndef sample_layer(\n pio,\n sampler,\n depth,\n coordsys=ToastCoordinateSystem.ASTRONOMICAL,\n format=None,\n parallel=None,\n cli_progress=False,\n):\n \"\"\"Generate a layer of the TOAST tile pyramid through direct sampling.\n\n Parameters\n ----------\n pio : :class:`toasty.pyramid.PyramidIO`\n A :class:`~toasty.pyramid.PyramidIO` instance to manage the I/O with\n the tiles in the tile pyramid.\n sampler : callable\n The sampler callable that will produce data for tiling.\n depth : int\n The depth of the layer of the TOAST tile pyramid to generate. The\n number of tiles in each layer is ``4**depth``. Each tile is 256×256\n TOAST pixels, so the resolution of the pixelization at which the\n data will be sampled is a refinement level of ``2**(depth + 8)``.\n coordsys : optional :class:`ToastCoordinateSystem`\n The TOAST coordinate system to use. Default is\n :attr:`ToastCoordinateSystem.ASTRONOMICAL`.\n format : optional :class:`str`\n If provided, override the default data storage format of *pio* with the\n named format, one of the values in ``toasty.image.SUPPORTED_FORMATS``.\n parallel : integer or None (the default)\n The level of parallelization to use. If unspecified, defaults to using\n all CPUs. If the OS does not support fork-based multiprocessing,\n parallel processing is not possible and serial processing will be\n forced. Pass ``1`` to force serial processing.\n cli_progress : optional boolean, defaults False\n If true, a progress bar will be printed to the terminal.\n \"\"\"\n\n from .pyramid import Pyramid\n\n p = Pyramid.new_toast(depth, coordsys=coordsys)\n proc = ToastSampler(pio, sampler, True, format=format)\n p.visit_leaves(proc.visit_callback, parallel=parallel, cli_progress=cli_progress)\n\n\ndef sample_layer_filtered(\n pio,\n tile_filter,\n sampler,\n depth,\n coordsys=ToastCoordinateSystem.ASTRONOMICAL,\n parallel=None,\n cli_progress=False,\n):\n \"\"\"Populate a subset of a layer of the TOAST tile pyramid through direct sampling.\n\n Parameters\n ----------\n pio : :class:`toasty.pyramid.PyramidIO`\n A :class:`~toasty.pyramid.PyramidIO` instance to manage the I/O with\n the tiles in the tile pyramid.\n tile_filter : callable\n A tile filtering function, suitable for passing to\n :func:`toasty.toast.generate_tiles_filtered`.\n sampler : callable\n The sampler callable that will produce data for tiling.\n depth : int\n The depth of the layer of the TOAST tile pyramid to generate. The\n number of tiles in each layer is ``4**depth``. Each tile is 256×256\n TOAST pixels, so the resolution of the pixelization at which the\n data will be sampled is a refinement level of ``2**(depth + 8)``.\n coordsys : optional :class:`ToastCoordinateSystem`\n The TOAST coordinate system to use. Default is\n :attr:`ToastCoordinateSystem.ASTRONOMICAL`.\n parallel : integer or None (the default)\n The level of parallelization to use. If unspecified, defaults to using\n all CPUs. If the OS does not support fork-based multiprocessing,\n parallel processing is not possible and serial processing will be\n forced. Pass ``1`` to force serial processing.\n cli_progress : optional boolean, defaults False\n If true, a progress bar will be printed to the terminal.\n \"\"\"\n\n from .pyramid import Pyramid\n\n p = Pyramid.new_toast_filtered(depth, tile_filter, coordsys=coordsys)\n proc = ToastSampler(pio, sampler, False, format=format)\n p.visit_leaves(proc.visit_callback, parallel=parallel, cli_progress=cli_progress)\n\n\nclass ToastSampler(object):\n \"\"\"A utility for performing TOAST sampling on a\n :class:`~toasty.pyramid.Pyramid`.\n\n Parameters\n ----------\n pio : :class:`toasty.pyramid.PyramidIO`\n Handle for image I/O on the pyramid\n sampler : callable\n The sampler callable that will produce data for tiling.\n clobber : bool\n If true, data in any existing tiles will be ignored and destroyed.\n Otherwise, data from existing tiles will be read and updated. The\n \"clobber\" mode is faster but will give incorrect results if other\n sampling operations will be run on this pyramid.\n format : optional :class:`str`\n If provided, override the default data storage format of *pio* with the\n named format, one of the values in ``toasty.image.SUPPORTED_FORMATS``.\n\n Notes\n -----\n This class provides a :meth:`visit_callback` method that can be passed to\n the :meth:`toasty.pyramid.Pyramid.visit_leaves` function. This class\n preserves some state between calls to help speed up processing.\"\"\"\n\n def __init__(self, pio, sampler, clobber, format=None):\n self._pio = pio\n self._sampler = sampler\n self._clobber = clobber\n self._format = format\n self._invert_into_tiles = pio.get_default_vertical_parity_sign() == 1\n\n def visit_callback(self, pos, tile):\n lon, lat = toast_tile_get_coords(tile)\n sampled_data = self._sampler(lon, lat)\n\n if self._invert_into_tiles:\n sampled_data = sampled_data[::-1]\n\n img = Image.from_array(sampled_data)\n\n if self._clobber:\n self._pio.write_image(pos, img, format=self._format)\n else:\n with self._pio.update_image(\n pos, masked_mode=img.mode, default=\"masked\"\n ) as basis:\n img.update_into_maskable_buffer(\n basis, slice(None), slice(None), slice(None), slice(None)\n )\n","sub_path":"toasty/toast.py","file_name":"toast.py","file_ext":"py","file_size_in_byte":24679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"14365457","text":"\"\"\"\n2\n3\n9 8 6\n2 3 7\n\n21\n\"\"\"\nm = int(input())\nn = int(input())\n\ngrap = []\nfor i in range(m):\n temp = list(map(int, input().strip().split(' ')))\n\n grap.append(temp)\n\n\ndp = [[0 for i in range(n+1)] for j in range(m+1)]\n\n#把第一行填了\nfor i in range(1, m+1):\n for j in range(1, n+1):\n #第一行处理\n if i == 1:\n dp[i][j] = dp[i][j-1] + grap[i-1][j-1]\n #处理第一列\n elif j == 1:\n dp[i][j] = dp[i-1][j] + grap[i-1][j-1]\n\n else:\n dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grap[i-1][j-1]\n\n# print(dp)\nprint(dp[-1][-1])","sub_path":"58秋招/动态规划最短路径.py","file_name":"动态规划最短路径.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"202476794","text":"# This is the code I used to get all the app descriptions. Now play_scraper has changed: running it throws an error\n\nimport play_scraper\nimport time\nfrom time import sleep\n\ncollections=['NEW_FREE','TOP_FREE','TOP_PAID','TOP_GROSSING','TRENDING']\n\nCATEGORIES = [\n \"ART_AND_DESIGN\",\n \"BOOKS_AND_REFERENCE\",\n \"BUSINESS\",\n \"COMICS\",\n \"EDUCATION\",\n \"ENTERTAINMENT\",\n \"FINANCE\",\n \"FOOD_AND_DRINK\",\n \"GAME\",\n \"HEALTH_AND_FITNESS\",\n \"HOUSE_AND_HOME\",\n \"MAPS_AND_NAVIGATION\",\n \"MEDICAL\",\n \"MUSIC_AND_AUDIO\",\n \"NEWS_AND_MAGAZINES\",\n \"PERSONALIZATION\",\n \"PHOTOGRAPHY\",\n \"PRODUCTIVITY\",\n \"SHOPPING\",\n \"SPORTS\",\n \"WEATHER\"]\n\napps=[]\nfor cat in CATEGORIES:\n for topic in collections:\n for p in range(0,4):\n g = play_scraper.collection(collection=topic,\n category = cat,\n results = 100,\n page = p, \n detailed = True, \n hl = 'en')\n apps.extend(g) \n print(p)\n time.sleep(30)\n\napp_price=[]\napp_score=[]\napp_name=[]\napp_description=[]\napp_category = []\nfor i in range(len(apps)):\n app_name.append(apps[i]['title'])\n app_description.append(apps[i]['description'])\n app_score.append(apps[i]['score'])\n app_price.append(apps[i]['price'])\n if apps[i]['category'] == []:\n app_category.append(\"NaN\")\n else:\n app_category.append(apps[i]['category'][0])\n \ndf=pd.DataFrame({'app':app_name, 'description':app_description, 'category':app_category, \n 'price':app_price, 'rating': app_score}).drop_duplicates()\n\n\ndf.to_csv(\"corpus1_raw.csv\", sep = \"\\t\")","sub_path":"app_descriptions/play_scraper_data.py","file_name":"play_scraper_data.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"120952657","text":"#! /usr/bin/python2\n# -*- coding = utf-8 -*-\nfrom __future__ import print_function\nimport numpy as np\nimport sys\nimport os\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport cPickle as pkl\n\n\nclass knowledgeGraph():\n def __init__(self, pagePath):\n ### self.pagePath is the folder where the content containing\n ### a folder of the original html pages, the .stats file, \n self.pagePath = pagePath\n self.contentPath = 'content'\n self.sim()\n self.buildGraph()\n self.tfidfTitle = TfidfVectorizer(input=u'content', strip_accents='ascii', stop_words='english')\n text_dict = {x:self.idx2url[x][6:].replace('_',' ') for x in self.idx2url}\n self.tfsTitle = self.tfidfTitle.fit_transform(text_dict.values())\n self.mostRelatedPath()\n\n def sim(self):\n # doing the tfidf and cosine similarity\n flist = os.listdir(self.pagePath + '/' + self.contentPath)\n self.tfidf = TfidfVectorizer(input=u'content', strip_accents='ascii', stop_words='english')\n text_dict = {int(f.strip('.txt')): file('%s/%s/%s' %(self.pagePath, self.contentPath, f)).read() for f in flist}\n fname = text_dict.keys()\n self.row2idx = {i: fname[i] for i in range(len(fname))}\n self.idx2row = {fname[i]: i for i in range(len(fname))}\n self.tfs = self.tfidf.fit_transform(text_dict.values())\n self.cosCoef = (self.tfs * self.tfs.T).toarray()\n\n\n def buildGraph(self):\n # building the weighted graph\n self.urlGraph, self.url2idx = pkl.load(file('%s/urlgi.pkl' % (self.pagePath)))\n self.idx2url = {self.url2idx[url]: url for url in self.url2idx}\n self.graph = {}\n mask = np.zeros(self.cosCoef.shape)\n for page in self.urlGraph:\n self.graph[page] = {sub: self.cosCoef[self.idx2row[page], self.idx2row[sub]] for sub in self.urlGraph[page]}\n mask[self.idx2row[page], [self.idx2row[sub] for sub in self.urlGraph[page]]] = 1\n self.cosCoef *= mask\n self.cosCoef[np.eye(len(self.cosCoef)) == 1] = 1\n fp = open('%s_edge.csv' % self.pagePath, 'w')\n for page in self.graph:\n map(fp.write, ['%s %s %f\\n' % (self.idx2url[page], self.idx2url[sub], self.graph[page][sub]) for sub in self.graph[page]])\n fp.close()\n # np.save(file('%s/graph.npy' % (self.pagePath), 'w'), self.cosCoef)\n\n def mostRelatedPath(self):\n self.distance = np.copy(self.cosCoef)\n N = len(self.distance)\n self.route = np.ones(self.distance.shape, dtype=int) * -1\n for i in range(N):\n self.route[i][self.distance[i] != 0] = i\n for k in range(N):\n for i in range(N):\n tmp = self.distance[i, k] * self.distance[k, :]\n isg = self.distance[i, :] < tmp\n self.distance[i, isg] = tmp[isg]\n self.route[i, isg] = k\n if k % 10 == 0:\n print('%6d / %6d \\r' % (k, N), end=\"\")\n self.distance[self.distance == 1] = -1\n # np.save(file('%s/dist.npy' % self.pagePath, 'w'), self.distance)\n # np.save(file('%s/path.npy' % self.pagePath, 'w'), self.route)\n return self.distance, self.route\n\n def matchQuery(self, query):\n titleVec = self.tfidfTitle.transform([query])\n tmp = (self.tfsTitle * titleVec.T).toarray()\n titleID = np.argmax(tmp)\n if tmp[titleID] == 0:\n wordVector = self.tfidf.transform([query])\n docID = np.argmax((self.tfs * wordVector.T).toarray())\n return docID\n else:\n return titleID\n\n def searchRelated(self, docID):\n descendantID = np.argsort(self.distance[docID, :])[::-1][:20]\n ancestorID = np.argsort(self.distance[:, docID])[::-1][:20]\n #print(self.idx2url[self.row2idx[docID]])\n #print([ self.idx2url[self.row2idx[i]] for i in descendantID])\n #print([ self.idx2url[self.row2idx[i]] for i in ancestorID])\n return descendantID, ancestorID\n\n def searchRoute(self, doc1, doc2):\n if doc1 == doc2:\n return []\n elif self.route[doc1, doc2] == -1:\n return []\n elif self.route[doc1, doc2] == doc1:\n return [doc1]\n else:\n return self.searchRoute(doc1, self.route[doc1, doc2]) + self.searchRoute(self.route[doc1, doc2], doc2)\n \nif __name__ == '__main__':\n G = knowledgeGraph(sys.argv[1])\n with open('%s/class.pkl'%sys.argv[1],'w') as f:\n pkl.dump(G, f)\n","sub_path":"django/wikiNet/knowledgeGraph.py","file_name":"knowledgeGraph.py","file_ext":"py","file_size_in_byte":4515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"576471996","text":"\nimport pygame\nimport time\nimport random\nimport sys\n\npygame.init()\n\nLARGURA = 640\nALTURA = 640\n\nBEGE = (238,238,210)\nPRETO = (0, 0, 0)\nFOSCO = (158, 158, 158)\nBRANCO = (255, 255, 255)\nCINZA = (100, 100, 100)\nVERDE_ESCURO = (118,150,86)\nYELLOW = (0, 255, 0)\nVERMELHO_CLARO = (255, 0, 0)\nYELLOW = (255,215,0)\nCINZA = (222, 235, 235)\nCORAL = (240,128,128)\nTAMANHO_QUADRADO = 80\nTAMANHO_DAMA = 34\n\n\ntela = pygame.display.set_mode((640, 640))\nclock = pygame.time.Clock()\n\n# Classe principal\nclass Jogo:\n # Classe para tomar conta do estado do jogo\n def __init__(self):\n self.estado = 'jogando'\n self.turno = 1\n self.jogadores = ('x', 'o')\n self.cedula_selecionada = None\n self.pulando = False\n self.tabuleiro = [['x', '-', 'x', '-', 'x', '-', 'x', '-'],\n\t\t\t\t\t\t ['-', 'x', '-', 'x', '-', 'x', '-', 'x'],\n\t\t\t\t\t\t ['x', '-', 'x', '-', 'x', '-', 'x', '-'],\n\t\t\t\t\t\t ['-', '-', '-', '-', '-', '-', '-', '-'],\n\t\t\t\t\t\t ['-', '-', '-', '-', '-', '-', '-', '-'],\n\t\t\t\t\t\t ['-', 'o', '-', 'o', '-', 'o', '-', 'o'],\n\t\t\t\t\t\t ['o', '-', 'o', '-', 'o', '-', 'o', '-'],\n\t\t\t\t\t\t ['-', 'o', '-', 'o', '-', 'o', '-', 'o']]\n\n def nao_ha_movimento_obrigatorio(self,movs,i):\n return movs[i] == []\n\n def jogadas(self, pos):\n if self.estado == \"jogando\":\n linha = linha_clicada(pos)\n coluna = coluna_clicada(pos)\n if self.cedula_selecionada:\n movimento = self.is_movimento_valido(self.jogadores[self.turno % 2], self.cedula_selecionada, linha, coluna)\n if movimento[0]:\n self.jogar(self.jogadores[self.turno % 2], self.cedula_selecionada, linha, coluna, movimento[1])\n elif linha == self.cedula_selecionada[0] and coluna == self.cedula_selecionada[1]:\n movs = self.movimento_obrigatorio(self.cedula_selecionada)\n if self.nao_ha_movimento_obrigatorio(movs,0) and self.pulando:\n self.pulando = False\n self.proximo_turno()\n self.cedula_selecionada = None\n else:\n if self.eh_a_vez(None,linha,coluna):\n self.cedula_selecionada = [linha, coluna]\n\n def ha_movimentos_obrigatorios(self,ob):\n return ob != {}\n\n def nao_esta_em(self,a,b):\n return a not in b\n\n def esta_em(self,a,b):\n return a in b\n\n def is_movimento_valido(self,jogador, localizacao_cedula, linha_destino, coluna_destino):\n linha_originaria = localizacao_cedula[0]\n coluna_originaria = localizacao_cedula[1]\n obrigatorios = self.todos_obrigatorios()\n if self.ha_movimentos_obrigatorios(obrigatorios):\n if self.nao_esta_em((linha_originaria, coluna_originaria),obrigatorios):\n return False, None\n elif self.nao_esta_em([linha_destino, coluna_destino],obrigatorios[(linha_originaria, coluna_originaria)]):\n return False, None\n movimento, pulo = self.movimentos_possiveis(localizacao_cedula)\n if self.esta_em([linha_destino, coluna_destino],movimento):\n if pulo:\n if len(pulo) == 1:\n return True, pulo[0]\n else:\n return self.calcula_pulo(pulo,linha_destino,coluna_destino)\n if self.pulando:\n return False, None\n return True, None\n return False, None\n\n def calcula_pulo(self,pulo,l_dest,c_dest):\n for i in range(len(pulo)):\n if abs(pulo[i][0] - l_dest) == 1 and abs(pulo[i][1] - c_dest == 1):\n return True, pulo[i]\n return False,None\n\n def proximo_turno(self):\n self.turno += 1\n\n def jogar(self, jogador, localizacao_cedula, linha_destino, coluna_destino, pulo):\n linha_atual = localizacao_cedula[0]\n coluna_atual = localizacao_cedula[1]\n char = self.tabuleiro[linha_atual][coluna_atual]\n\n self.tabuleiro[linha_destino][coluna_destino] = char\n self.tabuleiro[linha_atual][coluna_atual] = '-'\n\n if pulo:\n self.tabuleiro[pulo[0]][pulo[1]] = '-'\n self.cedula_selecionada = [linha_destino, coluna_destino]\n self.pulando = True\n\n if not self.movimento_obrigatorio((linha_destino, coluna_destino))[0]:\n if(linha_destino == 0):\n self.tabuleiro[linha_destino][coluna_destino] = char.upper()\n self.pulando = False\n self.cedula_selecionada = None\n self.proximo_turno()\n else:\n if(linha_destino == 0):\n self.tabuleiro[linha_destino][coluna_destino] = char.upper()\n self.pulando = False\n self.cedula_selecionada = None\n self.proximo_turno()\n\n vencedor = self.verifica_vencedor()\n\n if vencedor != None:\n self.estado = ('game over')\n\n def proximo_turno(self):\n self.turno += 1\n\n def todos_obrigatorios(self):\n all = {}\n for r in range(len(self.tabuleiro)):\n for c in range(len(self.tabuleiro[r])):\n ob, pulos = self.movimento_obrigatorio((r, c))\n if ob != []:\n all[(r, c)] = ob\n return all\n\n def todos_obrigatorios_IA(self):\n all = {}\n\n for r in range(len(self.tabuleiro)):\n for c in range(len(self.tabuleiro[r])):\n ob, pulos = self.movimento_obrigatorio((r, c))\n if ob != []:\n all[(r, c)] = ob\n print(all)\n break\n\n return all\n\n def eh_a_vez(self,indice,linha,coluna):\n if linha == None or coluna == None:\n return self.turno % 2 == indice\n return self.tabuleiro[linha][coluna].lower() == self.jogadores[self.turno % 2]\n\n def nao_eh_dama(self,linha,coluna,jogador):\n return self.tabuleiro[linha][coluna].islower() and self.tabuleiro[linha][coluna] == jogador\n\n def eh_dama(self,linha,coluna,jogador):\n return self.tabuleiro[linha][coluna].isupper() and self.tabuleiro[linha][coluna] == jogador.upper()\n\n def eh_casa_vazia(self,l,c):\n return self.tabuleiro[l][c] == '-'\n\n def obrigs_e_pulada(self,obrigatorios,posicao_cedula_pulada,l_x,i,l_c,j):\n #i=-1\n #j=+1\n obrigatorios.append([l_x + i, l_c + j])\n posicao_cedula_pulada.append((l_x, l_c))\n return obrigatorios,posicao_cedula_pulada\n\n def obrigs_e_pulada_aux(self,obrigatorios,posicao_cedula_pulada,u,i,v,j,cond):\n if cond and self.eh_casa_vazia((u) + i, (v) + j):\n return self.obrigs_e_pulada(obrigatorios,posicao_cedula_pulada,(u),i,(v),j)\n return obrigatorios,posicao_cedula_pulada\n\n def tabuleiro_not_in_array(self,obrigatorios,posicao_cedula_pulada,u,i,v,j,cond,array):\n if self.tabuleiro[u][v].lower() not in array:\n return self.obrigs_e_pulada_aux(obrigatorios,posicao_cedula_pulada,u,i,v,j,cond)\n return obrigatorios,posicao_cedula_pulada\n \n def movimento_obrigatorio(self, localizacao_cedula):\n obrigatorios = []\n posicao_cedula_pulada = []\n l = localizacao_cedula[0]#posicao da pedra\n c = localizacao_cedula[1]\n jogador = self.jogadores[self.turno % 2]#quem e a vez\n himself = [jogador.lower(), jogador.upper()]\n index = self.jogadores.index(jogador)#cont de quem e o jogador\n array = [jogador.lower(), jogador.upper(), '-']#indica quem e a vez\n #iI(posicao_cedula_pulada)\n if self.nao_eh_dama(l,c,jogador) and self.eh_a_vez(index,None,None):\n if l > 0:\n if c < 7:\n obrigatorios,posicao_cedula_pulada = self.tabuleiro_not_in_array(obrigatorios,posicao_cedula_pulada,(l - 1),-1,(c + 1),+1,(l - 1) - 1 >= 0 and (c + 1) + 1 <= 7,array)\n if c > 0:\n obrigatorios, posicao_cedula_pulada = self.tabuleiro_not_in_array(obrigatorios, posicao_cedula_pulada, (l - 1),\n -1, (c - 1), -1,\n (l - 1) - 1 >= 0 and (c - 1) - 1 >= 0,array)\n if l < 7:\n if c < 7:\n obrigatorios, posicao_cedula_pulada = self.tabuleiro_not_in_array(obrigatorios, posicao_cedula_pulada, (l + 1),\n +1, (c + 1), +1,\n (l + 1) + 1 <= 7 and (c + 1) + 1 <= 7,array)\n if c > 0:\n obrigatorios, posicao_cedula_pulada = self.tabuleiro_not_in_array(obrigatorios, posicao_cedula_pulada, (l + 1),+1, (c - 1), -1,(l + 1) + 1 <= 7 and (c - 1) - 1 >= 0,array)\n elif self.eh_dama(l,c,jogador) and self.eh_a_vez(index,None,None) :\n if not self.pulando and (jogador.lower() == 'x') or (jogador.lower() == 'o'):\n movimento_x = l\n movimento_y = c\n while True:\n if movimento_x - 1 < 0 or movimento_y - 1 < 0:\n break\n else:\n if self.tabuleiro[movimento_x - 1][movimento_y - 1] in himself:\n break\n if self.tabuleiro[movimento_x - 1][movimento_y - 1] not in array:\n l_x = movimento_x - 1\n l_c = movimento_y - 1\n if l_x - 1 >= 0 and l_c - 1 >= 0:\n if self.eh_casa_vazia(l_x - 1,l_c - 1):#TTTTTTTT\n #l_x, l_c, obrigatorios,\n #posicao_cedula_pulada =\n #self.obrigs_e_pulada_segunda_condic(l_x -\n #1 < 0 or l_c - 1 < 0, l_x,-1, l_c,-1,\n #obrigatorios, posicao_cedula_pulada)\n posicao_cedula_pulada.append((l_x, l_c))\n while True:\n if l_x - 1 < 0 or l_c - 1 < 0:\n break\n else:\n if self.eh_casa_vazia(l_x - 1,l_c - 1):\n obrigatorios.append([l_x - 1, l_c - 1])\n else:\n break\n l_x -= 1\n l_c -= 1\n break\n movimento_x -= 1\n movimento_y -= 1\n movimento_x = l\n movimento_y = c\n while True:\n if movimento_x - 1 < 0 or movimento_y + 1 > 7:\n break\n else:\n if self.tabuleiro[movimento_x - 1][movimento_y + 1] in himself:\n break\n if self.tabuleiro[movimento_x - 1][movimento_y + 1] not in array:\n l_x = movimento_x - 1\n l_c = movimento_y + 1\n if l_x - 1 >= 0 and l_c + 1 <= 7:\n if self.eh_casa_vazia(l_x - 1,l_c + 1):####TTTTTTTT\n # l_x, l_c, obrigatorios,\n # posicao_cedula_pulada =\n # self.obrigs_e_pulada_segunda_condic(l_x -\n # 1 < 0 or l_c + 1 > 7, l_x,-1, l_c,+1,\n # obrigatorios, posicao_cedula_pulada)\n posicao_cedula_pulada.append((l_x, l_c))\n while True:\n if l_x - 1 < 0 or l_c + 1 > 7:\n break\n else:\n if self.eh_casa_vazia(l_x - 1,l_c + 1):\n obrigatorios.append([l_x - 1, l_c + 1])\n else:\n break\n l_x -= 1\n l_c += 1\n break\n movimento_x -= 1\n movimento_y += 1\n movimento_x = l\n movimento_y = c\n while True:\n if movimento_x + 1 > 7 or movimento_y + 1 > 7:\n break\n else:\n if self.tabuleiro[movimento_x + 1][movimento_y + 1] in himself:\n break\n if self.tabuleiro[movimento_x + 1][movimento_y + 1] not in array:\n l_x = movimento_x + 1\n l_c = movimento_y + 1\n if l_x + 1 <= 7 and l_c + 1 <= 7:\n if self.eh_casa_vazia(l_x + 1,l_c + 1):##########TTTTTTTTTTTTTTTTTT\n #l_x, l_c, obrigatorios,\n #posicao_cedula_pulada =\n #self.obrigs_e_pulada_segunda_condic(\n # l_x + 1 > 7 or l_c + 1 > 7, l_x, +1,\n # l_c, +1, obrigatorios,\n # posicao_cedula_pulada)\n posicao_cedula_pulada.append((l_x, l_c))\n while True:\n if l_x + 1 > 7 or l_c + 1 > 7:\n break\n else:\n if self.eh_casa_vazia(l_x + 1,l_c + 1):\n obrigatorios.append([l_x + 1, l_c + 1])\n else:\n break\n l_x += 1\n l_c += 1\n break\n movimento_x += 1\n movimento_y += 1\n\n movimento_x = l\n movimento_y = c\n while True:\n if movimento_x + 1 > 7 or movimento_y - 1 < 0:\n break\n else:\n if self.tabuleiro[movimento_x + 1][movimento_y - 1] in himself:\n break\n if self.tabuleiro[movimento_x + 1][movimento_y - 1] not in array:\n l_x = movimento_x + 1\n l_c = movimento_y - 1\n\n if l_x + 1 <= 7 and l_c - 1 >= 0:\n if self.eh_casa_vazia(l_x + 1,l_c - 1):########ttttttttttttttttt\n #l_x, l_c, obrigatorios,\n #posicao_cedula_pulada =\n #self.obrigs_e_pulada_segunda_condic(\n # l_x + 1 > 7 or l_c - 1 < 0, l_x, +1,\n # l_c, -1, obrigatorios,\n # posicao_cedula_pulada)\n posicao_cedula_pulada.append((l_x, l_c))\n while True:\n if l_x + 1 > 7 or l_c - 1 < 0:\n break\n else:\n if self.eh_casa_vazia(l_x + 1,l_c - 1):\n obrigatorios.append([l_x + 1, l_c - 1])\n else:\n break\n l_x += 1\n l_c -= 1\n break\n movimento_x += 1\n movimento_y -= 1\n return obrigatorios, posicao_cedula_pulada\n\n def existe_possivel(self):\n for l in range(len(self.tabuleiro)):\n for c in range(len(self.tabuleiro[l])):\n if self.movimentos_possiveis((l, c))[0]:\n return True\n return False\n\n def movimentos_possiveis(self, localizacao_cedula):\n movimentos, pulos = self.movimento_obrigatorio(localizacao_cedula)\n\n if movimentos == []:\n linha_atual = localizacao_cedula[0]\n coluna_atual = localizacao_cedula[1]\n\n if self.tabuleiro[linha_atual][coluna_atual].islower():\n if self.tabuleiro[linha_atual][coluna_atual] == 'o':\n if linha_atual > 0:\n if coluna_atual < 7:\n if self.tabuleiro[linha_atual - 1][coluna_atual + 1] == '-':\n movimentos.append([linha_atual - 1, coluna_atual + 1])\n if coluna_atual > 0:\n if self.tabuleiro[linha_atual - 1][coluna_atual - 1] == '-':\n movimentos.append([linha_atual - 1, coluna_atual - 1])\n elif self.tabuleiro[linha_atual][coluna_atual] == 'x':\n if linha_atual < 7:\n if coluna_atual < 7:\n if self.tabuleiro[linha_atual + 1][coluna_atual + 1] == '-':\n movimentos.append([linha_atual + 1, coluna_atual + 1])\n if coluna_atual > 0:\n if self.tabuleiro[linha_atual + 1][coluna_atual - 1] == '-':\n movimentos.append([linha_atual + 1, coluna_atual - 1])\n elif self.tabuleiro[linha_atual][coluna_atual].isupper():\n conta_linha = linha_atual\n conta_coluna = coluna_atual\n while True:\n if conta_linha - 1 < 0 or conta_coluna - 1 < 0:\n break\n else:\n if self.tabuleiro[conta_linha - 1][conta_coluna - 1] == '-':\n movimentos.append([conta_linha - 1, conta_coluna - 1])\n else:\n break\n conta_linha -= 1\n conta_coluna -= 1\n\n conta_linha = linha_atual\n conta_coluna = coluna_atual\n while True:\n if conta_linha - 1 < 0 or conta_coluna + 1 > 7:\n break\n else:\n if self.tabuleiro[conta_linha - 1][conta_coluna + 1] == '-':\n movimentos.append([conta_linha - 1, conta_coluna + 1])\n else:\n break\n conta_linha -= 1\n conta_coluna += 1\n\n conta_linha = linha_atual\n conta_coluna = coluna_atual\n while True:\n if conta_linha + 1 > 7 or conta_coluna + 1 > 7:\n break\n else:\n if self.tabuleiro[conta_linha + 1][conta_coluna + 1] == '-':\n movimentos.append([conta_linha + 1, conta_coluna + 1])\n else:\n break\n conta_linha += 1\n conta_coluna += 1\n\n conta_linha = linha_atual\n conta_coluna = coluna_atual\n while True:\n if conta_linha + 1 > 7 or conta_coluna - 1 < 0:\n break\n else:\n if self.tabuleiro[conta_linha + 1][conta_coluna - 1] == '-':\n movimentos.append([conta_linha + 1, conta_coluna - 1])\n else:\n break\n conta_linha += 1\n conta_coluna -= 1\n if len(movimentos) == 0:\n movimentos = [[]]\n return movimentos, pulos\n\n def verifica_vencedor(self):\n\n resp1, resp2 = getRandomPosIA(self.tabuleiro)\n if resp1 == None:\n return 'o'\n\n x = sum([contador.count('x') + contador.count('X') for contador in self.tabuleiro])\n o = sum([contador.count('o') + contador.count('O') for contador in self.tabuleiro])\n\n if x == 0:\n return 'o'\n\n if o == 0:\n return 'x'\n\n if x == 1 and o == 1:\n return 'empate'\n\n if self.cedula_selecionada:\n if not self.movimentos_possiveis(self.cedula_selecionada)[0]:\n if x == 1 and self.turno % 2 == 0:\n return 'o'\n if o == 1 and self.turno % 2 == 1:\n return 'x'\n\n if not self.existe_possivel():\n return 'empate'\n\n return None\n\n def desenha(self):\n matriz = []\n\n for i in range(8):\n if i % 2 == 0:\n matriz.append(['#', '-', '#', '-', '#', '-', '#', '-'])\n else:\n matriz.append(['-', '#', '-', '#', '-', '#', '-', '#'])\n\n y = 0\n for l in range(len(matriz)):\n x = 0\n for c in range(len(matriz[l])):\n if matriz[l][c] == '#':\n pygame.draw.rect(tela, VERDE_ESCURO, (x, y, TAMANHO_QUADRADO, TAMANHO_QUADRADO))\n else:\n pygame.draw.rect(tela, BEGE, (x, y, TAMANHO_QUADRADO, TAMANHO_QUADRADO))\n x += TAMANHO_QUADRADO\n y += TAMANHO_QUADRADO\n\n if self.cedula_selecionada:\n obrigatorios = self.todos_obrigatorios()\n movs = self.movimentos_possiveis(self.cedula_selecionada)\n\n if obrigatorios != {}:\n if (self.cedula_selecionada[0], self.cedula_selecionada[1]) not in obrigatorios:\n x_vermelho = ALTURA / 8 * self.cedula_selecionada[1]\n y_vermelho = ALTURA / 8 * self.cedula_selecionada[0]\n pygame.draw.rect(tela, VERMELHO_CLARO, (x_vermelho, y_vermelho, 80, 80))\n else:\n if movs[0] == []:\n x_vermelho = ALTURA / 8 * self.cedula_selecionada[1]\n y_vermelho = ALTURA / 8 * self.cedula_selecionada[0]\n\n pygame.draw.rect(tela, VERMELHO_CLARO, (x_vermelho, y_vermelho, 80, 80))\n else:\n for i in range(len(movs[0])):\n x_possivel = ALTURA / 8 * movs[0][i][1]\n y_possivel = ALTURA / 8 * movs[0][i][0]\n\n pygame.draw.rect(tela, YELLOW, (x_possivel, y_possivel, 80, 80))\n else:\n if self.pulando:\n x_vermelho = ALTURA / 8 * self.cedula_selecionada[1]\n y_vermelho = ALTURA / 8 * self.cedula_selecionada[0]\n\n pygame.draw.rect(tela, VERMELHO_CLARO, (x_vermelho, y_vermelho, 80, 80))\n else:\n if movs[0] == []:\n x_vermelho = ALTURA / 8 * self.cedula_selecionada[1]\n y_vermelho = ALTURA / 8 * self.cedula_selecionada[0]\n\n pygame.draw.rect(tela, VERMELHO_CLARO, (x_vermelho, y_vermelho, 80, 80))\n else:\n for i in range(len(movs[0])):\n x_possivel = ALTURA / 8 * movs[0][i][1]\n y_possivel = ALTURA / 8 * movs[0][i][0]\n\n pygame.draw.rect(tela, YELLOW, (x_possivel, y_possivel, 80, 80))\n\n for l in range(len(self.tabuleiro)):\n for c in range(len(self.tabuleiro[l])):\n elemento = self.tabuleiro[l][c]\n if elemento != '-':\n x = int(ALTURA / 8) * c + int(ALTURA / 16)\n y = int(ALTURA / 8) * l + int(ALTURA / 16)\n\n img = pygame.image.load('coroa.png')\n img = pygame.transform.scale(img, (60,60))\n\n if elemento.lower() == 'x':\n pygame.draw.circle(tela, PRETO, (x, y), TAMANHO_DAMA, 0)\n if elemento == 'X':\n tela.blit(img, (x - 36, y - 36))\n else:\n pygame.draw.circle(tela, BRANCO, (x, y), TAMANHO_DAMA, 0)\n if elemento == 'O':\n tela.blit(img, (x - 36, y - 36))\n\ndef fim_de_jogo(winner):\n fim = False\n while not fim:\n for evento in pygame.event.get():\n if evento.type == pygame.QUIT:\n fim = True\n pygame.quit()\n quit()\n if evento.type == pygame.KEYDOWN or evento.type == pygame.MOUSEBUTTONDOWN:\n fim = True\n\n tela.fill(CORAL)\n fonte = pygame.font.SysFont('comicsansms', 40)\n\n surface_texto, rect_texto = None, None\n\n if winner == \"empate\":\n surface_texto, rect_texto = texto_na_tela(\"EMPATE !\", fonte, BRANCO)\n elif winner == \"x\":\n surface_texto, rect_texto = texto_na_tela(\"CPU VENCEU O JOGO\", fonte, PRETO)\n elif winner == \"o\":\n surface_texto, rect_texto = texto_na_tela(\"PARABÉNS VOCÊ GANHOU!!\", fonte, BRANCO)\n rect_texto.center = ((LARGURA / 2), ALTURA / 3)\n tela.blit(surface_texto, rect_texto)\n\n fonte = pygame.font.Font(None, 30)\n voltar = fonte.render('Pressione qualquer tecla para jogar novamente.', False, CORAL)\n\n tela.blit(voltar, (25, 550))\n\n pygame.display.update()\n clock.tick(60)\n\n\ndef coluna_clicada(pos):\n x = pos[0]\n for i in range(1, 8):\n if x < i * ALTURA / 8:\n return i - 1\n return 7\n\ndef texto_na_tela(text, font, color):\n\ttxt = font.render(text, True, color)\n\treturn txt, txt.get_rect()\n\ndef linha_clicada(pos):\n y = pos[1]\n for i in range(1, 8):\n if y < i * ALTURA / 8:\n return i - 1\n return 7\n\ndef getRandomPosIA(tabuleiro):\n linha_v = []\n coluna_v = []\n for i in range(len(tabuleiro)):\n for j in range(len(tabuleiro[i])):\n if tabuleiro[i][j].lower() == 'x':\n if i < 7:\n if j < 7:\n if tabuleiro[i + 1][j + 1] == '-':\n linha, coluna = i, j\n linha_v.append(linha)\n coluna_v.append(coluna)\n if tabuleiro[i + 1][j - 1] == '-':\n linha, coluna = i, j\n linha_v.append(linha)\n coluna_v.append(coluna)\n else:\n if tabuleiro[i][j] == 'X':\n if j < 7:\n if tabuleiro[i - 1][j + 1] == '-':\n linha, coluna = i, j\n linha_v.append(linha)\n coluna_v.append(coluna)\n elif j == 7:\n if tabuleiro[i - 1][j - 1] == '-':\n linha, coluna = i, j\n linha_v.append(linha)\n coluna_v.append(coluna)\n\n if len(linha_v) > 0:\n i = random.randrange(0,len(linha_v),1)\n return linha_v[i], coluna_v[i]\n else:\n return None, None\n\ndef IAsimples(jogo, vez):\n pulo = []\n if(jogo.cedula_selecionada != None):\n obrigatorios = jogo.movimento_obrigatorio(jogo.cedula_selecionada)\n if obrigatorios != ([],[]):\n linha_origem = jogo.cedula_selecionada[0]\n coluna_origem = jogo.cedula_selecionada[1]\n linha_dest = obrigatorios[0][0][0]\n coluna_dest = obrigatorios[0][0][1]\n else:\n jogo.cedula_selecionada = None\n return jogo\n else:\n obrigatorios = jogo.todos_obrigatorios_IA()\n \n if obrigatorios != {}: \n for i in range(len(jogo.tabuleiro)):\n for j in range(len(jogo.tabuleiro[1])):\n if(i,j) in obrigatorios:\n linha_origem = i\n coluna_origem = j\n resp = obrigatorios[(i,j)]\n linha_dest = resp[0][0]\n coluna_dest = resp[0][1]\n break\n\n y_origem = ALTURA / 8 * linha_origem\n x_origem = ALTURA / 8 * coluna_origem\n\n y_d = ALTURA / 8 * linha_dest\n x_d = ALTURA / 8 * coluna_dest\n\n y_dest = int(ALTURA / 8) * linha_dest + int(ALTURA / 16)\n x_dest = int(ALTURA / 8) * coluna_dest + int(ALTURA / 16)\n\n y = int(ALTURA / 8) * linha_origem + int(ALTURA / 16)\n x = int(ALTURA / 8) * coluna_origem + int(ALTURA / 16)\n\n\n img = pygame.image.load('coroa.png')\n img = pygame.transform.scale(img, (60,60))\n\n pygame.draw.rect(tela, YELLOW, (x_origem, y_origem, 80, 80))\n pygame.draw.circle(tela, PRETO, (int(x), int(y)), TAMANHO_DAMA, 0)\n if jogo.tabuleiro[linha_origem][coluna_origem] == 'X':\n tela.blit(img, (x_origem, y_origem))\n pygame.display.update()\n time.sleep(0.5)\n pygame.draw.circle(tela, FOSCO, (int(x_dest), int(y_dest)), TAMANHO_DAMA, 0)\n pygame.display.update()\n time.sleep(0.5)\n pygame.draw.rect(tela, VERDE_ESCURO, (x_d, y_d, 80, 80))\n pygame.draw.rect(tela, VERDE_ESCURO, (x_origem, y_origem, 80, 80))\n pygame.draw.circle(tela, PRETO, (int(x), int(y)), TAMANHO_DAMA, 0)\n pygame.display.update()\n time.sleep(0.5)\n\n print('lo: ', linha_origem, ' co: ', coluna_origem, 'ld: ', linha_dest, 'cd: ', coluna_dest)\n print(jogo.tabuleiro[linha_origem][coluna_origem])\n if jogo.tabuleiro[linha_origem][coluna_origem] == 'x':\n print('eh sim')\n if linha_dest > linha_origem:\n pulo.append(linha_origem + 1)\n else:\n pulo.append(linha_origem - 1)\n if coluna_dest > coluna_origem:\n pulo.append(coluna_origem + 1)\n else:\n pulo.append(coluna_origem - 1)\n else:\n print('eh nao')\n if linha_dest > linha_origem:\n pulo.append(linha_dest - 1)\n else:\n pulo.append(linha_dest + 1)\n if coluna_dest > coluna_origem:\n pulo.append(coluna_dest - 1)\n else:\n pulo.append(coluna_dest + 1)\n\n char = jogo.tabuleiro[linha_origem][coluna_origem]\n jogo.tabuleiro[linha_dest][coluna_dest] = char\n jogo.tabuleiro[linha_origem][coluna_origem] = '-'\n\n if (linha_dest == 7):\n if jogo.movimentos_possiveis((linha_dest, coluna_dest))[0] == None:\n jogo.tabuleiro[linha_dest][coluna_dest] = char.upper()\n\n print('pulo: ', pulo)\n jogo.tabuleiro[pulo[0]][pulo[1]] = '-'\n pygame.display.update()\n jogo.cedula_selecionada = [linha_dest, coluna_dest]\n jogo = IAsimples(jogo,2)\n\n\n elif obrigatorios == {} and jogo.cedula_selecionada == None and vez == 1:\n linha_origem, coluna_origem = getRandomPosIA(jogo.tabuleiro)\n if linha_origem != None and coluna_origem != None:\n envia = [linha_origem, coluna_origem]\n opcionais = jogo.movimentos_possiveis(envia)\n if len(opcionais) == 0:\n jogo.estado = ('game over')\n return jogo\n print('opcionais', opcionais)\n if({} not in opcionais): ### BUG FIXED\n linha_dest = opcionais[0][0][0]\n coluna_dest = opcionais[0][0][1]\n\n y_origem = ALTURA / 8 * linha_origem\n x_origem = ALTURA / 8 * coluna_origem\n\n y_d = ALTURA / 8 * linha_dest\n x_d = ALTURA / 8 * coluna_dest\n\n y_dest = int(ALTURA / 8) * linha_dest + int(ALTURA / 16)\n x_dest = int(ALTURA / 8) * coluna_dest + int(ALTURA / 16)\n\n y = int(ALTURA / 8) * linha_origem + int(ALTURA / 16)\n x = int(ALTURA / 8) * coluna_origem + int(ALTURA / 16)\n\n pygame.draw.rect(tela, YELLOW, (x_origem, y_origem, 80, 80))\n pygame.draw.circle(tela, PRETO, (int(x), int(y)), TAMANHO_DAMA, 0)\n pygame.display.update()\n time.sleep(1)\n pygame.draw.rect(tela, VERDE_ESCURO, (x_d, y_d, 80, 80))\n pygame.draw.rect(tela, VERDE_ESCURO, (x_origem, y_origem, 80, 80))\n pygame.draw.circle(tela, PRETO, (int(x), int(y)), TAMANHO_DAMA, 0)\n pygame.display.update()\n time.sleep(1)\n\n char = jogo.tabuleiro[linha_origem][coluna_origem]\n jogo.tabuleiro[linha_dest][coluna_dest] = char\n jogo.tabuleiro[linha_origem][coluna_origem] = '-'\n\n if (linha_dest == 7):\n if jogo.movimentos_possiveis((linha_dest, coluna_dest))[0] == None:\n jogo.tabuleiro[linha_dest][coluna_dest] = char.upper()\n\n jogo.cedula_selecionada = None\n\n else:\n jogo.estado = ('game over')\n return jogo\n else:\n jogo.cedula_selecionada = None\n vencedor = jogo.verifica_vencedor()\n\n if vencedor != None:\n jogo.estado = ('game over')\n\n if(jogo.cedula_selecionada == None and linha_dest == 7):\n jogo.tabuleiro[linha_dest][coluna_dest] = jogo.tabuleiro[linha_dest][coluna_dest].upper()\n\n return jogo\n\ndef loop_jogo():\n sair = False\n\n jogo = Jogo()\n print(\"tamanho = \" + str(sys.getsizeof(jogo)))\n while not sair:\n if jogo.jogadores[jogo.turno % 2] == 'o':\n for evento in pygame.event.get():\n if evento.type == pygame.QUIT:\n sair = True\n pygame.quit()\n quit()\n if evento.type == pygame.MOUSEBUTTONDOWN:\n jogo.jogadas(pygame.mouse.get_pos())\n else:\n #jogo.cedula_selecionada = None\n time.sleep(0.5)\n jogo = IAsimples(jogo, 1)\n jogo.proximo_turno()\n\n tela.fill(PRETO)\n jogo.desenha()\n\n vencedor = jogo.verifica_vencedor()\n\n if vencedor is not None:\n fim_de_jogo(vencedor)\n sair = True\n\n\n pygame.display.update()\n clock.tick(60)\n\n\n\nloop_jogo()\npygame.quit()\nquit()\n","sub_path":"dama.py","file_name":"dama.py","file_ext":"py","file_size_in_byte":36012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"138850545","text":"# -*- coding: utf-8 -*-\nimport random\n\ndef throw():\n throws = []\n n = 0\n i = int(input(\"Please input a number of throws: \"))\n while n < i:\n randthrow = random.randrange(0,2)\n throws.append(randthrow)\n n += 1\n heads = throws.count(1)\n tails = throws.count(0)\n print(\"You threw \" + str(heads) + \" heads and \" + str(tails) + \" tails.\")\nthrow()\n","sub_path":"cointhrow.py","file_name":"cointhrow.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"594370085","text":"# -*- coding: utf-8 -*-\n# Ref: Yuxin Wu file GAN.py\n# Author: VQNam\n\nimport tensorflow as tf\nimport numpy as np\nfrom tf_utils.ar_layers import *\nfrom tf_utils.common import *\nfrom tf_utils.distributions import *\nfrom tensorpack import *\nfrom tensorpack import ModelDescBase, StagingInput, TowerTrainer\nfrom tensorpack.tfutils.tower import TowerContext, TowerFuncWrapper\nfrom tensorpack.tfutils.summary import *\nfrom tensorpack.utils.argtools import memoized_method\n\n# from utils import *\nfrom encoder import encoder\nfrom decoder import decoder\nfrom predicter import predict\nfrom multi_iaf import multi_iaf\nfrom build_loss import build_losses\n\n\nclass VDEModelDesc(ModelDescBase):\n def __init__(self, hps):\n self.hps = hps\n self.l_mask = np.tril(np.ones([self.hps.n_z, self.hps.n_z]), k=0).astype(np.float32)\n\n\n def inputs(self):\n return [\n tf.TensorSpec((None, self.hps.T, self.hps.D), tf.float32, 'x'),\n tf.TensorSpec((None, self.hps.T, self.hps.D), tf.float32, 'x_con'),\n tf.TensorSpec((None, self.hps.Tau, self.hps.C), tf.float32, 'y_one_hot')\n ]\n\n def collect_variables(self, encode_scope='encode', predict_scope='predict', decode_scope='decode'):\n self.encode_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, encode_scope)\n assert self.encode_vars, \"Encode graph not found\"\n\n self.predict_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, predict_scope)\n assert self.predict_vars, \"Predict graph not found\"\n\n self.decode_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, decode_scope)\n assert self.decode_vars, \"Decode graph not found\"\n\n def encoder(self, x):\n return encoder(self, x)\n\n def predict(self, z):\n return predict(self, z)\n\n def decoder(self, z):\n return decoder(self, z)\n\n def multi_iaf(self, z):\n return multi_iaf(self, z)\n\n def build_losses(self, y_one_hot, x_hat):\n build_losses(self, y_one_hot, x_hat)\n\n def build_graph(self, x, x_hat, y_one_hot):\n\n with tf.variable_scope('encode', reuse=False):\n self.z_mu, self.z_lsgm, self.z = self.encoder(x)\n\n if self.hps.is_IAF:\n with tf.variable_scope('encode', reuse=False):\n self.z_iaf, self.z_lgsm_iaf = self.multi_iaf(self.z)\n\n with tf.variable_scope('predict', reuse=False):\n self.y_pred = self.predict(self.z_iaf)\n\n with tf.variable_scope('decode', reuse=False):\n self.x_con = self.decoder(self.z_iaf)\n\n with tf.variable_scope('encode', reuse=True):\n self.z_tau_mu, self.z_tau_lsgm, self.z_tau = self.encoder(self.x_con)\n self.z_tau_iaf, self.z_tau_lsgm_iaf = self.multi_iaf(self.z_tau)\n else:\n with tf.variable_scope('predict', reuse=False):\n self.y_pred = self.predict(self.z)\n with tf.variable_scope('decode', reuse=False):\n self.x_con = self.decoder(self.z)\n with tf.variable_scope('encode', reuse=True):\n self.z_tau_mu, self.z_tau_lsgm, self.z_tau = self.encoder(self.x_con)\n\n self.build_losses(y_one_hot=y_one_hot, x_hat=x_hat)\n\n self.collect_variables()\n\n def optimizer(self):\n optimizer_origin = tf.train.AdamOptimizer(learning_rate=self.hps.learning_rate, beta1=0.5, epsilon=1e-3)\n\n return tf.contrib.estimator.clip_gradients_by_norm(optimizer_origin, clip_norm=1.0)\n\n @memoized_method\n def get_optimizer(self):\n return self.optimizer()\n\n\nclass VDETrainer(TowerTrainer):\n\n def __init__(self, input, model, num_gpu=1):\n \"\"\"\n Args:\n input (InputSource):\n model (VDEModelDesc):\n \"\"\"\n super(VDETrainer, self).__init__()\n assert isinstance(model, VDEModelDesc), model\n\n if num_gpu > 1:\n input = StagingInput(input)\n\n # Setup input\n cbs = input.setup(model.get_input_signature())\n self.register_callback(cbs)\n\n assert num_gpu <= 1, \"Should be 1 gpu for small data\"\n\n self._build_vde_trainer(input, model)\n\n def _build_vde_trainer(self, input, model):\n \"\"\"\n Args:\n input (InputSource):\n model (VDEModelDesc):\n \"\"\"\n # Build the graph\n self.tower_func = TowerFuncWrapper(model.build_graph, model.get_input_signature())\n with TowerContext('', is_training=True):\n self.tower_func(*input.get_input_tensors())\n opt = model.get_optimizer()\n\n with tf.name_scope('optimize'):\n vde_min = opt.minimize(model.total_loss,\n var_list=[model.encode_vars, model.predict_vars, model.decode_vars], name='train_op')\n self.train_op = vde_min\n","sub_path":"src/models_VAE/iaf_models/VDE.py","file_name":"VDE.py","file_ext":"py","file_size_in_byte":4813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"633738533","text":"import json\nimport requests\n\nclass GetHandelsbankenAccountTransactions:\n def __init__(self, account):\n self.account = account\n self.url = \"https://sandbox.handelsbanken.com/openbanking/psd2/v2/accounts/{0}/transactions\".format(account)\n self.payload={}\n self.headers = {\n 'Authorization': 'Bearer MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI1',\n 'PSU-IP-Address': '192.102.28.2',\n 'TPP-Request-ID': 'c8271b81-4229-5a1f-bf9c-758f11c1f5b1',\n 'TPP-Transaction-ID': '6b24ce42-237f-4303-a917-cf778e5013d6',\n 'X-IBM-Client-Id': '62dec6b3-1814-4ca2-864a-c33b91ef6007',\n 'Accept': 'application/json'\n }\n\n def run(self):\n response = requests.request(\"GET\", self.url, headers=self.headers, data=self.payload)\n parsed = json.loads(response.text)\n print(json.dumps(parsed, indent=3, separators=(',', ':'), sort_keys=True))\n\n","sub_path":"BanksTransactions/HandelsBanken/GetHandelsbankenAccountTransactions.py","file_name":"GetHandelsbankenAccountTransactions.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"279510839","text":"from typing import Generic, TypeVar, Optional, List\n\nT = TypeVar(\"T\")\n\n\nclass ListNode(Generic[T]):\n val: T\n next: Optional[\"ListNode[T]\"]\n\n def __init__(self, val: T):\n self.val = val\n self.next = None\n\n\ndef create_linked_list(values: List[T]) -> Optional[ListNode[T]]:\n \"\"\"Create a linked-list into a list\n\n Arguments:\n values {List[T]} -- values of list\n\n Returns:\n Optional[ListNode[T]] -- head of the linked-list\n \"\"\"\n node = None\n for val in reversed(values):\n prev = ListNode(val)\n prev.next = node\n node = prev\n\n return node\n\n\ndef create_list(head: Optional[ListNode[T]]) -> List[T]:\n \"\"\"Convert a linked-list into a list\n\n Arguments:\n head {Optional[ListNode[T]]} -- The head of linked-list\n\n Returns:\n List[T] -- list of values of linked-list\n \"\"\"\n values: List[T] = []\n\n while head:\n values.append(head.val)\n head = head.next\n\n return values\n","sub_path":"python/leetcode/lib/list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"590184471","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n\turl(r'^$', views.index),\n\turl(r'^register$', views.register),\n\turl(r'^login$', views.login),\n\turl(r'^secrets$', views.secrets),\n\turl(r'^secret_submit$', views.secret_submit),\n\turl(r'^like_button/(?P\\d+)$', views.like_button),\n\turl(r'^delete/(?P\\d+)$', views.delete),\n\turl(r'^unlike/(?P\\d+)$', views.unlike),\n\turl(r'^popular/$', views.popular)\n]","sub_path":"apps/first_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"111443654","text":"\"\"\"Test the S3StorageBroker self description metadata.\"\"\"\n\nfrom . import tmp_uuid_and_uri # NOQA\nfrom . import (\n _key_exists_in_storage_broker,\n _get_data_structure_from_key,\n _get_unicode_from_key\n)\n\n\ndef test_writing_of_dtool_structure_file(tmp_uuid_and_uri): # NOQA\n from dtoolcore import ProtoDataSet, generate_admin_metadata\n from dtool_s3 import __version__\n\n # Create a proto dataset.\n uuid, dest_uri = tmp_uuid_and_uri\n name = \"test_dtool_structure_file\"\n admin_metadata = generate_admin_metadata(name)\n admin_metadata[\"uuid\"] = uuid\n proto_dataset = ProtoDataSet(\n uri=dest_uri,\n admin_metadata=admin_metadata,\n config_path=None\n )\n proto_dataset.create()\n\n # Check that the \".dtool/structure.json\" file exists.\n expected_s3_key = uuid + '/structure.json'\n assert _key_exists_in_storage_broker(\n proto_dataset._storage_broker,\n expected_s3_key\n )\n\n expected_content = {\n \"dataset_registration_key\": \"dtool-{}\".format(uuid),\n \"data_key_infix\": \"data\",\n \"fragment_key_infix\": \"fragments\",\n \"overlays_key_infix\": \"overlays\",\n \"annotations_key_infix\": \"annotations\",\n \"tags_key_infix\": \"tags\",\n \"structure_key_suffix\": \"structure.json\",\n \"dtool_readme_key_suffix\": \"README.txt\",\n \"dataset_readme_key_suffix\": \"README.yml\",\n \"manifest_key_suffix\": \"manifest.json\",\n \"admin_metadata_key_suffix\": \"dtool\",\n \"http_manifest_key\": \"http_manifest.json\",\n \"storage_broker_version\": __version__,\n }\n actual_content = _get_data_structure_from_key(\n proto_dataset._storage_broker,\n expected_s3_key\n )\n assert expected_content == actual_content\n\n\ndef test_writing_of_dtool_readme_file(tmp_uuid_and_uri): # NOQA\n from dtoolcore import ProtoDataSet, generate_admin_metadata\n\n # Create a proto dataset.\n uuid, dest_uri = tmp_uuid_and_uri\n name = \"test_dtool_readme_file\"\n admin_metadata = generate_admin_metadata(name)\n admin_metadata[\"uuid\"] = uuid\n proto_dataset = ProtoDataSet(\n uri=dest_uri,\n admin_metadata=admin_metadata,\n config_path=None\n )\n proto_dataset.create()\n\n # Check that the \".dtool/README.txt\" file exists.\n expected_s3_key = uuid + '/README.txt'\n assert _key_exists_in_storage_broker(\n proto_dataset._storage_broker,\n expected_s3_key\n )\n\n actual_content = _get_unicode_from_key(\n proto_dataset._storage_broker,\n expected_s3_key\n )\n assert actual_content.startswith(\"README\")\n","sub_path":"tests/test_self_description.py","file_name":"test_self_description.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"299579621","text":"# coding:utf-8\nfrom virt_who import *\nfrom virt_who.base import Base\nfrom virt_who.register import Register\nfrom virt_who.testing import Testing\n\nclass Testcase(Testing):\n def test_run(self):\n self.vw_case_info(os.path.basename(__file__), case_id='RHEL-137100')\n register_type = self.get_config('register_type')\n if 'stage' in register_type:\n self.vw_case_skip(register_type)\n self.vw_case_init()\n\n # Case Config\n results = dict()\n self.vw_option_enable('[global]', '/etc/virt-who.conf')\n self.vw_option_enable('debug', '/etc/virt-who.conf')\n self.vw_option_update_value('debug', 'True', '/etc/virt-who.conf')\n config_name = \"virtwho-config\"\n config_file = \"/etc/virt-who.d/{0}.conf\".format(config_name)\n self.vw_etc_d_mode_create(config_name, config_file)\n\n hypervisor_type = self.get_config('hypervisor_type')\n register_config = self.get_register_config()\n ssh_sat = register_config['ssh_sat']\n default_org = register_config['owner']\n vdc_physical = register_config['vdc']\n vdc_virtual = register_config['vdc_bonus']\n limit_sku = register_config['limit']\n physical_vdc_pool_id = self.system_sku_attr(self.ssh_host(), vdc_physical, \"physical\")['pool_id']\n physical_limit_pool_id= self.system_sku_attr(self.ssh_host(), limit_sku, \"physical\")['pool_id']\n default_org_id = self.satellite_org_id_get(ssh_sat, register_config, default_org)\n ak_list = {\n 'libvirt-local': 'libvirt-local_ak',\n 'libvirt-remote': 'libvirt-remote_ak',\n 'esx': 'esx_ak',\n 'hyperv': 'hyperv_ak',\n 'xen': 'xen_ak',\n 'vdsm': 'vdsm_ak',\n 'rhevm': 'rhevm_ak',\n 'kubevirt': 'kubevirt_ak'\n }\n\n ak_name = ak_list[hypervisor_type]\n host_uuid = self.get_hypervisor_hostuuid()\n host_name = self.get_hypervisor_hostname()\n guest_name = self.get_hostname(self.ssh_guest())\n guest_uuid = self.get_hypervisor_guestuuid()\n\n # Case Steps\n try:\n logger.info(\">>>step1: Register host with activation key, and start to run virt-who\")\n self.satellite_active_key_create(ssh_sat, register_config, ak_name, default_org_id)\n self.system_register_with_ak(self.ssh_host(), register_config, ak_name)\n data, tty_output, rhsm_output = self.vw_start(exp_send=1)\n res = self.op_normal_value(data, exp_error=0, exp_thread=1, exp_send=1)\n results.setdefault('step1', []).append(res)\n\n logger.info(\">>>step2: Attach physical vdc and limit sku to hypervisor, and check virtual sku in guest\")\n self.system_sku_unattach(self.ssh_host())\n self.vw_web_attach(host_name, host_uuid, physical_limit_pool_id)\n self.vw_web_attach(host_name, host_uuid, physical_vdc_pool_id)\n virtual_vdc_pool_id = self.system_sku_attr(self.ssh_guest(), vdc_virtual, \"virtual\")['pool_id']\n virtual_limit_pool_id = self.system_sku_attr(self.ssh_guest(), limit_sku, \"virtual\")['pool_id']\n if not virtual_vdc_pool_id and not virtual_limit_pool_id:\n results.setdefault('step2', []).append(False)\n\n logger.info(\">>>step3: Register guest with auto-attach enabled by default, no sku in the key\")\n # guest will be auto-attached the best matched pool, vdc has the high priority\n self.system_register_with_ak(self.ssh_guest(), register_config, ak_name)\n output = self.system_sku_consumed(self.ssh_guest())\n res1 = self.vw_msg_search(output, virtual_limit_pool_id, exp_exist=False)\n res2 = self.vw_msg_search(output, virtual_vdc_pool_id, exp_exist=True)\n results.setdefault('step3', []).append(res1)\n results.setdefault('step3', []).append(res2)\n\n logger.info(\">>>step4: Re-register guest with auto-attach enabled by default, but only add virtual_vdc to the key\")\n # guest will be auto-attached with the only virtual vdc\n vdc_katello_id = self.satellite_katello_id(ssh_sat, register_config, virtual_vdc_pool_id)\n self.satellite_active_key_attach_sku(ssh_sat, register_config, ak_name, vdc_katello_id, default_org_id)\n self.system_register_with_ak(self.ssh_guest(), register_config, ak_name)\n output = self.system_sku_consumed(self.ssh_guest())\n res1 = self.vw_msg_search(output, virtual_limit_pool_id, exp_exist=False)\n res2 = self.vw_msg_search(output, virtual_vdc_pool_id, exp_exist=True)\n results.setdefault('step4', []).append(res1)\n results.setdefault('step4', []).append(res2)\n\n logger.info(\">>>step5: Re-register guest with auto-attach enabled by default, both virtual_vdc and virtual_limit are added to the key\")\n # guest will be auto-attached the best matched pool, vdc has the high priority\n limit_katello_id = self.satellite_katello_id(ssh_sat, register_config, virtual_limit_pool_id)\n self.satellite_active_key_attach_sku(ssh_sat, register_config, ak_name, limit_katello_id, default_org_id)\n self.system_register_with_ak(self.ssh_guest(), register_config, ak_name)\n output = self.system_sku_consumed(self.ssh_guest())\n res1 = self.vw_msg_search(output, virtual_limit_pool_id, exp_exist=False)\n res2 = self.vw_msg_search(output, virtual_vdc_pool_id, exp_exist=True)\n results.setdefault('step5', []).append(res1)\n results.setdefault('step5', []).append(res2)\n\n logger.info(\">>>step6: Re-register guest with auto-attach disabled, both virtual_vdc and virtual_limit are added to the key\")\n # guest will be auto-attached with these two skus\n self.satellite_active_key_auto_attach_enable(ssh_sat, register_config, ak_name, default_org_id, auto_attach='false')\n self.system_register_with_ak(self.ssh_guest(), register_config, ak_name)\n output = self.system_sku_consumed(self.ssh_guest())\n res1 = self.vw_msg_search(output, virtual_limit_pool_id, exp_exist=True)\n res2 = self.vw_msg_search(output, virtual_vdc_pool_id, exp_exist=True)\n results.setdefault('step6', []).append(res1)\n results.setdefault('step6', []).append(res2)\n\n logger.info(\">>>step7: Re-register guest with auto-attach disabled, no sku in the key\")\n # guest will not be auto-attached to any sku\n self.satellite_active_key_unattach_sku(ssh_sat, register_config, ak_name, limit_katello_id, default_org_id)\n self.satellite_active_key_unattach_sku(ssh_sat, register_config, ak_name, vdc_katello_id, default_org_id)\n self.system_register_with_ak(self.ssh_guest(), register_config, ak_name)\n output = self.system_sku_consumed(self.ssh_guest(), exp_exist=False)\n res1 = self.vw_msg_search(output, 'No consumed subscription pools', exp_exist=True)\n results.setdefault('step7', []).append(res1)\n except:\n results.setdefault('step7', []).append(False)\n pass\n\n finally:\n logger.info(\">>>Finally step: Clear environment\")\n self.vw_web_host_delete(host_name, host_uuid)\n self.vw_web_host_delete(guest_name, guest_uuid)\n self.satellite_active_key_delete(ssh_sat, register_config, ak_name, default_org_id)\n\n # Case Result\n notes = list()\n notes.append(\"Bug(Step3,Step5): Which SKU has the high priority to auto-attach?\")\n notes.append(\"Bug: https://bugzilla.redhat.com/show_bug.cgi?id=1712821\")\n self.vw_case_result(results, notes)\n","sub_path":"tests/tier2/tc_2044_subscribe_guest_with_activation_key.py","file_name":"tc_2044_subscribe_guest_with_activation_key.py","file_ext":"py","file_size_in_byte":7816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"325404890","text":"def readinput():\n na,nb=list(map(int,input().split()))\n a=list(map(int,input().split()))\n b=list(map(int,input().split()))\n return na,nb,a,b\n\ndef main(na,nb,a,b):\n seta=set(a)\n setb=set(b)\n uab=seta | setb\n iab=seta & setb\n ans=len(iab)/len(uab)\n return ans\n\nif __name__=='__main__':\n na,nb,a,b=readinput()\n ans=main(na,nb,a,b)\n print(ans)\n","sub_path":"AtCoder/ARC033/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"5804655","text":"# python for 循环\nzodiac = \"鼠牛虎兔龙蛇马羊猴鸡狗猪\"\nfor x in zodiac:\n if \"鸡\" == x:\n print(x)\n elif \"猪\" == x:\n print(str(2019) + \": \" + x)\n else:\n print(\"else:\" + x)\n# 1到100循环相加\nsum = 0\n# range(1, 101) 包前不包后\nfor i in range(1, 101):\n sum += i\nprint(sum)\n# 循环年份 获取生肖 并完成字符串替换\nfor year in range(2000, 2020):\n print(\"%s 年的生肖是: %s\" % (year, zodiac[year % 12 - 4]))\n","sub_path":"logic/ForCycle.py","file_name":"ForCycle.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"374448889","text":"from wasmer import wasi, Store, ImportObject, Module, Instance\nfrom enum import IntEnum\nimport os\nimport pytest\nimport subprocess\nimport sys\n\nhere = os.path.dirname(os.path.realpath(__file__))\nTEST_BYTES = open(here + '/wasi.wasm', 'rb').read()\n\ndef test_wasi_version():\n assert issubclass(wasi.Version, IntEnum)\n assert len(wasi.Version) == 3\n assert wasi.Version.LATEST == 1\n assert wasi.Version.SNAPSHOT0 == 2\n assert wasi.Version.SNAPSHOT1 == 3\n\ndef test_wasi_get_version():\n assert wasi.get_version(Module(Store(), TEST_BYTES), strict=True) == wasi.Version.SNAPSHOT1\n\ndef test_wasi_state_builder():\n state_builder = \\\n wasi.StateBuilder(\"test-program\"). \\\n argument(\"--foo\"). \\\n environments({\"ABC\": \"DEF\", \"X\": \"YZ\"}). \\\n map_directory(\"the_host_current_dir\", \".\") \n\n assert isinstance(state_builder, wasi.StateBuilder)\n\ndef test_wasi_env():\n assert isinstance(wasi.StateBuilder(\"foo\").finalize(), wasi.Environment)\n\ndef test_wasi_import_object():\n env = wasi.StateBuilder(\"foo\").finalize()\n\n assert isinstance(env.generate_import_object(Store(), wasi.Version.LATEST), ImportObject)\n\ndef test_wasi_env_memory():\n store = Store()\n wasi_env = wasi.StateBuilder(\"foo\").finalize()\n import_object = wasi_env.generate_import_object(store, wasi.Version.LATEST)\n\n instance = Instance(Module(store, TEST_BYTES), import_object)\n\ndef test_wasi():\n store = Store()\n wasi_env = \\\n wasi.StateBuilder(\"test-program\"). \\\n argument(\"--foo\"). \\\n environments({\"ABC\": \"DEF\", \"X\": \"YZ\"}). \\\n map_directory(\"the_host_current_dir\", \".\"). \\\n finalize()\n import_object = wasi_env.generate_import_object(store, wasi.Version.LATEST)\n\n instance = Instance(Module(store, TEST_BYTES), import_object)\n instance.exports._start()\n","sub_path":"tests/test_wasi.py","file_name":"test_wasi.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"146563998","text":"#!/usr/bin/env python\n# coding=utf-8\n\nimport numpy as np\nimport tensorflow as tf\nfrom keras.layers import Dense, Input, Lambda\nfrom keras.models import Model\nfrom keras import backend as keras\nfrom keras.activations import softmax, tanh\nfrom keras.engine.topology import Layer\n\n\ndef single_attention_block(inputs):\n x = inputs\n\n # tensorflow like\n w = tf.get_variable('ab_0_w', shape=[1024, 1])\n x = tf.matmul(x, w)\n # x = tf.exp(x)\n # x = tf.div(x, tf.reduce_sum(x))\n x = tf.nn.softmax(x)\n\n x = tf.matmul(tf.transpose(x), inputs)\n\n return x\n\n\ndef cascaded_attention_block(inputs):\n x = inputs\n\n # tensorflow like\n w = tf.get_variable('ab_1_w', shape=[1024, 1024])\n b = tf.get_variable('ab_1_b', shape=[1024])\n x = tf.add(tf.matmul(x, w), b)\n x = tf.nn.tanh(x)\n\n return x\n\n\nclass SingleAttentionBlock(Layer):\n def __init__(self, output_dim, **kwargs):\n assert output_dim == 1\n self.output_dim = output_dim\n super(SingleAttentionBlock, self).__init__(**kwargs)\n\n def build(self, input_shape):\n self.kernel = self.add_weight(name='kernel',\n shape=(input_shape[1], self.output_dim),\n initializer='uniform',\n trainable=True)\n super(SingleAttentionBlock, self).build(input_shape)\n\n def call(self, x):\n inputs = x\n x = keras.dot(x, self.kernel)\n # x = softmax(x)\n x = keras.exp(x)\n x = x / keras.sum(x)\n x = keras.dot(keras.transpose(x), inputs)\n return x\n\n def compute_output_shape(self, input_shape):\n return (self.output_dim, input_shape[1])\n\n\nclass CascadedAttentionBlock(Layer):\n def __init__(self, output_dim, **kwargs):\n self.output_dim = output_dim\n super(CascadedAttentionBlock, self).__init__(**kwargs)\n\n def build(self, input_shape):\n self.kernel = self.add_weight(name='kernel',\n shape=(input_shape[1], self.output_dim),\n initializer='uniform',\n trainable=True)\n self.bias = self.add_weight(name='kernel',\n shape=(self.output_dim,),\n initializer='zero',\n trainable=True)\n super(CascadedAttentionBlock, self).build(input_shape)\n\n def call(self, x):\n x = keras.bias_add(keras.dot(x, self.kernel), self.bias)\n x = tanh(x)\n return x\n\n def compute_output_shape(self, input_shape):\n return (input_shape[0], self.output_dim)\n\ndef attention_test_tf():\n inputs = tf.placeholder(tf.float32, shape=[None, 1024])\n labels = tf.placeholder(tf.float32, shape=[None, 1024])\n\n x = inputs\n x = single_attention_block(x)\n x = cascaded_attention_block(x)\n outputs = x\n\n loss = tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=outputs)\n optimizer = tf.train.AdamOptimizer(learning_rate=1e-2).minimize(loss)\n accuracy = tf.reduce_sum(tf.cast(tf.equal(tf.argmax(labels, axis=1), tf.argmax(outputs, axis=1)), tf.int32))\n\n init = tf.global_variables_initializer()\n sess = tf.Session()\n sess.run(init)\n\n for i in range(1000000):\n num_samples = np.random.randint(1,10,(1,))[0]\n x_batch = np.random.random((num_samples, 1024))\n t_batch = np.zeros((1,1024))\n t_batch[0,np.random.randint(1,10,(1,))[0]] = 1\n [y_batch, cost, _, acc] = sess.run([outputs, loss, optimizer, accuracy], feed_dict={inputs: x_batch, labels: t_batch})\n print(np.argmax(y_batch, axis=1), cost, acc)\n\n sess.close()\n\n\ndef attention_test_keras():\n inputs = Input(shape=(1024,))\n x = inputs\n\n x = SingleAttentionBlock(1)(x)\n x = CascadedAttentionBlock(1024)(x)\n\n outputs = x\n model = Model(inputs, outputs)\n model.summary()\n\n '''Keras is disgusting!!!'''\n # TODO: model.output.shape != sess.run(model.output).shape ???\n for i in range(1):\n num_samples = np.random.randint(1,10,(1,))[0]\n x_batch = np.random.random((num_samples, 1024))\n y_batch = model.predict(x_batch)\n print(x_batch.shape, y_batch.shape)\n print(y_batch)\n print(y_batch.mean(axis=0))\n\nif __name__ == '__main__':\n attention_test_tf()\n # attention_test_keras()","sub_path":"keras-dcgan/attention.py","file_name":"attention.py","file_ext":"py","file_size_in_byte":4399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"376641352","text":"def run( x ):\n\treturn rasterio.open(x).read(1)\n\ndef sort_files( files, split_on='_', elem_month=-2, elem_year=-1 ):\n\t'''\n\tsort a list of files properly using the month and year parsed\n\tfrom the filename. This is useful with SNAP data since the standard\n\tis to name files like '_MM_YYYY.tif'. If sorted using base\n\tPythons sort/sorted functions, things will be sorted by the first char\n\tof the month, which makes thing go 1, 11, ... which sucks for timeseries\n\tthis sorts it properly following SNAP standards as the default settings.\n\n\tARGUMENTS:\n\t----------\n\tfiles = [list] list of `str` pathnames to be sorted by month and year. usually from glob.glob.\n\tsplit_on = [str] `str` character to split the filename on. default:'_', SNAP standard.\n\telem_month = [int] slice element from resultant split filename list. Follows Python slicing syntax.\n\t\tdefault:-2. For SNAP standard.\n\telem_year = [int] slice element from resultant split filename list. Follows Python slicing syntax.\n\t\tdefault:-1. For SNAP standard.\n\n\tRETURNS:\n\t--------\n\tsorted `list` by month and year ascending. \n\n\t'''\n\tmonths = [ int(fn.split('.')[0].split( split_on )[elem_month]) for fn in files ]\n\tyears = [ int(fn.split('.')[0].split( split_on )[elem_year]) for fn in files ]\n\tdf = pd.DataFrame( {'fn':files, 'month':months, 'year':years} )\n\tdf_sorted = df.sort_values( ['year', 'month' ] )\n\treturn df_sorted.fn.tolist()\n\ndef only_years( files, begin=1901, end=2100, split_on='_', elem_year=-1 ):\n\t'''\n\treturn new list of filenames where they are truncated to begin:end\n\n\tARGUMENTS:\n\t----------\n\tfiles = [list] list of `str` pathnames to be sorted by month and year. usually from glob.glob.\n\tbegin = [int] four digit integer year of the begin time default:1901\n\tend = [int] four digit integer year of the end time default:2100\n\tsplit_on = [str] `str` character to split the filename on. default:'_', SNAP standard.\n\telem_year = [int] slice element from resultant split filename list. Follows Python slicing syntax.\n\t\tdefault:-1. For SNAP standard.\n\n\tRETURNS:\n\t--------\n\tsliced `list` to begin and end year.\n\t'''\n\tyears = [ int(fn.split('.')[0].split( split_on )[elem_year]) for fn in files ]\n\tdf = pd.DataFrame( { 'fn':files, 'year':years } )\n\tdf_slice = df[ (df.year >= begin ) & (df.year <= end ) ]\n\treturn df_slice.fn.tolist()\n\n\nif __name__ == '__main__':\n\timport numpy as np\n\timport pandas as pd\n\timport os, glob, rasterio\n\tfrom multiprocessing import Pool\n\n\t# MODEL\n\tinput_path = '/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data/downscaled_cmip5/CCSM4/historical/tasmax'\n\t\n\t# list the data\n\tl = sort_files( glob.glob( os.path.join( input_path, '*.tif' ) ) )\n\tl = only_years( l, begin=1901, end=2005 )\n\n\t# open a pool and turn the list of arrays into an ndarray\n\tpool = Pool( 31 )\n\tarr = np.array( pool.map( run, l ) )\n\tpool.close()\n\tpool.join()\n\n\t# mask it\n\tarr = np.ma.masked_where( arr <= np.min( arr ), arr )\n\n\t# BASELINE -- 5ModelAvg\n\tinput_path = '/workspace/Shared/Tech_Projects/EPSCoR_Southcentral/project_data/downscaled_cmip5/5ModelAvg/historical/tasmax'\n\t\n\t# list the data\n\tl = sort_files( glob.glob( os.path.join( input_path, '*.tif' ) ) )\n\tl = only_years( l, begin=1901, end=2005 )\n\n\t# open a pool and turn the list of arrays into an ndarray\n\tpool = Pool( 31 )\n\tbase = np.array( pool.map( run, l ) )\n\tpool.close()\n\tpool.join()\n\n\t# mask it\n\tbase = np.ma.masked_where( base <= np.min( base ), base )\n\n\t# do some stuff with the outputs here\n\tdiff_masked = np.diff( arr - base, axis=0 )\n\n","sub_path":"snap_scripts/epscor_sc/older_epscor_sc_scripts_archive/diff_model_5modelavg_epscor_se.py","file_name":"diff_model_5modelavg_epscor_se.py","file_ext":"py","file_size_in_byte":3500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"138064834","text":"from __future__ import print_function\n\nimport json\nimport urllib\nimport boto3\nimport datetime\nimport sys\nimport os\nfrom botocore.client import Config\n\ndef lambda_handler(event, context):\n jobId = event[\"CodePipeline.job\"][\"id\"]\n codePipeline = boto3.client(\"codepipeline\")\n s3Client = boto3.resource(\"s3\", config=Config(signature_version=\"s3v4\"))\n try:\n tempReadyFile = \"/tmp/deploy.json\"\n readyFileLocation = event[\"CodePipeline.job\"][\"data\"][\"inputArtifacts\"][0][\"location\"][\"s3Location\"]\n s3Client = boto3.resource(\"s3\", config=Config(signature_version=\"s3v4\"))\n readyFileBucket = s3Client.Bucket(readyFileLocation[\"bucketName\"])\n readyFileBucket.download_file(readyFileLocation[\"objectKey\"], tempReadyFile)\n \n readyFileJson = {}\n with open(tempReadyFile, \"r\") as file:\n readyFileJson = json.load(file)\n \n print(json.dumps(readyFileJson))\n \n tempArtifact = \"/tmp/artifact.zip\"\n for artifact in event[\"CodePipeline.job\"][\"data\"][\"outputArtifacts\"]:\n dlRef = readyFileJson[\"artifacts\"][artifact[\"name\"]]\n dlBucket = s3Client.Bucket(dlRef[\"bucket\"])\n dlBucket.download_file(dlRef[\"key\"], tempArtifact)\n ulRef = artifact[\"location\"][\"s3Location\"]\n ulBucket = s3Client.Bucket(ulRef[\"bucketName\"])\n ulBucket.upload_file(tempArtifact, ulRef[\"objectKey\"])\n \n codePipeline.put_job_success_result(jobId=jobId)\n return readyFileJson\n except Exception as e:\n print(\"!!! FAILED\")\n print(e)\n codePipeline.put_job_failure_result(\n jobId=jobId,\n failureDetails={\"message\": str(e), \"type\": \"JobFailed\"}\n )\n raise","sub_path":"terraform/lambda/parse-deploy-readyfile.py","file_name":"parse-deploy-readyfile.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"93789411","text":"# -*- coding: utf-8 -*-\nimport os\nBASEDIR = os.path.abspath(os.path.dirname(__file__))\n\n# Set the this for development/production environment\nDEBUG = True\n\nAPPLICATION_NAME = \"Squad URL\"\n\n# mail server settings\nMAIL_SERVER = \"localhost\"\nMAIL_PORT = 25\nMAIL_USERNAME = None\nMAIL_PASSWORD = None\n\nADMINS = frozenset([\"yourmail@yourdomain.com\"])\n\nSECRET_KEY = \"SecretKeyForSessionSigning\"\n\n# Default database is SQLite, replace with the following and adapt accordingly\n# MySQL string: mysql://username:password@host:port/databasename\n# PostgreSQL string: postgresql://username:password@host:port/databasename\n# Oracle string: oracle://username:password@db_server_IP:port/databasename\nSQLALCHEMY_DATABASE_URI = \"sqlite:///\" + os.path.join(BASEDIR, \"app.db\")\nDATABASE_CONNECT_OPTIONS = {}\n\n#at https://github.com/mitsuhiko/flask/wiki/Large-app-how-to#config\n# mentions 2 threads/core -> needs more investigation\nTHREADS_PER_PAGE = 4\n\n# Enable Cross-site request forgery protection\nCSRF_ENABLED = True\nCSRF_SESSION_KEY = \"supersecretimpossibletoguesskey\"\n\n# Enable Google's Recaptcha\nRECAPTCHA_USE_SSL = False\nRECAPTCHA_PUBLIC_KEY = \"recaptcha_public_key_get_it_from_www.google.com/recaptcha\"\nRECAPTCHA_PRIVATE_KEY = \"as_above_available_from_www.google.com/recaptcha\"\n#see developers.google.com/recaptcha/docs/customization for available themes\nRECAPTCHA_OPTIONS = {\"theme\": \"clean\"}\n\n# same as in Django see: https://docs.djangoproject.com/en/dev/ref/settings/#login-redirect-url\n# Where is the login URL if any\nLOGIN_URL = \"/login\"\n# After successful login redirect to...\nLOGIN_REDIRECT_URL = \"/\"\n# After successful logout redirect to...\nLOGOUT_REDIRECT_URL = \"/\"\n\n# Logger settings\n# Enable logger default is true\nLOGGER = True\n# How many file to rotate\nROTATE_FILES = 4\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"362236680","text":"def numerics(n):\n return [int(x) for x in list(str(n))]\n\n\ndef kaprekar_step(L):\n sort_L = ''.join([str(x) for x in sorted(L)])\n return int(sort_L[::-1]) - int(sort_L) \n\n\ndef kaprekar_loop_0(n):\n print(n)\n while(n != 6174):\n n = kaprekar_step(numerics(n))\n print(n)\n\n\ndef kaprekar_loop_1(n):\n if len(set(numerics(n))) == 1:\n print(f'Ошибка! На вход подано число {n} - все цифры одинаковые')\n elif n < 1001:\n print('Ошибка! На вход подано число 1000')\n else:\n print(n)\n while(n != 6174):\n n = kaprekar_step(numerics(n))\n print(n)\n\n\ndef kaprekar_check(n):\n if n in [100, 1000, 100000]:\n return False\n elif len(set(numerics(n))) == 1:\n return False\n elif len(list(numerics(n))) not in [3, 4, 6]:\n return False\n return True\n\n\ndef kaprekar_loop(n):\n if not kaprekar_check(n):\n print(f'Ошибка! На вход подано число {n}, не удовлетворяющее условиям процесса Капрекара')\n else:\n list_nums = [n,]\n print(n)\n while(n not in [495, 6174, 549945, 631764]):\n n = kaprekar_step(numerics(n))\n if n in list_nums:\n print(f'Следующее число - {n}, кажется процесс зациклился...')\n break\n else:\n list_nums.append(n)\n print(n)","sub_path":"math and python workshop/4/4-2.py","file_name":"4-2.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"514901174","text":"import dash_html_components as html\nimport dash_core_components as dcc\nfrom dash.dependencies import Input, Output, State\nfrom dash.exceptions import PreventUpdate\n\nfrom . import heatmap\nfrom . import pca\nfrom . import distributions\nfrom . import hierachical_clustering\nfrom . import plotting\nfrom . import tools as T\n\n\n_modules = [\n heatmap,\n distributions,\n pca,\n hierachical_clustering,\n plotting\n]\n\nmodules = {module._label: module for module in _modules}\n\ngroupby_options = [{'label': 'Batch', 'value': 'Batch'},\n {'label': 'Label', 'value': 'Label'},\n {'label': 'Type', 'value': 'Type'},\n {'label': 'Color', 'value': 'Color'}]\n\nana_normalization_cols = [{'label': 'Batch', 'value': 'Batch'},\n {'label': 'peak_label', 'value': 'peak_label'},\n {'label': 'ms_file', 'value': 'ms_file'}]\n\n_layout = html.Div([\n dcc.Tabs(id='ana-secondary-tab', value=_modules[0]._label, vertical=False, \n children=[dcc.Tab(value=key, \n label=modules[key]._label,\n ) for key in modules.keys()\n ]\n ),\n \n dcc.Dropdown(id='ana-file-types', options=[], placeholder='Types of files to include', multi=True),\n dcc.Dropdown(id='ana-peak-labels-include', options=[], placeholder='Include peak_labels', multi=True),\n dcc.Dropdown(id='ana-peak-labels-exclude', options=[], placeholder='Exclude peak_labels', multi=True),\n dcc.Dropdown(id='ana-ms-order', options=[], placeholder='MS-file sorting', multi=True),\n dcc.Dropdown(id='ana-groupby', options=groupby_options, value=None, placeholder='Group by column'),\n dcc.Dropdown(id='ana-normalization-cols', options=ana_normalization_cols, value=None, placeholder='Normalize by', multi=True),\n html.Div(id='ana-secondary-tab-content')\n])\n\n\n_label = 'Analysis'\n\n_outputs = None\n\ndef layout():\n return _layout\n\n\ndef callbacks(app, fsc, cache):\n\n for module in _modules:\n func = module.callbacks\n if func is not None:\n func(app=app, fsc=fsc, cache=cache)\n\n @app.callback(\n Output('ana-secondary-tab-content', 'children'),\n Input('ana-secondary-tab', 'value'),\n State('wdir', 'children')\n )\n def render_content(tab, wdir):\n func = modules[tab].layout\n if func is not None:\n return func()\n else:\n raise PreventUpdate\n\n\n @app.callback(\n Output('ana-file-types', 'options'),\n Output('ana-file-types', 'value'),\n Input('tab', 'value'),\n State('wdir', 'children')\n )\n def file_types(tab, wdir):\n if tab != _label:\n raise PreventUpdate\n meta = T.get_metadata( wdir )\n if meta is None:\n raise PreventUpdate\n file_types = meta['Type'].drop_duplicates().sort_values()\n options = [{'value': str(i), 'label': str(i)} for i in file_types]\n print(file_types, options)\n return options, file_types\n\n\n @app.callback(\n Output('ana-ms-order', 'options'),\n Output('ana-groupby', 'options'),\n Input('ana-secondary-tab', 'value'),\n State('wdir', 'children')\n )\n def ms_order_options(tab, wdir):\n cols = T.get_metadata(wdir).dropna(how='all', axis=1).columns.to_list()\n if 'index' in cols: cols.remove('index')\n if 'PeakOpt' in cols: cols.remove('PeakOpt')\n options = [{'value':i, 'label': i} for i in cols]\n return options, options\n\n\n @app.callback(\n Output('ana-peak-labels-include', 'options'),\n Output('ana-peak-labels-exclude', 'options'),\n Input('tab', 'value'),\n State('wdir', 'children')\n )\n def peak_labels(tab, wdir):\n if tab != _label:\n raise PreventUpdate\n peaklist = T.get_peaklist( wdir ).reset_index()\n options = [{'value': i, 'label': i} for i in peaklist.peak_label]\n return options, options","sub_path":"ms_mint/app/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":3954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"201439466","text":"# Prompt: https://leetcode.com/problems/next-greater-element-i\n\n# Runtime: 60 ms, faster than 37.16% of Python online submissions for Next Greater Element I.\n# Memory Usage: 12 MB, less than 48.05% of Python online submissions for Next Greater Element I.\n\nclass Solution(object):\n # finds the next greater number after index in arr\n def nextGreater(self, arr, index):\n for i in range(index+1, len(arr)):\n if arr[i] > arr[index]:\n return arr[i]\n return -1\n \n def nextGreaterElement(self, nums1, nums2):\n # pre-compute next greater for each num in num2 (saves time later)\n nextGreater = {} # we can use a hash map because numbers are unique\n for index, num in enumerate(nums2):\n nextGreater[num] = self.nextGreater(nums2, index)\n # go through each num in nums1 & look up next greater number\n result = []\n for num in nums1:\n result.append(nextGreater[num])\n \n return result\n","sub_path":"0. Easy/0496. Next Greater Element I/next_greater.py","file_name":"next_greater.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"119552479","text":"# coding: utf8\nfrom __future__ import unicode_literals\nimport sys\n\nimport prodigy\nfrom prodigy.core import recipe_args\nfrom prodigy.components.db import connect\nfrom prodigy.components.sorters import Probability\nfrom prodigy.util import log, prints, split_string, set_hashes\nimport requests\nimport spacy\nimport srsly\n\n\nAPI_URL = \"\"\n\n\n@prodigy.recipe('phrases.teach',\n dataset=recipe_args[\"dataset\"],\n seeds=(\"One or more comma-separated seed terms\", \"option\", \"se\", split_string),\n threshold=(\"Similarity threshold for sense2vec\", \"option\", \"t\", float),\n batch_size=(\"Batch size to use\", \"option\", \"bs\", int),\n resume=(\"Resume from existing phrases dataset\", \"flag\", \"R\", bool)\n)\ndef phrases_teach(dataset, seeds, threshold=0.85, batch_size=5, resume=False):\n \"\"\"\n Bootstrap a terminology list with word vectors and seeds terms. Prodigy\n will suggest similar terms based on the word vectors, and update the\n target vector accordingly.\n \"\"\"\n\n DB = connect()\n seed_tasks = [set_hashes({\"text\": s, \"answer\": \"accept\"}) for s in seeds]\n DB.add_examples(seed_tasks, datasets=[dataset])\n\n accept_phrases = seeds\n reject_phrases = []\n\n seen = set(accept_phrases)\n sensed = set()\n\n if resume:\n prev = DB.get_dataset(dataset)\n prev_accept = [eg[\"text\"] for eg in prev if eg[\"answer\"] == \"accept\"]\n prev_reject = [eg[\"text\"] for eg in prev if eg[\"answer\"] == \"reject\"]\n accept_phrases += prev_accept\n reject_phrases += prev_reject\n\n seen.update(set(accept_phrases))\n seen.update(set(reject_phrases))\n\n def sense2vec(phrase, threshold):\n \"\"\"Call sense2vec API to get similar \"senses\" (phrases)\"\"\"\n res = requests.post(API_URL, {\n \"sense\": \"auto\",\n \"word\": phrase\n })\n results = res.json()[\"results\"]\n output = []\n for r in results:\n if r[\"score\"] > threshold or len(output) <= 10:\n output.append((r[\"score\"], r[\"text\"]))\n\n return output\n\n def update(answers):\n \"\"\"Updates accept_phrases so that the stream can find new phrases\"\"\"\n for answer in answers:\n if answer['answer'] == 'accept':\n accept_phrases.append(answer['text'])\n elif answer['answer'] == 'reject':\n reject_phrases.append(answer['text'])\n \n def get_stream():\n \"\"\"Continue querying sense2vec whenever we get a new phrase and presenting\n examples to the user with a similarity above the threshold parameter\"\"\"\n while True:\n seen.update(set([rp.lower() for rp in reject_phrases]))\n for p in accept_phrases:\n if p.lower() not in sensed:\n sensed.add(p.lower())\n for score, phrase in sense2vec(p, threshold):\n if phrase.lower() not in seen:\n seen.add(phrase.lower())\n yield score, {\"text\": phrase, 'meta': {'score': score}}\n\n stream = Probability(get_stream())\n\n return {\n 'view_id': 'text',\n 'dataset': dataset,\n 'stream': stream,\n 'update': update,\n 'config': {\n \"batch_size\": batch_size\n }\n }\n\n\n@prodigy.recipe(\n \"phrases.to-patterns\",\n dataset=recipe_args[\"dataset\"],\n label=recipe_args[\"label\"],\n output_file=recipe_args[\"output_file\"],\n)\ndef to_patterns(dataset=None, label=None, output_file=None):\n \"\"\"\n Convert a list of seed phrases to a list of match patterns that can be used\n with ner.match. If no output file is specified, each pattern is printed\n so the recipe's output can be piped forward to ner.match.\n\n This is pretty much an exact copy of terms.to-patterns.\n The pattern for each example is just split on whitespace so instead of:\n\n {\"label\": \"SHOE_BRAND\", \"pattern\": [{\"LOWER\": \"new balance\"}]}\n\n\n which won't match anything you'll get:\n\n {\"label\": \"SHOE_BRAND\", \"pattern\": [{\"LOWER\": \"new\"}, {\"LOWER\": \"balance\"}]}\n \"\"\"\n if label is None:\n prints(\n \"--label is a required argument\",\n \"This is the label that will be assigned to all patterns \"\n \"created from terms collected in this dataset. \",\n exits=1,\n error=True,\n )\n\n DB = connect()\n\n def get_pattern(term, label):\n return {\"label\": label, \"pattern\": [{\"lower\": t.lower()} for t in term[\"text\"].split()]}\n\n log(\"RECIPE: Starting recipe terms.to-patterns\", locals())\n if dataset is None:\n log(\"RECIPE: Reading input terms from sys.stdin\")\n terms = (srsly.json_loads(line) for line in sys.stdin)\n else:\n if dataset not in DB:\n prints(\"Can't find dataset '{}'\".format(dataset), exits=1, error=True)\n terms = DB.get_dataset(dataset)\n log(\n \"RECIPE: Reading {} input terms from dataset {}\".format(len(terms), dataset)\n )\n if output_file:\n patterns = [\n get_pattern(term, label) for term in terms if term[\"answer\"] == \"accept\"\n ]\n log(\"RECIPE: Generated {} patterns\".format(len(patterns)))\n srsly.write_jsonl(output_file, patterns)\n prints(\"Exported {} patterns\".format(len(patterns)), output_file)\n else:\n log(\"RECIPE: Outputting patterns\")\n for term in terms:\n if term[\"answer\"] == \"accept\":\n print(srsly.json_dumps(get_pattern(term, label)))\n","sub_path":"contrib/phrases/phrases.py","file_name":"phrases.py","file_ext":"py","file_size_in_byte":5474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"178294479","text":"from collections import deque\n\nsteps = 356\n\nd = deque([0])\n\npos = 0\nfor i in range(1, 2018):\n d.rotate(-steps-1)\n d.appendleft(i)\n\nfor d1, d2 in zip(d, list(d)[1:]):\n if d1 == 2017:\n print(d2)\n exit()\n","sub_path":"day17/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"132624468","text":"from wtforms import Form\nfrom wtforms.fields import TextField\nfrom wtforms.validators import (\n InputRequired,\n Length,\n)\n\nname_field = TextField('Name', [InputRequired(), Length(max=100)])\ndescription_field = TextField('Description', [Length(max=50000)])\n\n\nclass AttachmentForm(Form):\n name = name_field\n description = description_field\n","sub_path":"mywdb/forms/attachment.py","file_name":"attachment.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"354089861","text":"import socket\r\nimport sys\r\n\r\n#create a TCP/IP socket\r\ns=socket.socket()\r\nprint('Socket successfully created')\r\n\r\n#researve a port on your computer\r\nport=12345\r\n\r\n'''\r\nnext bind to the port, we have not type any ip in the ip filed\r\ninsted we have inputted an empty string, this makes the server listen to requests\r\ncoming from other computers on the network\r\n'''\r\n\r\ns.bind(('',port))\r\nprint('socket binded to %s' %port)\r\n\r\n#put the socket into listening mode\r\ns.listen(5)\r\nprint('socket is listening')\r\n\r\n#A forever loop until we interrupt it or an error occurs\r\nwhile True:\r\n #establish connection with client\r\n c, addr=s.accept()\r\n print('got connection from ' , addr)\r\n\r\n #send a thank you message to the client\r\n c.send('thank you for connecting'.encode())\r\n #close the connection with the client\r\n c.close()\r\n","sub_path":"diary-project/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"218929118","text":"from django.conf import settings\nfrom django.shortcuts import get_object_or_404\nfrom memberships.models import Membership\n\n\ndef bag_contents(request):\n\n bag_items = []\n total = 0\n membership_count = 0\n bag = request.session.get('bag', {})\n\n for membership_id, quantity in bag.items():\n membership = get_object_or_404(Membership, pk=membership_id)\n total += quantity * membership.price\n membership_count += quantity\n bag_items.append({\n 'membership_id': membership_id,\n 'quantity': quantity,\n 'membership': membership,\n })\n\n grand_total = total\n\n context = {\n 'bag_items': bag_items,\n 'total': total,\n 'membership_count': membership_count,\n 'grand_total': grand_total,\n }\n\n return context\n","sub_path":"bag/contexts.py","file_name":"contexts.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"94262146","text":"# This script is for download the stock price of nearly 700 companies on Yahoo Finance\n# Please remember to chagne the absolute paths to your own\nfrom selenium import webdriver\nfrom openpyxl import load_workbook\nimport time\nimport os\nimport csv\n\n# Load excel file with the list of the companies which need searching\nfileName = \"D:/Users/hans/Desktop/Graduate Assistant/fs list 2017_An.xlsx\"\nwb = load_workbook(fileName)\nws = wb.active\n\n# Initiate chrome web driver for web automation\ndriver = webdriver.Chrome(\"D:/Users/hans/Desktop/Graduate Assistant/chromedriver.exe\")\ndriver.get(\"https://finance.yahoo.com/\")\ntime.sleep(5)\n\n# Extract the cache of the section at Yahoo Finance\ndriver.get(\"https://finance.yahoo.com/quote/AET/history?period1=1483164000&period2=1509426000&interval=1d&filter=history&frequency=1d\")\nlink = driver.find_element_by_xpath(\"//a[span[text()='Download Data']]\").get_attribute('href')\ncache = link[(link.find(\"crumb\") + 6):]\n\n# Download a particular company's stock price by its stock code (row)\ndef run(row):\n print(\"\\nrow: \" + str(row))\n driver.get(\"https://query1.finance.yahoo.com/v7/finance/download/\" + ws['D' + str(row)].value + \"?period1=1483164000&period2=1509426000&interval=1d&events=history&crumb=\" + cache)\n\n# Loop through the list in the excel file\nfor row in range(2, 150):\n run(row)\n\n# Merge all the downloaded excel into one file\ndirectory = os.fsencode(\"C:/Users/hans/Desktop/Graduate Assistant/Yahoo Finance/\")\nYahooFianance = \"C:/Users/hans/Desktop/Graduate Assistant/Yahoo Finance.csv\"\n\nwith open(YahooFianance, 'a') as fout:\n writer = csv.writer(fout, delimiter=',')\n for file in os.listdir(directory):\n \t# File name = stock code\n filename = os.fsdecode(file)\n with open(\"C:/Users/hans/Desktop/Graduate Assistant/Yahoo Finance/\" + filename, 'r') as fin:\n reader = csv.reader(fin, delimiter=',')\n for line in reader:\n \t# Add each line of individual files to the final one together with stock code\n writer.writerow([filename, line])\n","sub_path":"Yahoo Finance/Yahoo Finance.py","file_name":"Yahoo Finance.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"324343132","text":"###################################################################################################################### \n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # \n# # \n# Licensed under the Apache License Version 2.0 (the \"License\"). You may not use this file except in compliance # \n# with the License. A copy of the License is located at # \n# # \n# http://www.apache.org/licenses/ # \n# # \n# or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES # \n# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions # \n# and limitations under the License. # \n######################################################################################################################\n\nimport os\nimport threading\nimport types\nimport uuid\nfrom datetime import datetime\n\nimport boto3\n\nimport actions\nimport handlers\nimport services\nimport tagging\nimport tagging.tag_filter_set\nfrom boto_retry import get_default_retry_strategy\nfrom handlers.task_tracking_table import TaskTrackingTable\nfrom helpers import safe_dict, safe_json\nfrom metrics import put_task_select_data\nfrom outputs import raise_exception\nfrom outputs.queued_logger import QueuedLogger\nfrom tagging.tag_filter_expression import TagFilterExpression\n\n\nREMAINING_TIME_AFTER_STORE = 15\nREMAINING_TIME_AFTER_DESCRIBE = 45\n\nWARN_REGION_NOT_IN_TASK_CONFIGURATION = \"Region from event {} is not configured in the list of regions for this task\"\n\nDEBUG_ACTION = \"Action properties {}\"\nDEBUG_ADD_SINGLE_RESOURCE_TASK = \"Created task item {} with 1 resource of type {} for task {}\"\nDEBUG_ADDED_AGGREGATED_RESOURCES_TASK = \"Created task item {} with {} resources of type {} for task {}\"\nDEBUG_EVENT = \"Handling event {}\"\nDEBUG_FILTER_METHOD = \"Resource filtered out by {} {} method\"\nDEBUG_FILTERED_RESOURCE = \"Returned resource by {} {} method is: {}\"\nDEBUG_RESOURCE_NO_TAGS = \"Resource {}\\n does not support tags, resource is selected\"\nDEBUG_RESOURCE_NOT_SELECTED = \"Resource {} not selected for task {} because task not in tags {}\"\nDEBUG_RESOURCE_NOT_SELECTED_TAG_FILTER = \"Resource {} not selected for task {}\\n task filter does not match tags {}\"\nDEBUG_SELECT_ALL_RESOURCES = \"* used as tag_filter all resources of type {} are selected\"\nDEBUG_SELECT_BY_TASK_NAME = \"Resources of type {} that have tag name {} and have {} in its list of values are selected\"\nDEBUG_SELECT_PARAMETERS = \"Selecting resources of type {} for service {} with parameters {}\"\nDEBUG_SELECTED_BY_TAG_FILTER = \"Resource {}\\n is selected because tags {} matches the filter {} set for task {}\"\nDEBUG_SELECTED_BY_TASK_NAME_IN_TAG_VALUE = \"Resources {}\\n selected because it has tag named {} and taskname {} is tag of value\"\nDEBUG_SELECTED_WILDCARD_TAG_FILTER = \"Resource {}\\n selected because the tagfilter set for task {} is set to *\"\nDEBUG_TAG_FILTER_USED_TO_SELECT_RESOURCES = \"Tag-filter is used to select resources of type {}\"\n\nINFO_ACCOUNT = \"Account is {}\"\nINFO_ADDED_ITEMS = \"Added {} action items for task {}\"\nINFO_AGGR_LEVEL = \"Aggregation level for action is \\\"{}\\\" level\"\nINFO_ASSUMED_ROLE = \"Assumed role to select resources is {}\"\nINFO_REGION_AGGREGATED = \"Added action item {} for {} aggregated resources for region {} of type \\\"{}\\\" for task \\\"{}\\\"\"\nINFO_RESOURCES_FOUND = \"{} resources found\"\nINFO_RESOURCES_SELECTED = \"{} resources selected\"\nINFO_RESULT = \"Selecting resources took {:>.3f} seconds\"\nINFO_SELECTED_RESOURCES = \"Selecting resources of type \\\"{}\\\" from service \\\"{}\\\" for task \\\"{}\\\"\"\nINFO_USE_TAGS_TO_SELECT = \"{}esource tags are used to select resources\"\n\nERR_CAN_NOT_EXECUTE_WITH_THESE_RESOURCES = \"Can not execute action \\\"{}\\\" for task \\\"{}\\\", reason {}\"\nERR_TIMEOUT_SELECT_OR_STORE = \"Selection and storing of resources not completed after {} seconds, adjust select memory \" \\\n \"settings for task {}\"\nERR_TIMEOUT_SELECTING_RESOURCES = \"Timeout selecting {} resources from service {} for task {}\"\nERR_CREATING_TASKS_FOR_SELECTED_RESOURCES = \"Timeout creating tasks for selected resources in DynamoDB tracking table for task {}\"\nERR_ACCOUNT_SKIPPED_NO_ROLE = \"Account {} skipped because the required role could not be assumed or was not available\"\nERR_SELECTING_TASK_RESOURCES = \"Error selecting resources for task {}, {}\"\n\nLOG_STREAM = \"{}-{}-{}{:0>4d}{:0>2d}{:0>2d}\"\n\n\nclass SelectResourcesHandler(object):\n \"\"\"\n Class that handles the selection of AWS service resources for a task to perform its action on.\n \"\"\"\n\n def __init__(self, event, context, logger=None, tracking_store=None):\n\n def log_stream_name():\n\n classname = self.__class__.__name__\n dt = datetime.utcnow()\n\n account = self._event.get(handlers.HANDLER_SELECT_ARGUMENTS, {}).get(handlers.HANDLER_EVENT_ACCOUNT, \"\")\n regions = self._event.get(handlers.HANDLER_SELECT_ARGUMENTS, {}).get(handlers.HANDLER_EVENT_REGIONS, [])\n\n if account is not None and len(regions) > 0:\n account_and_region = \"-\".join([account, regions[0]]) + \"-\"\n\n else:\n region = \"\"\n\n if self.sub_task is not None:\n account = \"\"\n if self._this_account:\n if len(self._accounts) == 0:\n account = os.getenv(handlers.ENV_OPS_AUTOMATOR_ACCOUNT)\n elif len(self._accounts) == 1:\n account = self._accounts[0]\n\n region = self._regions[0] if len(self._regions) == 1 else \"\"\n\n if account != \"\":\n if region not in [\"\", None]:\n account_and_region = \"-\".join([account, region]) + \"-\"\n else:\n account_and_region = account\n else:\n account_and_region = \"\"\n\n return LOG_STREAM.format(classname, self.task[handlers.TASK_NAME], account_and_region, dt.year, dt.month, dt.day)\n\n self._context = context\n self._event = event\n self.task = event[handlers.HANDLER_EVENT_TASK]\n self.sub_task = event.get(handlers.HANDLER_EVENT_SUB_TASK, None)\n self.use_custom_select = event.get(handlers.HANDLER_EVENT_CUSTOM_SELECT, True)\n\n # the job id is used to correlate all generated tasks for the selected resources\n self.task_group = self._event.get(handlers.HANDLER_EVENT_TASK_GROUP, None)\n if self.task_group is None:\n self.task_group = str(uuid.uuid4())\n\n debug = event[handlers.HANDLER_EVENT_TASK].get(handlers.TASK_DEBUG, False)\n if logger is None:\n self._logger = QueuedLogger(logstream=log_stream_name(), context=context, buffersize=50 if debug else 20, debug=debug)\n else:\n self._logger = logger\n\n self._sts = None\n\n self.select_args = event.get(handlers.HANDLER_SELECT_ARGUMENTS, {})\n self.task_dt = event[handlers.HANDLER_EVENT_TASK_DT]\n\n self.action_properties = actions.get_action_properties(self.task[handlers.TASK_ACTION])\n self.action_class = actions.get_action_class(self.task[handlers.TASK_ACTION])\n self.task_parameters = self.task.get(handlers.TASK_PARAMETERS, {})\n self.metrics = self.task.get(handlers.TASK_METRICS, False)\n\n self.service = self.action_properties[actions.ACTION_SERVICE]\n self.keep_tags = self.action_properties.get(actions.ACTION_KEEP_RESOURCE_TAGS, True)\n\n self.source = self._event.get(handlers.HANDLER_EVENT_SOURCE, handlers.UNKNOWN_SOURCE)\n self.run_local = handlers.running_local(self._context)\n self._timer = None\n self._timeout_event = self._timeout_event = threading.Event()\n\n self.aggregation_level = self.action_properties.get(actions.ACTION_AGGREGATION, actions.ACTION_AGGREGATION_RESOURCE)\n if self.aggregation_level is not None and isinstance(self.aggregation_level, types.FunctionType):\n self.aggregation_level = self.aggregation_level(self.task_parameters)\n\n self.batch_size = self.action_properties.get(actions.ACTION_BATCH_SIZE)\n if self.batch_size is not None and isinstance(self.batch_size, types.FunctionType):\n self.batch_size = self.batch_size(self.task_parameters)\n\n self.actions_tracking = TaskTrackingTable(self._context, logger=self._logger) if tracking_store is None else tracking_store\n\n @classmethod\n def is_handling_request(cls, event, _):\n \"\"\"\n Tests if this handler handles the event.\n :param _:\n :param event: The event tyo test\n :return: True if the event is handled by this handler\n \"\"\"\n return event.get(handlers.HANDLER_EVENT_ACTION, \"\") == handlers.HANDLER_ACTION_SELECT_RESOURCES\n\n @property\n def _task_tag(self):\n \"\"\"\n Returns the name of the tag that contains the list of actions for a resource.\n :return: The name of the tag that contains the list of actions for a resource\n \"\"\"\n name = os.environ.get(handlers.ENV_AUTOMATOR_TAG_NAME)\n if name is None:\n name = handlers.DEFAULT_SCHEDULER_TAG\n return name\n\n @property\n def sts(self):\n if self._sts is None:\n self._sts = boto3.client(\"sts\")\n return self._sts\n\n @property\n def _resource_name(self):\n name = self.action_properties[actions.ACTION_RESOURCES]\n if name in [None, \"\"]:\n name = self._event.get(handlers.HANDLER_SELECT_ARGUMENTS, {}).get(handlers.HANDLER_EVENT_RESOURCE_NAME, \"\")\n return name\n\n def _check_can_execute(self, selected_resources):\n \"\"\"\n Checks if the action for the task can be executed with the selected resources\n :param selected_resources: \n :return: \n \"\"\"\n check_method = getattr(self.action_class, actions.CHECK_CAN_EXECUTE, None)\n if check_method:\n try:\n check_method(selected_resources, self.task_parameters)\n return True\n except ValueError as ex:\n self._logger.error(ERR_CAN_NOT_EXECUTE_WITH_THESE_RESOURCES, self.task[handlers.TASK_ACTION],\n self.task[handlers.TASK_NAME], str(ex))\n return False\n return True\n\n def _task_assumed_roles(self):\n \"\"\"\n Returns a list of service instances for each handled account/role\n :return:\n \"\"\"\n\n # account can optionally be passed in by events\n account = self._event.get(handlers.HANDLER_SELECT_ARGUMENTS, {}).get(handlers.HANDLER_EVENT_ACCOUNT)\n\n if account is not None:\n assumed_role = handlers.get_account_role(account=account, task=self.task, logger=self._logger)\n if assumed_role is None:\n if account != os.getenv(handlers.ENV_OPS_AUTOMATOR_ACCOUNT):\n self._logger.error(ERR_ACCOUNT_SKIPPED_NO_ROLE, account)\n yield None\n else:\n yield assumed_role\n\n else:\n # no role if processing scheduled task in own account\n if self._this_account:\n assumed_role = handlers.get_account_role(account=os.getenv(handlers.ENV_OPS_AUTOMATOR_ACCOUNT),\n task=self.task,\n logger=self._logger)\n yield assumed_role\n\n for acct in self._accounts:\n # for external accounts\n assumed_role = handlers.get_account_role(account=acct, task=self.task, logger=self._logger)\n if assumed_role is not None:\n yield assumed_role\n\n @property\n def _this_account(self):\n if self.sub_task is not None:\n return self.sub_task[handlers.TASK_THIS_ACCOUNT]\n return self.task.get(handlers.TASK_THIS_ACCOUNT, True)\n\n @property\n def _accounts(self):\n if self.sub_task is not None:\n return self.sub_task[handlers.TASK_ACCOUNTS]\n return self.task.get(handlers.TASK_ACCOUNTS, [])\n\n @property\n def _regions(self):\n \"\"\"\n Returns the regions in where resources are selected\n :return:\n \"\"\"\n regions = self._event.get(handlers.HANDLER_SELECT_ARGUMENTS, {}).get(handlers.HANDLER_EVENT_REGIONS)\n if regions is None:\n regions = self.sub_task[handlers.TASK_REGIONS] if self.sub_task is not None else self.task.get(\n handlers.TASK_REGIONS, [None])\n else:\n # check if the regions in the event are in the task configurations regions\n checked_regions = [r for r in regions if r in regions]\n if len(checked_regions) != len(regions):\n self._logger.warning(WARN_REGION_NOT_IN_TASK_CONFIGURATION, self._event)\n return checked_regions\n return regions if len(regions) > 0 else [None]\n\n def handle_request(self):\n \"\"\"\n Handles the select resources request. Creates new actions for resources found for a task\n :return: Results of handling the request\n \"\"\"\n\n def filter_by_action_filter(srv, used_role, r):\n filter_method = getattr(self.action_class, actions.SELECT_AND_PROCESS_RESOURCE_METHOD, None)\n if filter_method is not None:\n r = filter_method(srv, self._logger, self._resource_name, r, self._context,\n self.task, used_role)\n if r is None:\n self._logger.debug(DEBUG_FILTER_METHOD, self.action_class.__name__, actions.SELECT_AND_PROCESS_RESOURCE_METHOD)\n return None\n else:\n self._logger.debug(DEBUG_FILTERED_RESOURCE, self.action_class.__name__,\n actions.SELECT_AND_PROCESS_RESOURCE_METHOD, safe_json(r, indent=3))\n\n return r\n\n def is_selected_resource(aws_service, resource, used_role, taskname, tags_filter, does_resource_supports_tags):\n\n # No tags then just use filter method if any\n if not does_resource_supports_tags:\n self._logger.debug(DEBUG_RESOURCE_NO_TAGS, resource)\n return filter_by_action_filter(srv=aws_service,\n used_role=used_role,\n r=resource)\n\n tags = resource.get(\"Tags\", {})\n\n # name of the tag that holds the list of tasks for this resource\n tagname = self._task_tag\n\n if tags_filter is None:\n # test if name of the task is in list of tasks in tag value\n if (tagname not in tags) or (taskname not in tagging.split_task_list(tags[tagname])):\n self._logger.debug(DEBUG_RESOURCE_NOT_SELECTED, safe_json(resource, indent=2), taskname,\n ','.join([\"'{}'='{}'\".format(t, tags[t]) for t in tags]))\n return None\n self._logger.debug(DEBUG_SELECTED_BY_TASK_NAME_IN_TAG_VALUE, safe_json(resource, indent=2), tagname, taskname)\n else:\n # using a tag filter, * means any tag\n if tags_filter != tagging.tag_filter_set.WILDCARD_CHAR:\n # test if there are any tags matching the tag filter\n if not TagFilterExpression(tags_filter).is_match(tags):\n self._logger.debug(DEBUG_RESOURCE_NOT_SELECTED_TAG_FILTER, safe_json(resource, indent=2), taskname,\n ','.join([\"'{}'='{}'\".format(t, tags[t]) for t in tags]))\n return None\n self._logger.debug(DEBUG_SELECTED_BY_TAG_FILTER, safe_json(resource, indent=2), tags, tag_filter_str, taskname)\n else:\n self._logger.debug(DEBUG_SELECTED_WILDCARD_TAG_FILTER, safe_json(resource, indent=2), taskname)\n return filter_by_action_filter(srv=aws_service,\n used_role=used_role,\n r=resource)\n\n return filter_by_action_filter(srv=aws_service,\n used_role=used_role,\n r=resource)\n\n def resource_batches(resources):\n \"\"\"\n Returns resources as chunks of size items. If the class has an optional custom aggregation function then the \n resources are aggregated first using this function before applying the batch size\n :param resources: resources to process\n :return: Generator for blocks of resource items\n \"\"\"\n\n aggregate_func = getattr(self.action_class, actions.CUSTOM_AGGREGATE_METHOD, None)\n\n for i in aggregate_func(resources, self.task_parameters, self._logger) if aggregate_func is not None else [resources]:\n if self.batch_size is None:\n yield i\n else:\n first = 0\n while first < len(i):\n yield i[first:first + self.batch_size]\n first += self.batch_size\n\n def setup_tag_filtering(t_name):\n # get optional tag filter\n no_select_by_tags = self.action_properties.get(actions.ACTION_NO_TAG_SELECT, False)\n if no_select_by_tags:\n tag_filter_string = tagging.tag_filter_set.WILDCARD_CHAR\n else:\n tag_filter_string = self.task.get(handlers.TASK_TAG_FILTER)\n\n # set if only a single task is required for selecting the resources, it is used to optimise the select\n select_tag = None\n if tag_filter_string is None:\n self._logger.debug(DEBUG_SELECT_BY_TASK_NAME, self._resource_name, self._task_tag, t_name)\n select_tag = self._task_tag\n elif tag_filter_string == tagging.tag_filter_set.WILDCARD_CHAR:\n self._logger.debug(DEBUG_SELECT_ALL_RESOURCES, self._resource_name)\n else:\n self._logger.debug(DEBUG_TAG_FILTER_USED_TO_SELECT_RESOURCES, self._resource_name)\n # build the tag expression that us used to filter the resources\n tag_filter_expression = TagFilterExpression(tag_filter_string)\n # the keys of the used tags\n tag_filter_expression_tag_keys = list(tag_filter_expression.get_filter_keys())\n # if there is only a single tag then we can optimize by just filtering on that specific tag\n if len(tag_filter_expression_tag_keys) == 1 and \\\n tagging.tag_filter_set.WILDCARD_CHAR not in tag_filter_expression_tag_keys[0]:\n select_tag = tag_filter_expression_tag_keys[0]\n return select_tag, tag_filter_string\n\n def add_aggregated(aggregated_resources):\n # create tasks action for aggregated resources , optionally split in batch size chunks\n for ra in resource_batches(aggregated_resources):\n if self._check_can_execute(ra):\n action_item = self.actions_tracking.add_task_action(task=self.task,\n assumed_role=assumed_role,\n action_resources=ra,\n task_datetime=self.task_dt,\n source=self.source,\n task_group=self.task_group)\n\n self._logger.debug(DEBUG_ADDED_AGGREGATED_RESOURCES_TASK, action_item[handlers.TASK_TR_ID], len(ra),\n self._resource_name, self.task[handlers.TASK_NAME])\n\n self._logger.debug(\"Added item\\n{}\", safe_json(action_item, indent=3))\n\n yield action_item\n\n def add_as_individual(resources):\n for ri in resources:\n # task action for each selected resource\n if self._check_can_execute([ri]):\n action_item = self.actions_tracking.add_task_action(task=self.task,\n assumed_role=assumed_role,\n action_resources=ri,\n task_datetime=self.task_dt,\n source=self.source,\n task_group=self.task_group)\n\n self._logger.debug(DEBUG_ADD_SINGLE_RESOURCE_TASK, action_item[handlers.TASK_TR_ID], self._resource_name,\n self.task[handlers.TASK_NAME])\n self._logger.debug(\"Added item\\n{}\", safe_json(action_item, indent=3))\n yield action_item\n\n try:\n task_items = []\n start = datetime.now()\n\n self._logger.debug(DEBUG_EVENT, safe_json(self._event, indent=3))\n self._logger.debug(DEBUG_ACTION, safe_json(self.action_properties, indent=3))\n\n self._logger.info(INFO_SELECTED_RESOURCES, self._resource_name, self.service, self.task[handlers.TASK_NAME])\n self._logger.info(INFO_AGGR_LEVEL, self.aggregation_level)\n\n task_level_aggregated_resources = []\n\n args = self._build_describe_argument()\n\n service_resource_with_tags = services.create_service(self.service).resources_with_tags\n if self._resource_name == \"\":\n supports_tags = len(service_resource_with_tags) != 0\n else:\n supports_tags = self._resource_name.lower() in [r.lower() for r in service_resource_with_tags]\n\n args[\"tags\"] = supports_tags\n self._logger.info(INFO_USE_TAGS_TO_SELECT, \"R\" if supports_tags else \"No r\")\n\n task_name = self.task[handlers.TASK_NAME]\n count_resource_items = 0\n selected_resource_items = 0\n\n select_on_tag, tag_filter_str = setup_tag_filtering(task_name)\n\n filter_func = getattr(self.action_class, actions.FILTER_RESOURCE_METHOD, None)\n\n # timer to guard selection time and log warning if getting close to lambda timeout\n if self._context is not None:\n self.start_timer(REMAINING_TIME_AFTER_DESCRIBE)\n try:\n\n for assumed_role in self._task_assumed_roles():\n retry_strategy = get_default_retry_strategy(service=self.service, context=self._context)\n\n service = services.create_service(service_name=self.service,\n service_retry_strategy=retry_strategy, role_arn=assumed_role)\n\n if self.is_timed_out():\n break\n\n # contains resources for account\n account_level_aggregated_resources = []\n\n self._logger.info(INFO_ACCOUNT, service.aws_account)\n if assumed_role not in [None, \"\"]:\n self._logger.info(INFO_ASSUMED_ROLE, assumed_role)\n\n for region in self._regions:\n\n # test for timeouts\n if self.is_timed_out():\n break\n\n # handle region passed in the event\n if region is not None:\n args[\"region\"] = region\n else:\n if \"region\" in args:\n del args[\"region\"]\n\n # resources can be passed in the invent by event handlers\n all_resources = self._event.get(handlers.HANDLER_SELECT_RESOURCES, None)\n\n if all_resources is None:\n\n # actions can have an optional method to select resources\n action_custom_describe_function = getattr(self.action_class, \"describe_resources\", None)\n if action_custom_describe_function is not None and self.use_custom_select:\n all_resources = action_custom_describe_function(service, self.task, region)\n else:\n # select resources from the service\n self._logger.debug(DEBUG_SELECT_PARAMETERS, self._resource_name, self.service, args)\n # selecting a list of all resources in this account/region\n all_resources = list(service.describe(self._resource_name,\n filter_func=filter_func,\n select_on_tag=select_on_tag,\n **args))\n # test for timeout\n if self.is_timed_out():\n break\n\n count_resource_items += len(all_resources)\n\n self._logger.info(INFO_RESOURCES_FOUND, len(all_resources))\n\n # select resources that are processed by the task\n selected_resources = []\n for sr in all_resources:\n sel = is_selected_resource(aws_service=service,\n resource=sr,\n used_role=assumed_role,\n taskname=task_name,\n tags_filter=tag_filter_str,\n does_resource_supports_tags=supports_tags)\n if sel is not None:\n selected_resources.append(sel)\n\n selected_resource_items += len(selected_resources)\n\n # display found and selected resources\n if len(all_resources) > 0:\n self._logger.info(INFO_RESOURCES_SELECTED, len(selected_resources))\n if len(selected_resources) == 0:\n continue\n\n # delete tags if not needed by the action\n if not self.keep_tags:\n for res in selected_resources:\n if \"Tags\" in res:\n del res[\"Tags\"]\n\n # add resources to total list of resources for this task\n if self.aggregation_level == actions.ACTION_AGGREGATION_TASK:\n task_level_aggregated_resources += selected_resources\n\n # add resources to list of resources for this account\n if self.aggregation_level == actions.ACTION_AGGREGATION_ACCOUNT:\n account_level_aggregated_resources += selected_resources\n\n # add batch(es) of resources for this region\n if self.aggregation_level == actions.ACTION_AGGREGATION_REGION and len(selected_resources) > 0:\n task_items += list(add_aggregated(selected_resources))\n\n # no aggregation, add each individual resource\n if self.aggregation_level == actions.ACTION_AGGREGATION_RESOURCE and len(selected_resources) > 0:\n task_items += list(add_as_individual(selected_resources))\n\n # at the end of the region loop, check if aggregated resources for account need to be added\n if self.aggregation_level == actions.ACTION_AGGREGATION_ACCOUNT and len(account_level_aggregated_resources) > 0:\n task_items += list(add_aggregated(account_level_aggregated_resources))\n\n # at the end of the accounts loop, check if aggregated resources for task need to be added\n if self.aggregation_level == actions.ACTION_AGGREGATION_TASK and len(task_level_aggregated_resources) > 0:\n task_items += list(add_aggregated(task_level_aggregated_resources))\n except Exception as ex:\n raise_exception(ERR_SELECTING_TASK_RESOURCES, self.task[handlers.TASK_NAME], ex)\n\n finally:\n if self._timer is not None:\n # cancel time used avoid timeouts when selecting resources\n self._timer.cancel()\n if self.is_timed_out():\n raise_exception(ERR_TIMEOUT_SELECTING_RESOURCES, self._resource_name, self.service, task_name)\n\n self.start_timer(REMAINING_TIME_AFTER_STORE)\n\n self.actions_tracking.flush(self._timeout_event)\n if self.is_timed_out():\n raise_exception(ERR_CREATING_TASKS_FOR_SELECTED_RESOURCES, task_name)\n self._timer.cancel()\n else:\n self.actions_tracking.flush()\n\n self._logger.info(INFO_ADDED_ITEMS, len(task_items), self.task[handlers.TASK_NAME])\n\n running_time = float((datetime.now() - start).total_seconds())\n self._logger.info(INFO_RESULT, running_time)\n\n if self.metrics:\n put_task_select_data(task_name=task_name,\n items=count_resource_items,\n selected_items=selected_resource_items,\n logger=self._logger,\n selection_time=running_time)\n\n return safe_dict({\n \"datetime\": datetime.now().isoformat(),\n \"running-time\": running_time,\n \"dispatched-tasks\": task_items\n })\n\n finally:\n self._logger.flush()\n\n def select_timed_out(self):\n \"\"\"\n Function is called when the handling of the request times out\n :return:\n \"\"\"\n time_used = int(os.getenv(handlers.ENV_LAMBDA_TIMEOUT, 900)) - int((self._context.get_remaining_time_in_millis() / 1000))\n self._logger.error(ERR_TIMEOUT_SELECT_OR_STORE, time_used, self.task[handlers.TASK_NAME])\n self._timeout_event.set()\n self._logger.flush()\n self._timer.cancel()\n\n def start_timer(self, remaining):\n execution_time_left = (self._context.get_remaining_time_in_millis() / 1000.00) - remaining\n self._timer = threading.Timer(execution_time_left, self.select_timed_out)\n self._timer.start()\n\n def is_timed_out(self):\n return self._timeout_event is not None and self._timeout_event.is_set()\n\n def _build_describe_argument(self):\n \"\"\"\n Build the argument for the describe call that selects the resources\n :return: arguments for describe call\n \"\"\"\n args = {}\n # get the mapping for parameters that should be used as parameters to the describe method call to select the resources\n action_parameters = self.action_properties.get(actions.ACTION_PARAMETERS, {})\n for p in [p for p in action_parameters if action_parameters[p].get(actions.PARAM_DESCRIBE_PARAMETER) is not None]:\n\n if self.task_parameters.get(p) is not None:\n args[action_parameters[p][actions.PARAM_DESCRIBE_PARAMETER]] = self.task_parameters[p]\n\n # also add describe method parameters specified as select parameters in the metadata of the action\n select_parameters = self.action_properties.get(actions.ACTION_SELECT_PARAMETERS, {})\n if types.FunctionType == type(select_parameters):\n select_parameters = select_parameters(self.task, self.task_parameters)\n for p in select_parameters:\n args[p] = select_parameters[p]\n\n # region and account are separate describe parameters\n args.update({a: self.select_args[a] for a in self.select_args if a not in [handlers.HANDLER_EVENT_REGIONS,\n handlers.HANDLER_EVENT_ACCOUNT,\n handlers.HANDLER_EVENT_RESOURCE_NAME]})\n # action specified select jmes-path expression for resources\n if actions.ACTION_SELECT_EXPRESSION in self.action_properties:\n # replace parameter placeholders with values. We cant use str.format here are the jmespath expression may contain {}\n # as well for projection of attributes, so the use placeholders for parameter names in format %paramname%\n jmes = self.action_properties[actions.ACTION_SELECT_EXPRESSION]\n for p in self.task_parameters:\n jmes = jmes.replace(\"%{}%\".format(p), str(self.task_parameters[p]))\n args[\"select\"] = jmes\n return args\n","sub_path":"source/code/handlers/select_resources_handler.py","file_name":"select_resources_handler.py","file_ext":"py","file_size_in_byte":34092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"560018539","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[66]:\n\n\nimport pandas as pd\nimport pyarrow.parquet as pq\nimport datetime\n\n\n# In[67]:\n\n\ndf = pq.read_table(source=\"/home/toliman/Desktop/257-2021-4-player-log.parquet\").to_pandas()\n\n\n# In[68]:\n\n\nprint(df.shape)\nnew_df = pd.DataFrame(columns=('month', 'week_day', 'half_hour', 'efficiency', 'unix', 'views'), )\n\n\n# In[69]:\n\n\nfor i in range(df.shape[0]):\n if (i % 1000 == 0):\n print(i // 1000)\n obj = df.loc[i]\n in_t = datetime.datetime.fromtimestamp(obj['DateTimeInTick'] / 1000)\n out_t = datetime.datetime.fromtimestamp(obj['DateTimeOutTick'] / 1000)\n month_1 = in_t.month\n month_2 = out_t.month\n weekday_1 = in_t.weekday()\n weekday_2 = out_t.weekday()\n halfhour_1 = 2 * in_t.hour + 1 + int(in_t.minute >= 30)\n halfhour_2 = 2 * in_t.hour + 1 + int(in_t.minute >= 30)\n efficiency = obj['MacCountAll'] / obj['Duration']\n\n new_df = new_df.append({'month': month_1, 'week_day': weekday_1, 'half_hour': halfhour_1, 'efficiency': efficiency,\n 'unix': obj['DateTimeOutTick'], 'views': int(obj['MacCountAll'])},\n ignore_index=True)\n\n if month_1 != month_2 or weekday_1 != weekday_2 or halfhour_1 != halfhour_2:\n new_df = new_df.append(\n {'month': month_2, 'week_day': weekday_2, 'half_hour': halfhour_2, 'efficiency': efficiency,\n 'unix': obj['DateTimeOutTick'], 'views': int(obj['MacCountAll'])},\n ignore_index=True)\n\n\n# In[70]:\n\n\nnew_df.shape\n\n\n# In[71]:\n\n\nnew_df\n\n\n# In[72]:\n\n\nnew_df.to_csv('/home/toliman/Desktop/preprocessing_data.csv')\n\n","sub_path":"models/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"93236015","text":"import datetime as dt\nfrom collections import defaultdict\nfrom enum import Enum\nfrom typing import Iterable, List, Optional\n\nimport yaml\n\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.validators import MaxValueValidator, MinValueValidator\nfrom django.db import models\nfrom django.db.models import F, Sum, Value\nfrom django.db.models.functions import Coalesce\nfrom django.utils.functional import cached_property, classproperty\nfrom django.utils.timezone import now\nfrom esi.models import Token\nfrom eveuniverse.models import EveEntity, EveMoon, EveSolarSystem, EveType\n\nfrom allianceauth.authentication.models import CharacterOwnership\nfrom allianceauth.eveonline.models import EveCorporationInfo\nfrom allianceauth.services.hooks import get_extension_logger\nfrom app_utils.allianceauth import notify_admins_throttled\nfrom app_utils.datetime import ldap_time_2_datetime\nfrom app_utils.logging import LoggerAddTag\nfrom app_utils.views import (\n BootstrapStyle,\n bootstrap_icon_plus_name_html,\n bootstrap_label_html,\n)\n\nfrom . import __title__, constants\nfrom .app_settings import MOONMINING_REPROCESSING_YIELD, MOONMINING_VOLUME_PER_MONTH\nfrom .core import CalculatedExtraction, CalculatedExtractionProduct\nfrom .managers import (\n EveOreTypeManger,\n ExtractionManager,\n MiningLedgerRecordManager,\n MoonManager,\n RefineryManager,\n)\nfrom .providers import esi\n\nlogger = LoggerAddTag(get_extension_logger(__name__), __title__)\n# MAX_DISTANCE_TO_MOON_METERS = 3000000\n\n\nclass NotificationType(str, Enum):\n \"\"\"ESI notification types used in this app.\"\"\"\n\n MOONMINING_AUTOMATIC_FRACTURE = \"MoonminingAutomaticFracture\"\n MOONMINING_EXTRACTION_CANCELLED = \"MoonminingExtractionCancelled\"\n MOONMINING_EXTRACTION_FINISHED = \"MoonminingExtractionFinished\"\n MOONMINING_EXTRACTION_STARTED = \"MoonminingExtractionStarted\"\n MOONMINING_LASER_FIRED = \"MoonminingLaserFired\"\n\n def __str__(self) -> str:\n return self.value\n\n @classproperty\n def all_moon_mining(cls) -> set:\n \"\"\"Return all moon mining notifications\"\"\"\n return {\n cls.MOONMINING_AUTOMATIC_FRACTURE,\n cls.MOONMINING_EXTRACTION_CANCELLED,\n cls.MOONMINING_EXTRACTION_FINISHED,\n cls.MOONMINING_EXTRACTION_STARTED,\n cls.MOONMINING_LASER_FIRED,\n }\n\n\nclass OreRarityClass(models.IntegerChoices):\n \"\"\"Rarity class of an ore\"\"\"\n\n NONE = 0, \"\"\n R4 = 4, \"R4\"\n R8 = 8, \"R8\"\n R16 = 16, \"R16\"\n R32 = 32, \"R32\"\n R64 = 64, \"R64\"\n\n @property\n def bootstrap_tag_html(self) -> str:\n map_rarity_to_type = {\n self.R4: BootstrapStyle.PRIMARY,\n self.R8: BootstrapStyle.INFO,\n self.R16: BootstrapStyle.SUCCESS,\n self.R32: BootstrapStyle.WARNING,\n self.R64: BootstrapStyle.DANGER,\n }\n try:\n return bootstrap_label_html(\n f\"R{self.value}\", label=map_rarity_to_type[self.value]\n )\n except KeyError:\n return \"\"\n\n @classmethod\n def from_eve_group_id(cls, eve_group_id: int) -> \"OreRarityClass\":\n \"\"\"Create object from eve group ID\"\"\"\n map_group_2_rarity = {\n constants.EVE_GROUP_ID_UBIQUITOUS_MOON_ASTEROIDS: cls.R4,\n constants.EVE_GROUP_ID_COMMON_MOON_ASTEROIDS: cls.R8,\n constants.EVE_GROUP_ID_UNCOMMON_MOON_ASTEROIDS: cls.R16,\n constants.EVE_GROUP_ID_RARE_MOON_ASTEROIDS: cls.R32,\n constants.EVE_GROUP_ID_EXCEPTIONAL_MOON_ASTEROIDS: cls.R64,\n }\n try:\n return map_group_2_rarity[eve_group_id]\n except KeyError:\n return cls.NONE\n\n @classmethod\n def from_eve_type(cls, eve_type: EveType) -> \"OreRarityClass\":\n \"\"\"Create object from eve type\"\"\"\n return cls.from_eve_group_id(eve_type.eve_group_id)\n\n\nclass OreQualityClass(models.TextChoices):\n \"\"\"Quality class of an ore\"\"\"\n\n UNDEFINED = \"UN\", \"(undefined)\"\n REGULAR = \"RE\", \"regular\"\n IMPROVED = \"IM\", \"improved\"\n EXCELLENT = \"EX\", \"excellent\"\n\n @property\n def bootstrap_tag_html(self) -> str:\n \"\"\"Return bootstrap tag.\"\"\"\n map_quality_to_label_def = {\n self.IMPROVED: {\"text\": \"+15%\", \"label\": BootstrapStyle.SUCCESS},\n self.EXCELLENT: {\"text\": \"+100%\", \"label\": BootstrapStyle.WARNING},\n }\n try:\n label_def = map_quality_to_label_def[self.value]\n return bootstrap_label_html(label_def[\"text\"], label=label_def[\"label\"])\n except KeyError:\n return \"\"\n\n @classmethod\n def from_eve_type(cls, eve_type: EveType) -> \"OreQualityClass\":\n \"\"\"Create object from given eve type.\"\"\"\n map_value_2_quality_class = {\n 1: cls.REGULAR,\n 3: cls.IMPROVED,\n 5: cls.EXCELLENT,\n }\n try:\n dogma_attribute = eve_type.dogma_attributes.get(\n eve_dogma_attribute_id=constants.DOGMA_ATTRIBUTE_ID_ORE_QUALITY\n )\n except ObjectDoesNotExist:\n return cls.UNDEFINED\n try:\n return map_value_2_quality_class[int(dogma_attribute.value)]\n except KeyError:\n return cls.UNDEFINED\n\n\nclass EveOreType(EveType):\n \"\"\"Subset of EveType for all ore types.\n\n Ensures TYPE_MATERIALS and DOGMAS is always enabled and allows adding methods to types.\n \"\"\"\n\n URL_PROFILE_TYPE = \"https://www.kalkoken.org/apps/eveitems/\"\n\n class Meta:\n proxy = True\n\n objects = EveOreTypeManger()\n\n @property\n def profile_url(self) -> str:\n return f\"{self.URL_PROFILE_TYPE}?typeId={self.id}\"\n\n @property\n def icon_url_32(self) -> str:\n return self.icon_url(32)\n\n @property\n def rarity_class(self) -> OreRarityClass:\n return OreRarityClass.from_eve_type(self)\n\n @cached_property\n def quality_class(self) -> OreQualityClass:\n return OreQualityClass.from_eve_type(self)\n\n @cached_property\n def price(self) -> float:\n \"\"\"Return calculated price estimate in ISK per unit.\"\"\"\n return self.extras.refined_price\n\n def price_by_volume(self, volume: int) -> float:\n \"\"\"Return calculated price estimate in ISK for volume in m3.\"\"\"\n return self.price_by_units(volume / self.volume)\n\n def price_by_units(self, units: int) -> float:\n \"\"\"Return calculated price estimate in ISK for units.\"\"\"\n return self.price * units\n\n def calc_refined_value_per_unit(self, reprocessing_yield: float = None) -> float:\n \"\"\"Calculate the refined total value per unit and return it.\"\"\"\n if not reprocessing_yield:\n reprocessing_yield = MOONMINING_REPROCESSING_YIELD\n units = 10000\n r_units = units / 100\n value = 0\n for type_material in self.materials.select_related(\n \"material_eve_type__market_price\"\n ):\n try:\n price = type_material.material_eve_type.market_price.average_price\n except (ObjectDoesNotExist, AttributeError):\n continue\n if price:\n value += price * type_material.quantity * r_units * reprocessing_yield\n return value / units\n\n # EveOreType.objects.annotate(extras=Sum(\n # F(\"materials__quantity\") * Value(0.81)\n # * F(\"materials__material_eve_type__market_price__average_price\") / Value(100), output_field=FloatField()))\n\n @classmethod\n def _enabled_sections_union(cls, enabled_sections: Iterable[str]) -> set:\n \"\"\"Return enabled sections with TYPE_MATERIALS and DOGMAS always enabled.\"\"\"\n enabled_sections = super()._enabled_sections_union(\n enabled_sections=enabled_sections\n )\n enabled_sections.add(cls.Section.TYPE_MATERIALS)\n enabled_sections.add(cls.Section.DOGMAS)\n return enabled_sections\n\n\nclass EveOreTypeExtras(models.Model):\n \"\"\"Extra fields for an EveOreType.\"\"\"\n\n ore_type = models.OneToOneField(\n EveOreType, on_delete=models.CASCADE, related_name=\"extras\"\n )\n refined_price = models.FloatField(\n default=None,\n null=True,\n help_text=\"price calculated as sum of prices for refined materials\",\n )\n\n def __str__(self) -> str:\n return str(self.ore_type)\n\n\nclass Extraction(models.Model):\n \"\"\"A mining extraction.\"\"\"\n\n class Status(models.TextChoices):\n STARTED = \"ST\", \"started\" # has been started\n CANCELED = \"CN\", \"canceled\" # has been canceled\n READY = \"RD\", \"ready\" # has finished extraction and is ready to be fractured\n COMPLETED = \"CP\", \"completed\" # has been fractured\n UNDEFINED = \"UN\", \"undefined\" # unclear status\n\n @property\n def bootstrap_tag_html(self) -> str:\n map_to_type = {\n self.STARTED: BootstrapStyle.SUCCESS,\n self.CANCELED: BootstrapStyle.DANGER,\n self.READY: BootstrapStyle.WARNING,\n self.COMPLETED: BootstrapStyle.DEFAULT,\n self.UNDEFINED: \"\",\n }\n try:\n return bootstrap_label_html(self.label, label=map_to_type[self.value])\n except KeyError:\n return \"\"\n\n @classproperty\n def considered_active(cls):\n return [cls.STARTED, cls.READY]\n\n @classproperty\n def considered_inactive(cls):\n return [cls.CANCELED, cls.COMPLETED]\n\n @classmethod\n def from_calculated(cls, calculated):\n map_from_calculated = {\n CalculatedExtraction.Status.STARTED: cls.STARTED,\n CalculatedExtraction.Status.CANCELED: cls.CANCELED,\n CalculatedExtraction.Status.READY: cls.READY,\n CalculatedExtraction.Status.COMPLETED: cls.COMPLETED,\n CalculatedExtraction.Status.UNDEFINED: cls.UNDEFINED,\n }\n try:\n return map_from_calculated[calculated.status]\n except KeyError:\n return cls.UNDEFINED\n\n # PK\n refinery = models.ForeignKey(\n \"Refinery\", on_delete=models.CASCADE, related_name=\"extractions\"\n )\n started_at = models.DateTimeField(help_text=\"when this extraction was started\")\n # normal properties\n auto_fracture_at = models.DateTimeField(\n help_text=\"when this extraction will be automatically fractured\",\n )\n canceled_at = models.DateTimeField(\n null=True, default=None, help_text=\"when this extraction was canceled\"\n )\n canceled_by = models.ForeignKey(\n EveEntity,\n on_delete=models.SET_DEFAULT,\n null=True,\n default=None,\n related_name=\"+\",\n help_text=\"Eve character who canceled this extraction\",\n )\n chunk_arrival_at = models.DateTimeField(\n db_index=True, help_text=\"when this extraction is ready to be fractured\"\n )\n fractured_at = models.DateTimeField(\n null=True, default=None, help_text=\"when this extraction was fractured\"\n )\n fractured_by = models.ForeignKey(\n EveEntity,\n on_delete=models.SET_DEFAULT,\n null=True,\n default=None,\n related_name=\"+\",\n help_text=\"Eve character who fractured this extraction (if any)\",\n )\n is_jackpot = models.BooleanField(\n default=None,\n null=True,\n help_text=\"Whether this is a jackpot extraction (calculated)\",\n )\n started_by = models.ForeignKey(\n EveEntity,\n on_delete=models.SET_DEFAULT,\n null=True,\n default=None,\n related_name=\"+\",\n help_text=\"Eve character who started this extraction\",\n )\n status = models.CharField(\n max_length=2, choices=Status.choices, default=Status.UNDEFINED, db_index=True\n )\n value = models.FloatField(\n null=True,\n default=None,\n validators=[MinValueValidator(0.0)],\n help_text=\"Estimated value of this extraction (calculated)\",\n )\n\n objects = ExtractionManager()\n\n class Meta:\n constraints = [\n models.UniqueConstraint(\n fields=[\"refinery\", \"started_at\"], name=\"functional_pk_extraction\"\n )\n ]\n\n def __str__(self) -> str:\n return f\"{self.refinery} - {self.started_at} - {self.status}\"\n\n @property\n def status_enum(self) -> \"Extraction.Status\":\n \"\"\"Return current status as enum type.\"\"\"\n return self.Status(self.status)\n\n @cached_property\n def products_sorted(self):\n \"\"\"Return current products as sorted iterable.\"\"\"\n try:\n return (\n self.products.select_related(\n \"ore_type\", \"ore_type__eve_group\", \"ore_type__extras\"\n )\n .annotate(total_price=self._total_price_db_func())\n .order_by(\"-ore_type__eve_group_id\")\n )\n except (ObjectDoesNotExist, AttributeError):\n return type(self).objects.none()\n\n @cached_property\n def ledger(self) -> models.QuerySet:\n \"\"\"Return ledger for this extraction.\"\"\"\n max_day = self.chunk_arrival_at + dt.timedelta(days=6)\n return self.refinery.mining_ledger.filter(\n day__gte=self.chunk_arrival_at,\n day__lte=max_day,\n )\n\n def calc_value(self) -> Optional[float]:\n \"\"\"Calculate value estimate.\"\"\"\n try:\n return self.products.select_related(\n \"ore_type\", \"ore_type__extras\"\n ).aggregate(total_price=self._total_price_db_func())[\"total_price\"]\n except (ObjectDoesNotExist, KeyError, AttributeError):\n return None\n\n @staticmethod\n def _total_price_db_func():\n return Sum(\n Coalesce(F(\"ore_type__extras__refined_price\"), 0.0)\n * F(\"volume\")\n / F(\"ore_type__volume\"),\n output_field=models.FloatField(),\n )\n\n def calc_is_jackpot(self) -> Optional[bool]:\n \"\"\"Calculate if extraction is jackpot and return result.\n Return None if extraction has no products\"\"\"\n try:\n products_qualities = [\n product.ore_type.quality_class == OreQualityClass.EXCELLENT\n for product in self.products.select_related(\"ore_type\").all()\n ]\n except (ObjectDoesNotExist, AttributeError):\n return None\n else:\n if not products_qualities:\n return None\n return all(products_qualities)\n\n def update_calculated_properties(self) -> float:\n \"\"\"Update calculated properties for this extraction.\"\"\"\n self.value = self.calc_value()\n self.is_jackpot = self.calc_is_jackpot()\n self.save()\n\n\nclass ExtractionProduct(models.Model):\n \"\"\"A product within a mining extraction.\"\"\"\n\n extraction = models.ForeignKey(\n Extraction, on_delete=models.CASCADE, related_name=\"products\"\n )\n ore_type = models.ForeignKey(EveOreType, on_delete=models.CASCADE, related_name=\"+\")\n\n volume = models.FloatField(validators=[MinValueValidator(0.0)])\n\n class Meta:\n constraints = [\n models.UniqueConstraint(\n fields=[\"extraction\", \"ore_type\"],\n name=\"functional_pk_extractionproduct\",\n )\n ]\n\n def __str__(self) -> str:\n return f\"{self.extraction} - {self.ore_type}\"\n\n # @cached_property\n # def value(self) -> float:\n # \"\"\"returns calculated value estimate in ISK\"\"\"\n # return self.ore_type.price_by_volume(self.volume)\n\n\nclass General(models.Model):\n \"\"\"Meta model for global app permissions\"\"\"\n\n class Meta:\n managed = False\n default_permissions = ()\n permissions = (\n (\"basic_access\", \"Can access the moonmining app\"),\n (\"extractions_access\", \"Can access extractions and view owned moons\"),\n (\"reports_access\", \"Can access reports\"),\n (\"view_all_moons\", \"Can view all known moons\"),\n (\"upload_moon_scan\", \"Can upload moon scans\"),\n (\"add_refinery_owner\", \"Can add refinery owner\"),\n )\n\n\nclass MiningLedgerRecord(models.Model):\n \"\"\"A recorded mining activity in the vicinity of a refinery.\"\"\"\n\n refinery = models.ForeignKey(\n \"Refinery\",\n on_delete=models.CASCADE,\n related_name=\"mining_ledger\",\n help_text=\"Refinery this mining activity was observed at\",\n )\n day = models.DateField(help_text=\"last_updated in ESI\", db_index=True)\n character = models.ForeignKey(\n EveEntity,\n on_delete=models.CASCADE,\n related_name=\"+\",\n help_text=\"character that did the mining\",\n )\n ore_type = models.ForeignKey(\n EveOreType, on_delete=models.CASCADE, related_name=\"mining_ledger\"\n )\n # regular\n corporation = models.ForeignKey(\n EveEntity,\n on_delete=models.CASCADE,\n related_name=\"+\",\n help_text=\"corporation of the character at time data was recorded\",\n )\n quantity = models.PositiveBigIntegerField()\n user = models.ForeignKey(\n User,\n on_delete=models.CASCADE,\n default=None,\n null=True,\n related_name=\"mining_ledger\",\n )\n\n objects = MiningLedgerRecordManager()\n\n class Meta:\n constraints = [\n models.UniqueConstraint(\n fields=[\"refinery\", \"day\", \"character\", \"ore_type\"],\n name=\"functional_pk_mining_activity\",\n )\n ]\n\n\nclass Moon(models.Model):\n \"\"\"Known moon through either survey data or anchored refinery.\n\n \"Head\" model for many of the other models\n \"\"\"\n\n # pk\n eve_moon = models.OneToOneField(\n EveMoon, on_delete=models.CASCADE, primary_key=True, related_name=\"known_moon\"\n )\n # regular\n products_updated_at = models.DateTimeField(\n null=True, default=None, help_text=\"Time the last moon survey was uploaded\"\n )\n products_updated_by = models.ForeignKey(\n User,\n on_delete=models.SET_DEFAULT,\n null=True,\n default=None,\n help_text=\"User who uploaded the last moon survey\",\n )\n rarity_class = models.PositiveIntegerField(\n choices=OreRarityClass.choices, default=OreRarityClass.NONE\n )\n value = models.FloatField(\n null=True,\n default=None,\n validators=[MinValueValidator(0.0)],\n db_index=True,\n help_text=\"Calculated value estimate\",\n )\n\n objects = MoonManager()\n\n def __str__(self):\n return self.name\n\n @property\n def name(self) -> str:\n return self.eve_moon.name.replace(\"Moon \", \"\")\n\n @cached_property\n def region(self) -> str:\n return self.eve_moon.eve_planet.eve_solar_system.eve_constellation.eve_region\n\n @property\n def is_owned(self) -> bool:\n return hasattr(self, \"refinery\")\n\n @cached_property\n def products_sorted(self) -> models.QuerySet:\n \"\"\"Return current products as sorted iterable.\"\"\"\n try:\n return (\n self.products.select_related(\n \"ore_type\", \"ore_type__eve_group\", \"ore_type__extras\"\n )\n .annotate(total_price=self._total_price_db_func())\n .order_by(\"-ore_type__eve_group_id\")\n )\n except (ObjectDoesNotExist, AttributeError):\n return type(self).objects.none()\n\n @property\n def rarity_tag_html(self) -> str:\n return OreRarityClass(self.rarity_class).bootstrap_tag_html\n\n def calc_rarity_class(self) -> Optional[OreRarityClass]:\n try:\n return max(\n [\n OreRarityClass.from_eve_group_id(eve_group_id)\n for eve_group_id in self.products.select_related(\n \"ore_type\"\n ).values_list(\"ore_type__eve_group_id\", flat=True)\n ]\n )\n except (ObjectDoesNotExist, ValueError):\n return OreRarityClass.NONE\n\n def calc_value(self) -> Optional[float]:\n \"\"\"Calculate value estimate.\"\"\"\n try:\n return self.products.select_related(\n \"ore_type\", \"ore_type__extras\"\n ).aggregate(total_value=self._total_price_db_func())[\"total_value\"]\n except (ObjectDoesNotExist, KeyError, AttributeError):\n return None\n\n @staticmethod\n def _total_price_db_func():\n return Sum(\n Coalesce(F(\"ore_type__extras__refined_price\"), 0.0)\n * F(\"amount\")\n * Value(float(MOONMINING_VOLUME_PER_MONTH))\n / F(\"ore_type__volume\"),\n output_field=models.FloatField(),\n )\n\n def update_calculated_properties(self):\n \"\"\"Update all calculated properties for this moon.\"\"\"\n self.value = self.calc_value()\n self.rarity_class = self.calc_rarity_class()\n self.save()\n\n\nclass MoonProduct(models.Model):\n \"\"\"A product of a moon, i.e. a specifc ore.\"\"\"\n\n moon = models.ForeignKey(Moon, on_delete=models.CASCADE, related_name=\"products\")\n ore_type = models.ForeignKey(EveOreType, on_delete=models.CASCADE, related_name=\"+\")\n\n amount = models.FloatField(\n validators=[MinValueValidator(0.0), MaxValueValidator(1.0)]\n )\n\n def __str__(self):\n return f\"{self.ore_type.name} - {self.amount}\"\n\n class Meta:\n constraints = [\n models.UniqueConstraint(\n fields=[\"moon\", \"ore_type\"], name=\"functional_pk_moonproduct\"\n )\n ]\n\n # @cached_property\n # def value(self) -> float:\n # \"\"\"returns calculated value estimate in ISK\"\"\"\n # return self.ore_type.price_by_volume(MOONMINING_VOLUME_PER_MONTH * self.amount)\n\n @property\n def amount_percent(self) -> float:\n \"\"\"Return the amount of this product as percent\"\"\"\n return self.amount * 100\n\n\nclass Notification(models.Model):\n \"\"\"An EVE Online notification about structures.\"\"\"\n\n # pk\n owner = models.ForeignKey(\n \"Owner\",\n on_delete=models.CASCADE,\n related_name=\"notifications\",\n help_text=\"Corporation that received this notification\",\n )\n notification_id = models.PositiveBigIntegerField(verbose_name=\"id\")\n # regular\n created = models.DateTimeField(\n null=True,\n default=None,\n help_text=\"Date when this notification was first received from ESI\",\n )\n details = models.JSONField(default=dict)\n notif_type = models.CharField(\n max_length=100,\n default=\"\",\n db_index=True,\n verbose_name=\"type\",\n help_text=\"type of this notification as reported by ESI\",\n )\n is_read = models.BooleanField(\n null=True,\n default=None,\n help_text=\"True when this notification has read in the eve client\",\n )\n last_updated = models.DateTimeField(\n help_text=\"Date when this notification has last been updated from ESI\"\n )\n sender = models.ForeignKey(\n EveEntity, on_delete=models.CASCADE, null=True, default=None, related_name=\"+\"\n )\n timestamp = models.DateTimeField(db_index=True)\n\n class Meta:\n constraints = [\n models.UniqueConstraint(\n fields=[\"owner\", \"notification_id\"], name=\"functional_pk_notification\"\n )\n ]\n\n def __str__(self) -> str:\n return str(self.notification_id)\n\n def __repr__(self) -> str:\n return \"%s(notification_id=%d, owner='%s', notif_type='%s')\" % (\n self.__class__.__name__,\n self.notification_id,\n self.owner,\n self.notif_type,\n )\n\n\nclass Owner(models.Model):\n \"\"\"A EVE Online corporation owning refineries.\"\"\"\n\n ESI_SERVICE_NAME_MOON_DRILLING = \"Moon Drilling\"\n\n # pk\n corporation = models.OneToOneField(\n EveCorporationInfo,\n on_delete=models.CASCADE,\n primary_key=True,\n related_name=\"mining_corporation\",\n )\n # regular\n character_ownership = models.ForeignKey(\n CharacterOwnership,\n on_delete=models.SET_DEFAULT,\n default=None,\n null=True,\n related_name=\"+\",\n help_text=\"character used to sync this corporation from ESI\",\n )\n is_enabled = models.BooleanField(\n default=True,\n db_index=True,\n help_text=\"disabled corporations are excluded from the update process\",\n )\n last_update_at = models.DateTimeField(\n null=True, default=None, help_text=\"time of last successful update\"\n )\n last_update_ok = models.BooleanField(\n null=True, default=None, help_text=\"True if the last update was successful\"\n )\n\n def __str__(self):\n return self.name\n\n @property\n def name(self) -> str:\n alliance_ticker_str = (\n f\" [{self.corporation.alliance.alliance_ticker}]\"\n if self.corporation.alliance\n else \"\"\n )\n return f\"{self.corporation}{alliance_ticker_str}\"\n\n @property\n def alliance_name(self) -> str:\n return (\n self.corporation.alliance.alliance_name if self.corporation.alliance else \"\"\n )\n\n @property\n def name_html(self):\n return bootstrap_icon_plus_name_html(\n self.corporation.logo_url(size=constants.IconSize.SMALL),\n self.name,\n size=constants.IconSize.SMALL,\n )\n\n def fetch_token(self) -> Token:\n \"\"\"Return valid token for this mining corp or raise exception on any error.\"\"\"\n if not self.character_ownership:\n raise RuntimeError(\"This owner has no character configured.\")\n token = (\n Token.objects.filter(\n character_id=self.character_ownership.character.character_id\n )\n .require_scopes(self.esi_scopes())\n .require_valid()\n .first()\n )\n if not token:\n raise Token.DoesNotExist(f\"{self}: No valid token found.\")\n return token\n\n def update_refineries_from_esi(self):\n \"\"\"Update all refineries from ESI.\"\"\"\n logger.info(\"%s: Updating refineries...\", self)\n refineries = self._fetch_refineries_from_esi()\n for structure_id, _ in refineries.items():\n try:\n self._update_or_create_refinery_from_esi(structure_id)\n except OSError as exc:\n exc_name = type(exc).__name__\n msg = (\n f\"{self}: Failed to fetch refinery with ID {structure_id} from ESI\"\n )\n message_id = (\n f\"{__title__}-update_refineries_from_esi-\"\n f\"{structure_id}-{exc_name}\"\n )\n notify_admins_throttled(\n message_id=message_id,\n message=f\"{msg}: {exc_name}: {exc}.\",\n title=f\"{__title__}: Failed to fetch refinery\",\n level=\"warning\",\n )\n logger.warning(msg, exc_info=True)\n # remove refineries that no longer exist\n self.refineries.exclude(id__in=refineries).delete()\n\n self.last_update_at = now()\n self.save()\n\n def _fetch_refineries_from_esi(self) -> dict:\n \"\"\"Return current refineries with moon drills from ESI for this owner.\"\"\"\n logger.info(\"%s: Fetching refineries from ESI...\", self)\n structures = esi.client.Corporation.get_corporations_corporation_id_structures(\n corporation_id=self.corporation.corporation_id,\n token=self.fetch_token().valid_access_token(),\n ).results()\n refineries = dict()\n for structure_info in structures:\n eve_type, _ = EveType.objects.get_or_create_esi(\n id=structure_info[\"type_id\"]\n )\n structure_info[\"_eve_type\"] = eve_type\n service_names = (\n {row[\"name\"] for row in structure_info[\"services\"]}\n if structure_info.get(\"services\")\n else set()\n )\n if (\n eve_type.eve_group_id == constants.EVE_GROUP_ID_REFINERY\n and self.ESI_SERVICE_NAME_MOON_DRILLING in service_names\n ):\n refineries[structure_info[\"structure_id\"]] = structure_info\n return refineries\n\n def _update_or_create_refinery_from_esi(self, structure_id: int):\n \"\"\"Update or create a refinery with universe data from ESI.\"\"\"\n logger.info(\"%s: Fetching details for refinery #%d\", self, structure_id)\n structure_info = esi.client.Universe.get_universe_structures_structure_id(\n structure_id=structure_id, token=self.fetch_token().valid_access_token()\n ).results()\n refinery, _ = Refinery.objects.update_or_create(\n id=structure_id,\n defaults={\n \"name\": structure_info[\"name\"],\n \"eve_type\": EveType.objects.get(id=structure_info[\"type_id\"]),\n \"owner\": self,\n },\n )\n if not refinery.moon:\n refinery.update_moon_from_structure_info(structure_info)\n return True\n\n def fetch_notifications_from_esi(self) -> bool:\n \"\"\"fetches notification for the current owners and proceses them\"\"\"\n notifications = self._fetch_moon_notifications_from_esi()\n self._store_notifications(notifications)\n\n def _fetch_moon_notifications_from_esi(self) -> dict:\n \"\"\"Fetch all notifications from ESI for current owner.\"\"\"\n logger.info(\"%s: Fetching notifications from ESI...\", self)\n all_notifications = (\n esi.client.Character.get_characters_character_id_notifications(\n character_id=self.character_ownership.character.character_id,\n token=self.fetch_token().valid_access_token(),\n ).results()\n )\n moon_notifications = [\n notif\n for notif in all_notifications\n if notif[\"type\"] in NotificationType.all_moon_mining\n ]\n return moon_notifications\n\n def _store_notifications(self, notifications: list) -> int:\n \"\"\"Store new notifications in database and return count of new objects.\"\"\"\n # identify new notifications\n existing_notification_ids = set(\n self.notifications.values_list(\"notification_id\", flat=True)\n )\n new_notifications = [\n obj\n for obj in notifications\n if obj[\"notification_id\"] not in existing_notification_ids\n ]\n # create new notif objects\n sender_type_map = {\n \"character\": EveEntity.CATEGORY_CHARACTER,\n \"corporation\": EveEntity.CATEGORY_CORPORATION,\n \"alliance\": EveEntity.CATEGORY_ALLIANCE,\n }\n new_notification_objects = list()\n for notification in new_notifications:\n known_sender_type = sender_type_map.get(notification[\"sender_type\"])\n if known_sender_type:\n sender, _ = EveEntity.objects.get_or_create_esi(\n id=notification[\"sender_id\"]\n )\n else:\n sender = None\n text = notification[\"text\"] if \"text\" in notification else None\n is_read = notification[\"is_read\"] if \"is_read\" in notification else None\n new_notification_objects.append(\n Notification(\n notification_id=notification[\"notification_id\"],\n owner=self,\n created=now(),\n details=yaml.safe_load(text),\n is_read=is_read,\n last_updated=now(),\n # at least one type has a trailing white space\n # which we need to remove\n notif_type=notification[\"type\"].strip(),\n sender=sender,\n timestamp=notification[\"timestamp\"],\n )\n )\n\n Notification.objects.bulk_create(new_notification_objects)\n if len(new_notification_objects) > 0:\n logger.info(\n \"%s: Received %d new notifications from ESI\",\n self,\n len(new_notification_objects),\n )\n else:\n logger.info(\"%s: No new notifications received from ESI\", self)\n return len(new_notification_objects)\n\n def update_extractions(self):\n self.update_extractions_from_esi()\n Extraction.objects.all().update_status()\n self.update_extractions_from_notifications()\n\n def update_extractions_from_esi(self):\n \"\"\"Creates new extractions from ESI for current owner.\"\"\"\n logger.info(\"%s: Fetching extractions from ESI...\", self)\n extractions = (\n esi.client.Industry.get_corporation_corporation_id_mining_extractions(\n corporation_id=self.corporation.corporation_id,\n token=self.fetch_token().valid_access_token(),\n ).results()\n )\n logger.info(\"%s: Received %d extractions from ESI.\", self, len(extractions))\n extractions_by_refinery = defaultdict(list)\n for row in extractions:\n extractions_by_refinery[row[\"structure_id\"]].append(row)\n new_extractions_count = 0\n for refinery_id, refinery_extractions in extractions_by_refinery.items():\n try:\n refinery = self.refineries.get(pk=refinery_id)\n except Refinery.DoesNotExist:\n continue\n new_extractions_count += refinery.create_extractions_from_esi_response(\n refinery_extractions\n )\n refinery.cancel_started_extractions_missing_from_list(\n [row[\"extraction_start_time\"] for row in refinery_extractions]\n )\n if new_extractions_count:\n logger.info(\"%s: Created %d new extractions.\", self, new_extractions_count)\n\n def update_extractions_from_notifications(self):\n \"\"\"Add information from notifications to extractions.\"\"\"\n logger.info(\"%s: Updating extractions from notifications...\", self)\n notifications_count = self.notifications.count()\n if not notifications_count:\n logger.info(\"%s: No moon notifications.\", self)\n return\n logger.info(\"%s: Processing %d moon notifications.\", self, notifications_count)\n\n # create or update extractions from notifications by refinery\n for refinery in self.refineries.all():\n updated_count = 0\n extraction = None\n notifications_for_refinery = self.notifications.filter(\n details__structureID=refinery.id\n )\n if not refinery.moon and notifications_for_refinery.exists():\n \"\"\"Update the refinery's moon from notification in case\n it was not found by nearest_celestial.\n \"\"\"\n notif = notifications_for_refinery.first()\n refinery.update_moon_from_eve_id(notif.details[\"moonID\"])\n for notif in notifications_for_refinery.order_by(\"timestamp\"):\n if notif.notif_type == NotificationType.MOONMINING_EXTRACTION_STARTED:\n extraction = CalculatedExtraction(\n refinery_id=refinery.id,\n status=CalculatedExtraction.Status.STARTED,\n chunk_arrival_at=ldap_time_2_datetime(\n notif.details[\"readyTime\"]\n ),\n auto_fracture_at=ldap_time_2_datetime(\n notif.details[\"autoTime\"]\n ),\n started_by=notif.details.get(\"startedBy\"),\n products=CalculatedExtractionProduct.create_list_from_dict(\n notif.details[\"oreVolumeByType\"]\n ),\n )\n\n elif extraction:\n if extraction.status == CalculatedExtraction.Status.STARTED:\n if (\n notif.notif_type\n == NotificationType.MOONMINING_EXTRACTION_CANCELLED\n ):\n extraction.status = CalculatedExtraction.Status.CANCELED\n extraction.canceled_at = notif.timestamp\n extraction.canceled_by = notif.details.get(\"cancelledBy\")\n updated = Extraction.objects.update_from_calculated(\n extraction\n )\n updated_count += 1 if updated else 0\n extraction = None\n\n elif (\n notif.notif_type\n == NotificationType.MOONMINING_EXTRACTION_FINISHED\n ):\n extraction.status = CalculatedExtraction.Status.READY\n extraction.products = (\n CalculatedExtractionProduct.create_list_from_dict(\n notif.details[\"oreVolumeByType\"]\n )\n )\n\n elif extraction.status == CalculatedExtraction.Status.READY:\n if notif.notif_type == NotificationType.MOONMINING_LASER_FIRED:\n extraction.status = CalculatedExtraction.Status.COMPLETED\n extraction.fractured_at = notif.timestamp\n extraction.fractured_by = notif.details.get(\"firedBy\")\n extraction.products = (\n CalculatedExtractionProduct.create_list_from_dict(\n notif.details[\"oreVolumeByType\"]\n )\n )\n updated = Extraction.objects.update_from_calculated(\n extraction\n )\n updated_count += 1 if updated else 0\n extraction = None\n\n elif (\n notif.notif_type\n == NotificationType.MOONMINING_AUTOMATIC_FRACTURE\n ):\n extraction.status = CalculatedExtraction.Status.COMPLETED\n extraction.fractured_at = notif.timestamp\n extraction.products = (\n CalculatedExtractionProduct.create_list_from_dict(\n notif.details[\"oreVolumeByType\"]\n )\n )\n updated = Extraction.objects.update_from_calculated(\n extraction\n )\n updated_count += 1 if updated else 0\n extraction = None\n else:\n if (\n notif.notif_type\n == NotificationType.MOONMINING_EXTRACTION_FINISHED\n ):\n extraction = CalculatedExtraction(\n refinery_id=refinery.id,\n status=CalculatedExtraction.Status.READY,\n auto_fracture_at=ldap_time_2_datetime(\n notif.details[\"autoTime\"]\n ),\n products=CalculatedExtractionProduct.create_list_from_dict(\n notif.details[\"oreVolumeByType\"]\n ),\n )\n\n if extraction:\n updated = Extraction.objects.update_from_calculated(extraction)\n updated_count += 1 if updated else 0\n if updated_count:\n logger.info(\n \"%s: %s: Updated %d extractions from notifications\",\n self,\n refinery,\n updated_count,\n )\n\n def fetch_mining_ledger_observers_from_esi(self) -> set:\n logger.info(\"%s: Fetching mining observers from ESI...\", self)\n observers = esi.client.Industry.get_corporation_corporation_id_mining_observers(\n corporation_id=self.corporation.corporation_id,\n token=self.fetch_token().valid_access_token(),\n ).results()\n logger.info(\"%s: Received %d observers from ESI.\", self, len(observers))\n return {\n row[\"observer_id\"]\n for row in observers\n if row[\"observer_type\"] == \"structure\"\n }\n\n @classmethod\n def esi_scopes(cls):\n \"\"\"Return list of all required esi scopes.\"\"\"\n return [\n \"esi-industry.read_corporation_mining.v1\",\n \"esi-universe.read_structures.v1\",\n \"esi-characters.read_notifications.v1\",\n \"esi-corporations.read_structures.v1\",\n \"esi-industry.read_corporation_mining.v1\",\n ]\n\n\nclass Refinery(models.Model):\n \"\"\"An Eve Online refinery structure.\"\"\"\n\n # pk\n id = models.PositiveBigIntegerField(primary_key=True)\n # regular\n eve_type = models.ForeignKey(EveType, on_delete=models.CASCADE, related_name=\"+\")\n moon = models.OneToOneField(\n Moon,\n on_delete=models.SET_DEFAULT,\n default=None,\n null=True,\n related_name=\"refinery\",\n help_text=\"The moon this refinery is anchored at (if any)\",\n )\n name = models.CharField(max_length=150, db_index=True)\n owner = models.ForeignKey(\n Owner,\n on_delete=models.CASCADE,\n related_name=\"refineries\",\n help_text=\"Corporation that owns this refinery\",\n )\n ledger_last_update_at = models.DateTimeField(\n null=True, default=None, help_text=\"last successful update of mining ledger\"\n )\n ledger_last_update_ok = models.BooleanField(\n null=True,\n default=None,\n help_text=\"True if the last update of the mining ledger was successful\",\n )\n\n objects = RefineryManager()\n\n def __str__(self):\n return self.name\n\n def update_moon_from_structure_info(self, structure_info: dict) -> bool:\n \"\"\"Find moon based on location in space and update the object.\n Returns True when successful, else false\n \"\"\"\n solar_system, _ = EveSolarSystem.objects.get_or_create_esi(\n id=structure_info[\"solar_system_id\"]\n )\n try:\n nearest_celestial = solar_system.nearest_celestial(\n structure_info[\"position\"][\"x\"],\n structure_info[\"position\"][\"y\"],\n structure_info[\"position\"][\"z\"],\n )\n except OSError:\n logger.exception(\"%s: Failed to fetch nearest celestial \", self)\n else:\n if (\n nearest_celestial\n and nearest_celestial.eve_type.id == constants.EVE_TYPE_ID_MOON\n ):\n eve_moon = nearest_celestial.eve_object\n moon, _ = Moon.objects.get_or_create(eve_moon=eve_moon)\n self.moon = moon\n self.save()\n return True\n return False\n\n def update_moon_from_eve_id(self, eve_moon_id: int):\n eve_moon, _ = EveMoon.objects.get_or_create_esi(id=eve_moon_id)\n moon, _ = Moon.objects.get_or_create(eve_moon=eve_moon)\n self.moon = moon\n self.save()\n\n def update_mining_ledger_from_esi(self):\n logger.info(\"%s: Fetching mining observer records from ESI...\", self)\n self.ledger_last_update_at = now()\n self.ledger_last_update_ok = None\n self.save()\n records = esi.client.Industry.get_corporation_corporation_id_mining_observers_observer_id(\n corporation_id=self.owner.corporation.corporation_id,\n observer_id=self.id,\n token=self.owner.fetch_token().valid_access_token(),\n ).results()\n # preload all missing ore types\n EveOreType.objects.bulk_get_or_create_esi(\n ids={record[\"type_id\"] for record in records}\n )\n character_2_user = {\n obj[0]: obj[1]\n for obj in CharacterOwnership.objects.values_list(\n \"character__character_id\",\n \"user_id\",\n )\n }\n for record in records:\n character, _ = EveEntity.objects.get_or_create(id=record[\"character_id\"])\n corporation, _ = EveEntity.objects.get_or_create(\n id=record[\"recorded_corporation_id\"]\n )\n MiningLedgerRecord.objects.update_or_create(\n refinery=self,\n character=character,\n day=record[\"last_updated\"],\n ore_type_id=record[\"type_id\"],\n defaults={\n \"corporation\": corporation,\n \"quantity\": record[\"quantity\"],\n \"user_id\": character_2_user.get(character.id),\n },\n )\n EveEntity.objects.bulk_update_new_esi()\n self.ledger_last_update_ok = True\n self.save()\n\n def create_extractions_from_esi_response(self, esi_extractions: List[dict]) -> int:\n existing_extractions = set(\n self.extractions.values_list(\"started_at\", flat=True)\n )\n new_extractions = list()\n for esi_extraction in esi_extractions:\n extraction_start_time = esi_extraction[\"extraction_start_time\"]\n if extraction_start_time not in existing_extractions:\n chunk_arrival_time = esi_extraction[\"chunk_arrival_time\"]\n auto_fracture_at = esi_extraction[\"natural_decay_time\"]\n if now() > auto_fracture_at:\n status = Extraction.Status.COMPLETED\n elif now() > chunk_arrival_time:\n status = Extraction.Status.READY\n else:\n status = Extraction.Status.STARTED\n new_extractions.append(\n Extraction(\n refinery=self,\n chunk_arrival_at=esi_extraction[\"chunk_arrival_time\"],\n started_at=extraction_start_time,\n status=status,\n auto_fracture_at=auto_fracture_at,\n )\n )\n if new_extractions:\n Extraction.objects.bulk_create(new_extractions, batch_size=500)\n return len(new_extractions)\n\n def cancel_started_extractions_missing_from_list(\n self, started_at_list: List[dt.datetime]\n ) -> int:\n \"\"\"Cancel started extractions that are not included in given list.\"\"\"\n canceled_extractions_qs = self.extractions.filter(\n status=Extraction.Status.STARTED\n ).exclude(started_at__in=started_at_list)\n canceled_extractions_count = canceled_extractions_qs.count()\n if canceled_extractions_count:\n logger.info(\n \"%s: Found %d likely canceled extractions.\",\n self,\n canceled_extractions_count,\n )\n canceled_extractions_qs.update(\n status=Extraction.Status.CANCELED, canceled_at=now()\n )\n return canceled_extractions_count\n","sub_path":"moonmining/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":47386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"432524302","text":"import requests\nimport json\nfrom src.models import Item\n\n# item\n# itemId : int\n# options : [] or {} ?\n# special : string(400)\n\nitems = [Item(menuId=1,\n options=[\"Mayo\",\"Mustard\"],\n special=\"let it get a little cold.\").toDict(),\n Item ( menuId=3 ,\n options=[ \"Medium Rare\" , \"Extra sauce\" ] ,\n special=\"I want it straight from the grill\" ).toDict()]\n\ndata = {\n 'userId' : '1',\n 'status' : 'Sent',\n 'receipt' : {},\n 'items': items\n}\n\n# Success Case\njsonData = json.dumps(data)\nprint('Data: ' + jsonData)\nresp_succeed = requests.post('http://127.0.0.1:5000/order',json=jsonData)\n\nprint('Success? ' + str(resp_succeed.json()))\n","sub_path":"DBService/test/OrderTest.py","file_name":"OrderTest.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"422640626","text":"import pickle\n\nimport pandas as pd\nfrom pandas.api.extensions import ExtensionDtype\n\nimport cudf\n\n\nclass CategoricalDtype(ExtensionDtype):\n def __init__(self, categories=None, ordered=None):\n \"\"\"\n dtype similar to pd.CategoricalDtype with the categories\n stored on the GPU.\n \"\"\"\n self._categories = self._init_categories(categories)\n self.ordered = ordered\n\n @property\n def categories(self):\n if self._categories is None:\n return cudf.core.index.as_index(\n cudf.core.column.column_empty(0, dtype=\"object\", masked=False)\n )\n return cudf.core.index.as_index(self._categories)\n\n @property\n def type(self):\n return self._categories.dtype.type\n\n @property\n def name(self):\n return \"category\"\n\n @property\n def str(self):\n return \"|O08\"\n\n @classmethod\n def from_pandas(cls, dtype):\n return CategoricalDtype(\n categories=dtype.categories, ordered=dtype.ordered\n )\n\n def to_pandas(self):\n if self.categories is None:\n categories = None\n else:\n categories = self.categories.to_pandas()\n return pd.CategoricalDtype(categories=categories, ordered=self.ordered)\n\n def _init_categories(self, categories):\n if categories is None:\n return categories\n if len(categories) == 0:\n dtype = \"object\"\n else:\n dtype = None\n return cudf.core.column.as_column(categories, dtype=dtype)\n\n def __eq__(self, other):\n if isinstance(other, str):\n return other == self.name\n elif other is self:\n return True\n elif not isinstance(other, self.__class__):\n return False\n elif self._categories is None or other._categories is None:\n return True\n else:\n return (\n self._categories.dtype == other._categories.dtype\n and self._categories.equals(other._categories)\n )\n\n def construct_from_string(self):\n raise NotImplementedError()\n\n def serialize(self):\n header = {}\n frames = []\n header[\"ordered\"] = self.ordered\n if self.categories is not None:\n categories_header, categories_frames = self.categories.serialize()\n header[\"categories\"] = categories_header\n frames.extend(categories_frames)\n return header, frames\n\n @classmethod\n def deserialize(cls, header, frames):\n ordered = header[\"ordered\"]\n categories_header = header[\"categories\"]\n categories_frames = frames\n categories_type = pickle.loads(categories_header[\"type-serialized\"])\n categories = categories_type.deserialize(\n categories_header, categories_frames\n )\n return cls(categories=categories, ordered=ordered)\n","sub_path":"python/cudf/cudf/core/dtypes.py","file_name":"dtypes.py","file_ext":"py","file_size_in_byte":2888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"492192210","text":"from typing import List, Optional, Union\n\nfrom lnbits.helpers import urlsafe_short_hash\n\nfrom . import db\nfrom .models import Captcha\n\n\nasync def create_captcha(\n *,\n wallet_id: str,\n url: str,\n memo: str,\n description: Optional[str] = None,\n amount: int = 0,\n remembers: bool = True,\n) -> Captcha:\n captcha_id = urlsafe_short_hash()\n await db.execute(\n \"\"\"\n INSERT INTO captcha.captchas (id, wallet, url, memo, description, amount, remembers)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n \"\"\",\n (captcha_id, wallet_id, url, memo, description, amount, int(remembers)),\n )\n\n captcha = await get_captcha(captcha_id)\n assert captcha, \"Newly created captcha couldn't be retrieved\"\n return captcha\n\n\nasync def get_captcha(captcha_id: str) -> Optional[Captcha]:\n row = await db.fetchone(\n \"SELECT * FROM captcha.captchas WHERE id = ?\", (captcha_id,)\n )\n\n return Captcha.from_row(row) if row else None\n\n\nasync def get_captchas(wallet_ids: Union[str, List[str]]) -> List[Captcha]:\n if isinstance(wallet_ids, str):\n wallet_ids = [wallet_ids]\n\n q = \",\".join([\"?\"] * len(wallet_ids))\n rows = await db.fetchall(\n f\"SELECT * FROM captcha.captchas WHERE wallet IN ({q})\", (*wallet_ids,)\n )\n\n return [Captcha.from_row(row) for row in rows]\n\n\nasync def delete_captcha(captcha_id: str) -> None:\n await db.execute(\"DELETE FROM captcha.captchas WHERE id = ?\", (captcha_id,))\n","sub_path":"lnbits/extensions/captcha/crud.py","file_name":"crud.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"279188540","text":"from django.shortcuts import render\nfrom django import forms\n\nimport random\n\nfrom .game import GameBoard\nfrom .player import *\n\ndef index(request, player=GameBoard.player_x):\n if request.method == \"POST\":\n move_form = SubmitMoveForm(request.POST)\n \n state = move_form['state'].value()\n row = int(move_form['row'].value())\n column = int(move_form['column'].value())\n \n game_board = GameBoard(state)\n game_board.move(row, column)\n \n if game_board.is_game_over():\n return render(request, 'end.html', {'game': game_board})\n \n game_board.move(*PlayerMinimax.choose_move(game_board))\n \n if game_board.is_game_over():\n return render(request, 'end.html', {'game': game_board})\n \n else:\n game_board = GameBoard()\n \n if player == GameBoard.player_o:\n game_board.move(*random.choice(game_board.get_valid_moves()[:5]))\n\n return render(request, 'board.html', {'game': game_board})\n \nclass SubmitMoveForm(forms.Form):\n row = forms.IntegerField(min_value=0, max_value=2)\n column = forms.IntegerField(min_value=0, max_value=2)\n state = forms.CharField(min_length=9, max_length=9)\n ","sub_path":"gameapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"142526634","text":"import csv\nfrom geopy.geocoders import Nominatim\n\ngeolocator = Nominatim(user_agent = 'https://nominatim.openstreetmap.org/')\n\ndef location(city):\n\n location = geolocator.geocode(str(city) + \" Airport\")\n return((location.latitude, location.longitude))\n\n#with open('flight.csv', encoding='utf8') as csv_file:\nwith open('flights.csv', mode='r+', encoding=\"utf-8\") as csv_file:\n csv_reader = csv.DictReader(csv_file)\n\n with open('flightCoor.csv', mode='w', newline=\"\") as new_csv_file:\n fieldNames = [\"From City\", \"latitude\", \"longitude\", \"To City\", \"latitude\", \"longitude\"]\n writer = csv.DictWriter(new_csv_file, fieldnames=fieldNames)\n writer.writeheader()\n writer = csv.writer(new_csv_file)\n\n for i in csv_reader:\n \n fromPlace = i[' From_City ']\n fromLatitude, fromLongitude = location(i[' From_City '])\n print(fromPlace,fromLatitude, fromLongitude)\n\n toPlace = i[' To_City ']\n toLatitude, toLongitude = location(i[' To_City '])\n\n row = (fromPlace, fromLatitude, fromLongitude, toPlace, toLatitude, toLongitude,)\n writer.writerow(row)\n\ncsv_file.close()\nnew_csv_file.close()\n\n\n","sub_path":"GetLonLat.py","file_name":"GetLonLat.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"437114084","text":"import pandas as pd\nfrom nltk.corpus import wordnet as wn\nfrom common import WORDSIM_PATH, find_max_similarity\nfrom similarity import wup_similarity, path_similarity, lch_similarity\nfrom scipy.stats import spearmanr, pearsonr\n\nif __name__ == '__main__':\n word_sim_df = pd.read_csv(WORDSIM_PATH, index_col=['Word 1', 'Word 2']).sort_index()\n\n for index, row in word_sim_df.iterrows():\n synsets1 = wn.synsets(index[0])\n synsets2 = wn.synsets(index[1])\n word_sim_df.loc[index, 'wup_similarity'] = find_max_similarity(synsets1, synsets2, wup_similarity)\n word_sim_df.loc[index, 'path_similarity'] = find_max_similarity(synsets1, synsets2, path_similarity)\n word_sim_df.loc[index, 'lch_similarity'] = find_max_similarity(synsets1, synsets2, lch_similarity)\n\n print(word_sim_df.to_string())\n print(\"\\n\\n\")\n spearman_wup = spearmanr(word_sim_df.loc[:, 'Human (mean)'].values, word_sim_df.loc[:, 'wup_similarity'].values)[0]\n pearson_wup = pearsonr(word_sim_df.loc[:, 'Human (mean)'].values, word_sim_df.loc[:, 'wup_similarity'].values)[0]\n spearman_path = spearmanr(word_sim_df.loc[:, 'Human (mean)'].values, word_sim_df.loc[:, 'path_similarity'].values)[0]\n pearson_path = pearsonr(word_sim_df.loc[:, 'Human (mean)'].values, word_sim_df.loc[:, 'path_similarity'].values)[0]\n spearman_lch = spearmanr(word_sim_df.loc[:, 'Human (mean)'].values, word_sim_df.loc[:, 'lch_similarity'].values)[0]\n pearson_lch = pearsonr(word_sim_df.loc[:, 'Human (mean)'].values, word_sim_df.loc[:, 'lch_similarity'].values)[0]\n \n print(f'Wu & Palmer Similarity Pearson Correlation Coefficient: {pearson_wup}')\n print(f'Wu & Palmer Similarity Spearman Correlation Coefficient: {spearman_wup}')\n print(f'Path Similarity Pearson Correlation Coefficient: {pearson_path}')\n print(f'Path Similarity Spearman Correlation Coefficient: {spearman_path}')\n print(f'Leakcock & Chodorow Similarity Pearson Correlation Coefficient: {pearson_lch}')\n print(f'Leakcock & Chodorow Similarity Spearman Correlation Coefficient: {spearman_lch}')\n print('\\n')","sub_path":"parte-2/esercizio-1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"264759485","text":"# Project Euler #9: Special Pythagorean triplet\n#!/bin/python3\n\nimport sys\nimport math\n\ndef pythagoras(a,b,c):\n if a**2 + b**2 == c**2:\n return True\n else:\n return False\n\n\nt = int(input().strip())\nfor a0 in range(t):\n n = int(input().strip())\n max_prod = -1\n for a in range(1,math.floor(n/2)):\n b = int(((n*n) - (2*n*a)) / ((2*n) - (2*a)))\n c = n-a-b\n if max_prod < a*b*c and a < b and b < c and a < c and pythagoras(a,b,c):\n max_prod = a*b*c\n print(max_prod)\n","sub_path":"Project Euler/Pr_9/Code.py","file_name":"Code.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"653202025","text":"import sqlite3\r\nimport pandas as pd\r\nimport time\r\nimport datetime\r\n\"\"\"\r\ncon = sqlite3.connect(\"c:/Users/김세윤/sample_32/report.db\") #중구난방인 투자의견을 5가지로 통일\r\ndf = pd.read_sql('select * from \"report\"', con)\r\ndf['comment'] = df['comment'].replace(['적극매수', '강력매수', 'Strong Buy', 'STRONGBUY', 'STRONG BUY'], 'StrongBuy')\r\ndf['comment'] = df['comment'].replace(['비중확대', '매수', 'buy', 'Outperform', 'OVERWEIGHT', 'OUTPERFORM', 'OUTPER', 'OURPERFORM', 'Buy', 'BUY'], 'Buy')\r\ndf['comment'] = df['comment'].replace(['장기매수', 'Trading Buy', 'TRADINGBUY', 'TRADING BUY'], 'TradingBuy')\r\ndf['comment'] = df['comment'].replace(['축소', '중립', '주의', '시장평균', '시장수익률', '비중축소', '보유', '매도', 'underperform', 'neutral', 'marketperform', 'UNDERPERFORM', 'UNDERPER', 'Sell', 'SUSPENDED', 'SELL', 'Reduce', 'REDUCE', 'Neutral', 'NEUTRAL', 'MKTUNDERPERF', 'MKTPERFORM', 'MKTPERF', 'MKTPER', 'MARKET PERFORM', 'Hold', 'HOLD', 'MARKETPERFORM', 'UNDERWEIGHT', 'mktper', '적극매도'], 'Hold')\r\ndf['comment'] = df['comment'].replace(['nr', 'Not Rated', '-', None], 'Not Rated')\r\n\r\ndef to_datetime(str) :\r\n return datetime.datetime.strptime(str, '%Y%m%d')\r\n\r\ndf['date'] = df['date'].astype(str).apply(to_datetime)\r\n\r\n\r\ncon = sqlite3.connect(\"c:/Users/김세윤/sample_32/stock.db\")\r\nweekday = pd.read_sql('select \"index\" from \"005930\"', con) # 평일만 모두 긁어온다 (상장한지 오래된 삼성전자 기준)\r\nweekday = weekday['index'].astype(str).apply(to_datetime).tolist()\r\n\r\nholiday_report_index = []\r\n\r\n\r\ndef last_weekday(date) :\r\n date = date-datetime.timedelta(days=1)\r\n if date not in weekday :\r\n date = date - datetime.timedelta(days=1)\r\n if date not in weekday:\r\n date = date - datetime.timedelta(days=1)\r\n if date not in weekday:\r\n date = date - datetime.timedelta(days=1)\r\n if date not in weekday:\r\n date = date - datetime.timedelta(days=1)\r\n if date not in weekday:\r\n date = date - datetime.timedelta(days=1)\r\n if date not in weekday:\r\n date = date - datetime.timedelta(days=1)\r\n if date not in weekday:\r\n date = date - datetime.timedelta(days=1)\r\n if date not in weekday:\r\n date = date - datetime.timedelta(days=1)\r\n if date not in weekday:\r\n date = date - datetime.timedelta(days=1)\r\n\r\n return date\r\n\r\nfor i in range(len(df)) :\r\n date = df['date'].ix[i]\r\n if date not in weekday :\r\n holiday_report_index.append(date)\r\n df['date'].ix[i] = last_weekday(date)\r\n print(date,\"에서\",df['date'].ix[i],\"로\")\r\n\r\nprint(holiday_report_index)\r\n\r\ndef datetime_to_int(date) :\r\n date = date.strftime('%Y%m%d')\r\n return date\r\n\r\ndf['date'] = df['date'].apply(datetime_to_int).astype(int)\r\n\r\ndf.to_sql('report', con, if_exists='replace', index=False)\r\n\r\na = [] #빠진것 없나 체크\r\nfor i in list(df['comment']) :\r\n if i in a :\r\n continue\r\n else :\r\n a.append(i)\r\nprint(a)\r\n\r\n\"\"\"\r\n\r\n##############################################################################################\r\n\r\ncon = sqlite3.connect(\"c:/Users/김세윤/sample_32/stock.db\")\r\ncur = con.cursor()\r\ncur.execute('select name from sqlite_master where type=\"table\"')\r\n\r\ntable_list = cur.fetchall()\r\ncode_list = []\r\n\r\nfor i in table_list[:len(table_list)-1] :\r\n code_list.append(i[0])\r\n\r\nprint(code_list) # 데이터베이스 속 전 종목의 코드리스트\r\nprint(len(code_list))\r\n\r\n\r\n\"\"\"\r\n#cur.execute('CREATE TABLE ab AS SELECT * FROM \"005930\"')\r\n#cur.execute('ALTER TABLE ab ADD TP REAL')\r\n#cur.execute('ALTER TABLE ab ADD Buy INT')\r\n#cur.execute('ALTER TABLE ab ADD Hold INT')\r\n#cur.execute('INSERT INTO ab(TP) SELECT AVG(TP) FROM report WHERE report.date = 20180220 AND report.code = \"005930\"')\r\n\r\ncur.execute('SELECT AVG(report.TP) FROM report, \"005930\" WHERE report.date = \"005930.index\" AND report.code = \"005930\"')\r\ncur.execute('INSERT INTO ab(TP, Buy, Hold) SELECT AVG( TP ) TPAvg, COUNT( case when comment=\"Buy\" THEN 1 END) BuyCount, COUNT( case when comment=\"Hold\" THEN 1 END ) HoldCount FROM report where code=\"005930\" AND group by date')\r\nprint(cur.fetchall())\r\n\r\n\r\nfor i, code in enumerate(code_list) : #칼럼부터 추가 이거필요없음\r\n print(i)\r\n if code == '040300' :\r\n continue\r\n cur.execute('ALTER TABLE \"%s\" ADD TP REAL' % code)\r\n cur.execute('ALTER TABLE \"%s\" ADD num_report INT' % code)\r\n cur.execute('ALTER TABLE \"%s\" ADD StrongBuy INT'%code)\r\n cur.execute('ALTER TABLE \"%s\" ADD Buy INT'%code)\r\n cur.execute('ALTER TABLE \"%s\" ADD TradingBuy INT' % code)\r\n cur.execute('ALTER TABLE \"%s\" ADD Hold INT'%code)\r\n cur.execute('ALTER TABLE \"%s\" ADD Not_Rated INT' % code)\r\n\r\n\r\n\"\"\"\r\n\r\n\r\n\r\nfor i, code in enumerate(code_list) :\r\n print(i)\r\n df_report = pd.read_sql('SELECT date, AVG( TP ) TP, COUNT(*) num_report, COUNT( case when comment=\"StrongBuy\" THEN 1 END) StrongBuy, COUNT( case when comment=\"Buy\" THEN 1 END) Buy, COUNT( case when comment=\"TradingBuy\" THEN 1 END) TradingBuy, COUNT( case when comment=\"Hold\" THEN 1 END ) Hold, COUNT( case when comment=\"Not Rated\" THEN 1 END ) Not_Rated FROM report where code=\"%s\" group by date'%code, con, index_col='date')\r\n df_company = pd.read_sql('SELECT * FROM \"%s\"'%code, con, index_col='index')\r\n df = pd.concat([df_company, df_report], axis=1)\r\n df[['num_report', 'StrongBuy', 'Buy', 'TradingBuy', 'Hold', 'Not_Rated']] = df[['num_report', 'StrongBuy', 'Buy', 'TradingBuy', 'Hold', 'Not_Rated']].fillna(0) #결측치 처리\r\n #df[['open', 'high', 'low', 'close', 'volume', 'trading_value','market_cap', 'individual', 'foreigner', 'institution', 'pension','num_report', 'StrongBuy', 'Buy', 'TradingBuy', 'Hold', 'Not_Rated']] = df[['open', 'high', 'low', 'close', 'volume', 'trading_value','market_cap', 'individual', 'foreigner', 'institution', 'pension','num_report', 'StrongBuy', 'Buy', 'TradingBuy', 'Hold', 'Not_Rated']].astype(int)\r\n df[['num_report', 'StrongBuy', 'Buy', 'TradingBuy', 'Hold', 'Not_Rated']] = df[['num_report', 'StrongBuy', 'Buy', 'TradingBuy', 'Hold', 'Not_Rated']].astype(int)\r\n df.to_sql(code, con, if_exists='replace')\r\n\r\n #con.commit()\r\n\r\n\r\n","sub_path":"8. 알고리즘 투자/merge_price&report.py","file_name":"merge_price&report.py","file_ext":"py","file_size_in_byte":6623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"313445181","text":"def overlappingIntervals(intervals):\n count=0\n i=0\n while iintervals[i+1][0]:\n count=count+1\n intervals.pop(i+1)\n i=i\n else:\n i=i+1\n return count\n\n\n\nintervals=[[1,2],[2,3],[3,4],[1,3]]\nprint(overlappingIntervals(intervals))","sub_path":"leetcodePractice/mediumProblems/overlappingIntervals.py","file_name":"overlappingIntervals.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"599198550","text":"###############################################################################\n# README:\n# CMPUT275 Assignment 1 Part 1 Section Tues/Thurs\n#\n# Tamara Micevic - 1458744\n# Donald Nguyen - 1473433\n#\n# No Arduino required for the first part of this assignment.\n# Use of stdin and stdout in effect.\n# works with check_server, opentestcenter version keeps giving errors\n#\n###############################################################################\n\nimport sys\nimport csv\nfrom adjacencygraph import AdjacencyGraph\nimport math\nfrom math import hypot\n#Variable infomation:\n# cords = dict: [ Latatude, Longatude ]\n# cost = dict: dict: [ Distance, Name ]\n\n\n\n\n \ndef read_graph(filename):\n lines = []\n\n with open(filename) as f: # f = open('some.csv')\n reader = csv.reader(f)\n\n for row in reader: # reads a line, or \"row\"\n lines.append(row) # list of strings\n\n f.close()\n #########################################################\n global graph\n global coordinate\n global cost\n global tempCords\n graph = AdjacencyGraph()\n coordinate = dict()\n cost = dict()\n tempCords = []\n for i in range(len(lines)):\n if lines[i][0] =='V':\n #Add Vertex\n graph.add_vertex(int(lines[i][1]))\n coordinate[int(lines[i][1])] = list()\n coordinate[int(lines[i][1])].append(int(round(float(lines[i][2])*100000)))\n coordinate[int(lines[i][1])].append(int(round(float(lines[i][3])*100000)))\n\n tempCords.append([int(lines[i][1]) , int(round(float(lines[i][2])*100000)) ,int(round(float(lines[i][3])*100000))])\n elif lines[i][0] == 'E':\n #Add edge\n graph.add_edge((int(lines[i][1]),int((lines[i][2]))))\n #Create cost dsict in dict, in format:\n # cost[source[destination]] = distance as in degrees\n cost[(int(lines[i][1]))] = dict()\n cost[(int(lines[i][1]))][int(lines[i][2])] = [cost_distance_node(int(lines[i][1]),int(lines[i][2])),(lines[i][3])]\n return [graph,coordinate,cost]\n\ndef find_closest(lat,lon):\n y = []\n\n for i in range(len(tempCords)):\n\n hpot = (int(math.hypot(lat-tempCords[i][1],lon-tempCords[i][2])))\n y.append([hpot,tempCords[i][0]])\n\n return (min(y)[1])\n\ndef cost_distance_node(a,b):\n #Manhattan Distance\n x = (coordinate[a][0] - coordinate[b][0])**2\n y = (coordinate[a][1] - coordinate[b][1])**2\n\n return (abs(x)+abs(y))**0.5\n\n#Recreating the path to display\ndef createpath(start, end, parent):\n\n current = end\n path = [end]\n\n # run until the end vertex is reached\n while current != start:\n path.append(parent[current])\n current = parent[current]\n\n # path was appended backwards\n path.reverse()\n\n return path\n\ndef least_cost_path(graph,a,b,cost):\n\n # lowest cost from the start a to current vertex v\n min_cost = {}\n min_cost[a] = 0\n\n parent = {}\n # set of vertices that need to be processed in the path\n path_vertices = {a}\n\n while path_vertices:\n # getting the vertex with the min cost\n current = min(path_vertices, key = lambda x: min_cost[x])\n\n # if we reached the end, recreate the path\n if current == b:\n return createpath(a, b, parent)\n\n path_vertices.remove(current)\n\n for neighbour in graph.neighbours(current):\n\n # if not in min_cost, haven't been processed yet\n # therefore add to the vertices that have been processed,\n # calcuate its cost and determine its parent\n if neighbour not in min_cost:\n path_vertices.add(neighbour)\n min_cost[neighbour] = min_cost[current] + cost(current, neighbour)\n parent[neighbour] = current\n\n # checking for the minimum cost of the path, if the cost is smaller\n # than the previous cost, replace it as the minimum\n elif min_cost[neighbour] > min_cost[current] + cost(current, neighbour):\n min_cost[neighbour] = min_cost[current] + cost(current, neighbour)\n parent[neighbour] = current\n\n return []\n\n\ndef testCentre():\n for line in sys.stdin:\n x = line.split()\n if x[0] == 'R':\n break\n\n\n start_lat = int(x[1])\n start_lon = int(x[2])\n end_lat = int(x[3])\n end_lon = int(x[4])\n\n start = find_closest(start_lat,start_lon)\n end = find_closest(end_lat,end_lon)\n\n x = least_cost_path(graph,start,end,cost_distance_node)\n #print(x)\n\n\n print('N ',len(x))\n for i in range(len(x)):\n sys.stdout.write('W ' + str(coordinate[x[i]][0]) + ' ' + str(coordinate[x[i]][1]) + '\\n')\n pass\n\ndef main():\n [graph,coordinate,cost]=read_graph(\"edmonton-roads-2.0.1.txt\")\n testCentre()\n\nmain()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"459043227","text":"import os\nimport pickle\nimport numpy as np\nimport pandas as pd\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.neural_network import MLPRegressor\nfrom sklearn import linear_model\nimport seaborn as sns\nimport pyrebase\nfrom flask import Flask,render_template,request\n\n\napp = Flask(__name__)\n\n\npredicted_meds=[]\n\n# Firebase storage initialization.\nidentifier = { \"apiKey\": \"AIzaSyBq-IIrvPQj9Q5GThKRoDYp1w3m15hhHsI\",\n \"authDomain\": \"tarp-919f0.firebaseapp.com\",\n \"databaseURL\": \"https://tarp-919f0.firebaseio.com\",\n \"projectId\": \"tarp-919f0\",\n \"storageBucket\": \"tarp-919f0.appspot.com\",\n \"messagingSenderId\": \"1036193468546\",\n \"appId\": \"1:1036193468546:web:70b3d8064e51ddb99a649b\",\n \"measurementId\": \"G-92Y7B1QYX9\"\n }\n\nfirebase = pyrebase.initialize_app(identifier)\nstorage = firebase.storage()\n\n\n@app.route('/')\ndef hello_world():\n return render_template('index.html')\n\n\n@app.route('/symptom',methods = ['POST', 'GET'])\ndef symptom_handle():\n \n if request.method == 'POST': \n result=request.form\n s1,s2,s3,s4,s5 = result['s1'],result['s2'],result['s3'],result['s4'],result['s5']\n \n #creating TFIDF of input symptom\n target_symptom=[[s1+' '+s2+' '+s3+' '+s4+' '+s5]]\n test_instance=pd.DataFrame(target_symptom,columns=['Mixed'])\n \n storage.child(\"Models/TFIDF.pkl\").download('.//Models//TFIDF.pkl')\n vectorizer = pickle.load(open('.//Models//TFIDF.pkl','rb'))\n \n X=vectorizer.transform(test_instance['Mixed'])\n\n storage.child(\"Models/knn.pkl\").download('.//Models//knn.pkl')\n neigh = pickle.load(open('.//Models//knn.pkl','rb'))\n \n test_instance = pd.DataFrame.sparse.from_spmatrix(X)\n inp=test_instance.iloc[0,:]\n distances,indices = neigh.kneighbors([inp])\n \n #getting the predicted meds \n\n storage.child(\"Models/meds.pkl\").download('.//Models//meds.pkl')\n medlist=pickle.load(open('.//Models//meds.pkl','rb'))\n\n for i in indices.ravel():\n predicted_meds.append(medlist[i])\n\n filename='.//Models//predmed.pkl' \n pickle.dump(predicted_meds, open(filename, 'wb'))\n storage.child(\"Models/predmed.pkl\").put(filename)\n return render_template('categories.html',result=predicted_meds)\n\n\n@app.route('/inventory',methods = ['POST', 'GET'])\ndef inventory_model():\n\n storage.child(\"Models/multi_regr.pkl\").download('.//Models//multi_regr.pkl')\n regr = pickle.load(open('.//Models//multi_regr.pkl','rb'))\n\n storage.child(\"PartDatasets/df_inventory.csv\").download('.//Datasets//df_inventory.csv')\n df5 = pd.read_csv('.//Datasets//df_inventory.csv') \n \n if request.method=='POST':\n result = request.form\n med,weight = result['med'],result['weight']\n \n #extracting suggest count from dataset\n l1=[]\n for i in range(len(df5['Item Description'])):\n if(df5['Item Description'][i]==med):\n l1.append(df5['Suggest count'][i])\n suggest_count=round(sum(l1)/len(l1)) if len(l1)>0 else 0\n \n #predicting line item quantity\n x_pred=[[float(weight),float(suggest_count)]]\n y_pred=regr.predict(x_pred)\n result=[med,round(y_pred[0]),1]\n return render_template('inventory.html',result=result)\n else:\n \n # Making X_test for our model.\n l1 = []\n l2 = []\n l3 = []\n for i in range(len(df5['Item Description'])):\n if(df5['Item Description'][i]==predicted_meds[0] or df5['Item Description'][i]==predicted_meds[1] or df5['Item Description'][i]==predicted_meds[2]):\n l1.append(df5.iloc[i,:]['Weight (Kilograms)'])\n l2.append(df5.iloc[i,:]['Suggest count'])\n l3.append(df5.iloc[i,:]['Item Description']) \n X_test = pd.DataFrame()\n X_test['meds']=l3\n X_test['Weight (Kilograms)'] = l1\n X_test['Suggest count'] = l2\n \n #predicting line item quantity using multiple regression\n y_pred = regr.predict(X_test.iloc[:,1:])\n \n #appending line item quantity to X_test\n X_test['Line Item Quantity']=list(y_pred)\n \n #finding mean line item quantity for each predicted med\n pred_med1=[]\n pred_med2=[]\n pred_med3=[]\n for i in range(len(X_test['meds'])):\n if(X_test['meds'][i]==predicted_meds[0]):\n pred_med1.append(X_test.iloc[i,:]['Line Item Quantity'])\n if(X_test['meds'][i]==predicted_meds[1]):\n pred_med2.append(X_test.iloc[i,:]['Line Item Quantity'])\n if(X_test['meds'][i]==predicted_meds[2]):\n pred_med3.append(X_test.iloc[i,:]['Line Item Quantity'])\n line_item_quantity=[round(sum(pred_med1)/len(pred_med1)) if len(pred_med1)>0 else 0,round(sum(pred_med2)/len(pred_med2)) if len(pred_med2)>0 else 0,round(sum(pred_med3)/len(pred_med3)) if len(pred_med3)>0 else 0]\n result=[predicted_meds,line_item_quantity,0]\n return render_template('inventory.html',result=result)\n\n\n@app.route('/demand',methods = ['POST', 'GET'])\ndef demand_model():\n if request.method=='POST':\n result=request.form\n attr=result['options']\n\n os.system('python C:\\\\Users\\\\YASH\\\\Documents\\\\GitHub\\\\Blueronic\\\\Scripts\\\\demand.py')\n\n storage.child(\"Models/error.pkl\").download('.//Models//error.pkl')\n message=pickle.load(open('.//Models//error.pkl','rb'))\n \n if message=='Model Success':\n result=attr\n else:\n result=message\n return render_template('demand.html',result=result)\n else:\n return render_template('demand.html')\n\n\n@app.route('/production',methods = ['POST', 'GET'])\ndef production_model():\n\n storage.child(\"Models/random_forest.pkl\").download('.//Models//random_forest.pkl')\n model = pickle.load(open('.//Models//random_forest.pkl','rb'))\n\n storage.child(\"Models/vendor_coder.pkl\").download('.//Models//vendor_coder.pkl')\n le = pickle.load(open('.//Models//vendor_coder.pkl','rb'))\n \n if request.method==\"GET\":\n\n storage.child(\"PartDatasets/df_demand.csv\").download('.//Datasets//df_demand.csv')\n X=pd.read_csv('.//Datasets//df_demand.csv')\n \n # Making X_test for our model. \n l1 = []\n l2 = []\n l3 = []\n l4 = []\n for i in range(len(X['meds'])):\n if(X['meds'][i]==predicted_meds[0] or X['meds'][i]==predicted_meds[1] or X['meds'][i]==predicted_meds[2]):\n l1.append(X.iloc[i,:]['Line Item Quantity'])\n l2.append(X.iloc[i,:]['Freight Cost (USD)'])\n l3.append(X.iloc[i,:]['Vendor'])\n l4.append(X.iloc[i,:]['meds']) \n X_test = pd.DataFrame()\n X_test['Line Item Quantity'] = l1\n X_test['Freight Cost (USD)'] = l2\n X_test['Vendor'] = l3\n \n #predicting the delivery time using random forest\n y_pred = model.predict(X_test)\n \n #reverse encoding the vendors\n vendors = list(le.inverse_transform(X_test['Vendor']))\n \n # Making our final output dataframe. (Sorted in ascending order of delivery time in days)\n df_vendor = pd.DataFrame(columns = ['Vendor', 'Days', 'Medication'])\n df_vendor['Vendor'] = vendors\n df_vendor['Days'] = list(y_pred)\n df_vendor['Medication'] = l4\n df_vendor.sort_values('Days', inplace = True)\n df_vendor.reset_index(inplace = True)\n df_vendor.drop(columns=['index'], axis = 1, inplace = True)\n sns_plot = sns.catplot(x=\"Medication\", y=\"Days\", hue=\"Vendor\", kind=\"bar\", data=df_vendor)\n sns_plot.savefig('.//static//production.png')\n \n results=[0,0]\n return render_template('production.html',result=results)\n else:\n result=request.form\n line_item_quant,freight_cost,vendor = result['quant'],result['freight'],result['vendor']\n vendor_coded=le.transform([vendor])\n test_instance=[line_item_quant,freight_cost,vendor_coded]\n df_test=pd.DataFrame([test_instance],columns=['Line Item Quantity','Freight Cost (USD)','Vendor'])\n \n #predicting delivery time\n y_pred=model.predict(df_test)\n results=[1,y_pred[0]]\n return render_template('production.html',result=results)\n\n\n@app.route('/supply',methods = ['POST', 'GET'])\ndef supply_model():\n\n storage.child(\"PartDatasets/df_supply.csv\").download('.//Datasets//df_supply.csv')\n df5=pd.read_csv('.//Datasets//df_supply.csv')\n \n # Making an input dataframe X according to predicted meds.\n l1 = []\n l2 = []\n l3 = []\n l4 = []\n l5 = []\n\n for i in range(len(df5['Item Description'])):\n if(df5['Item Description'][i]==predicted_meds[0] or df5['Item Description'][i]==predicted_meds[1] or df5['Item Description'][i]==predicted_meds[2]):\n l1.append(df5.iloc[i,:]['Shipment Mode'])\n l2.append(df5.iloc[i,:]['Vendor'])\n l3.append(df5.iloc[i,:]['Freight Cost (USD)'])\n l4.append(df5.iloc[i,:]['Shipment Cost'])\n l5.append(df5.iloc[i,:]['db_cluster'])\n \n X_test = pd.DataFrame()\n X_test['Shipment Mode'] = l1\n X_test['Vendor'] = l2\n X_test['Freight Cost (USD)'] = l3\n X_test['Shipment Cost'] = l4\n X_test['db_cluster'] = l5\n \n # Make the predictions for supply score.\n storage.child(\"Models/neural_regr.pkl\").download('.//Models//neural_regr.pkl')\n regr = pickle.load(open('.//Models//neural_regr.pkl','rb')) \n neural_pred = []\n for i in range(X_test.shape[0]):\n neural_res = regr.predict([X_test.iloc[i,:]])\n neural_pred.append(neural_res.tolist()[0])\n \n # Inverse transform and print the best supplier.\n storage.child(\"Models/vendor_label.pkl\").download('.//Models//vendor_label.pkl')\n le1 = pickle.load(open('.//Models//vendor_label.pkl','rb'))\n \n best_vendor_index = neural_pred.index(min(neural_pred))\n best_vendor=le1.inverse_transform(X_test['Vendor'].astype(int)).tolist()[best_vendor_index]\n supply_score=min(neural_pred)\n result=[best_vendor,supply_score]\n return render_template('supply.html',result=result)\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"Blueronic/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":10237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"580024262","text":"# Copyright 2015 Canonical Ltd\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\nimport hashlib\nimport os\nimport tarfile\nimport uuid\n\nfrom nova import exception\nfrom nova import i18n\nfrom nova import image\nfrom oslo_config import cfg\nfrom oslo_log import log as logging\nfrom oslo_utils import fileutils\nfrom pylxd import api\nfrom pylxd import exceptions as lxd_exceptions\n\nfrom nclxd.nova.virt.lxd import container_utils\nfrom nclxd.nova.virt.lxd import container_client\n\n_ = i18n._\n\nCONF = cfg.CONF\nLOG = logging.getLogger(__name__)\nIMAGE_API = image.API()\n\nclass LXDContainerImage(object):\n def __init__(self):\n self.container_client = container_client.LXDContainerClient()\n self.container_dir = container_utils.LXDContainerDirectories()\n\n def setup_image(self, context, instance, image_meta, host=None):\n LOG.debug('Fetching image info from glance')\n\n if self.container_client.client('alias_defined',\n instance=instance.image_ref,\n host=host):\n return\n\n lxd_image = self._get_lxd_image(image_meta)\n if lxd_image is not None:\n return\n\n base_dir = self.container_dir.get_base_dir()\n if not os.path.exists(base_dir):\n fileutils.ensure_tree(base_dir)\n\n container_rootfs_img = (\n self.container_dir.get_container_rootfs_image(\n image_meta))\n IMAGE_API.download(context, instance.image_ref, dest_path=container_rootfs_img)\n lxd_image_manifest = self._get_lxd_manifest(image_meta)\n if lxd_image_manifest is not None:\n container_manifest_img = (\n self.container_dir.get_container_manifest_image(\n image_meta))\n IMAGE_API.download(context, lxd_image_manifest,\n dest_path=container_manifest_img)\n img_info = self._image_upload((container_manifest_img, container_rootfs_img),\n container_manifest_img.split('/')[-1])\n else:\n img_info = self._image_upload(container_rootfs_img,\n container_rootfs_img.split(\"/\")[-1])\n\n self._setup_alias(instance, img_info, image_meta, context)\n\n def _get_lxd_image(self, image_meta):\n return image_meta['properties'].get('lxd-image-alias', None)\n\n def _get_lxd_manifest(self, image_meta):\n return image_meta['properties'].get('lxd-manifest', None)\n\n def _image_upload(self, path, filename):\n LOG.debug('Uploading Image to LXD.')\n lxd = api.API()\n headers = {}\n\n if isinstance(path, str):\n headers['Content-Type'] = \"application/octet-stream\"\n try:\n status, data = lxd.image_upload(data=open(path, 'rb'),\n headers=headers)\n except lxd_exceptions as ex:\n raise exception.ImageUnacceptable(\n image_id=instance.image_ref,\n reason=_('Failed to upload image: %s' % ex))\n else:\n meta_path, rootfs_path = path\n boundary = str(uuid.uuid1())\n\n form = []\n for name, path in [(\"metadata\", meta_path),\n (\"rootfs\", rootfs_path)]:\n filename = os.path.basename(path)\n form.append(\"--%s\" % boundary)\n form.append(\"Content-Disposition: form-data; \"\n \"name=%s; filename=%s\" % (name, filename))\n form.append(\"Content-Type: application/octet-stream\")\n form.append(\"\")\n with open(path, \"rb\") as fd:\n form.append(fd.read())\n\n form.append(\"--%s--\" % boundary)\n form.append(\"\")\n\n body = b\"\"\n for entry in form:\n if isinstance(entry, bytes):\n body += entry + b\"\\r\\n\"\n else:\n body += entry.encode() + b\"\\r\\n\"\n\n headers['Content-Type'] = \"multipart/form-data; boundary=%s\" \\\n % boundary\n\n try:\n status, data = lxd.image_upload(data=body,\n headers=headers)\n except lxd_exceptions as ex:\n raise exception.ImageUnacceptable(\n image_id=instance.image_ref,\n reason=_('Failed to upload image: %s' % ex))\n\n return data\n\n def _setup_alias(self, instance, img_info, image_meta, context):\n LOG.debug('Updating image and metadata')\n\n lxd = api.API()\n try:\n alias_config = {\n 'name': instance.image_ref,\n 'target': img_info['metadata']['fingerprint']\n }\n LOG.debug('Creating alias: %s' % alias_config)\n lxd.alias_create(alias_config)\n except lxd_exceptions.APIError as ex:\n raise exception.ImageUnacceptable(\n image_id=instance.image_ref,\n reason=_('Image already exists: %s' % ex))\n\n image_meta = {\n 'properties': {\n 'lxd-image-alias': instance.image_ref,\n 'lxd-manifest': self._get_lxd_manifest(image_meta)\n }\n }\n\n IMAGE_API.update(context,\n instance.image_ref,\n image_meta)","sub_path":"nclxd/nova/virt/lxd/container_image.py","file_name":"container_image.py","file_ext":"py","file_size_in_byte":5977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"320517830","text":"# 罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。\n# 字符 数值\n# I 1\n# V 5\n# X 10\n# L 50\n# C 100\n# D 500\n# M 1000\n# 例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。\n# 27 写做 XXVII, 即为 XX + V + II 。\n# 通常情况下,罗马数字中小的数字在大的数字的右边。\n# 但也存在特例,例如 4 不写做 IIII,而是 IV。\n# 数字 1 在数字 5 的左边,所表���的数等于大数 5 减小数 1 得到的数值 4 。\n# 同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况:\n# I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。\n# X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。\n# C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。\n# 给定一个罗马数字,将其转换成整数。输入确保在 1 到 3999 的范围内。\nclass Solution:\n def romanToInt(self, s):\n m = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}\n ans = 0\n N = len(s)\n for i in range(N):\n if i < N - 1 and m[s[i]] < m[s[i + 1]]:\n ans -= m[s[i]]\n else:\n ans += m[s[i]]\n return ans\n","sub_path":"LeetCodePython/No013.py","file_name":"No013.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"337032544","text":"#!/usr/local/bin/python3\n\nimport smtplib\nimport ssl\nfrom email.header import Header\nfrom email.utils import formataddr\nfrom email.message import EmailMessage\nimport securer_templates\nimport smtp_details_templates\n\nsmtp_server = securer_templates.smtp_server['link']\ntemplate = smtp_details_templates.tmpl1\ndef SendMessage(text_to_send, email, texttype):\n refused = {}\n recepients_emails = email\n sender_name = template['sender_name']\n sender_address = template['sender_address']\n subject = template['subject']\n\n msg = EmailMessage()\n msg.set_content(text_to_send, subtype=texttype)\n msg['Subject'] = subject\n msg['From'] = formataddr((sender_name, sender_address))\n msg['To'] = \", \".join(recepients_emails)\n\n try:\n server = smtplib.SMTP(smtp_server, 25)\n try:\n server.send_message(msg)\n finally:\n server.quit()\n print ('email sent')\n except smtplib.SMTPRecipientsRefused as e:\n refused = e.recipients\n print ('error sending mail')\n except smtplib.SMTPException as e:\n print ('got', e.__class__)\n errcode = getattr(e, 'smtp_code', -1)\n errmsg = getattr(e, 'smtp_error', 'ignore')\n for r in rcpttos:\n refused[r] = (errcode, errmsg)\n","sub_path":"cgi-bin/smtp_sender.py","file_name":"smtp_sender.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"35585288","text":"# -*- coding:utf-8 -*-\n\n\"\"\"\n@author fuweiyi\n@time 2020/6/11\n\"\"\"\nfrom source.async_model import AsyncModelBase\n\n\nclass Model(AsyncModelBase):\n\n tbl_shop = 'tbl_sm_shop'\n tbl_shop_admin = 'tbl_sm_shop_admin'\n\n async def query_one(self, params):\n \"\"\"\n 查询店铺信息(单条)\n @param params:\n @return:\n \"\"\"\n fields = []\n condition = '1 = 1'\n values = []\n\n #\n if not self.util.is_empty('shop_id', params):\n condition += ' and shop_id = %s'\n values.append(params['shop_id'])\n\n result = await self.find(self.tbl_shop, {\n self.sql_constants.FIELDS: fields,\n self.sql_constants.CONDITION: condition\n }, tuple(values))\n return result\n\n async def create(self, params):\n \"\"\"\n 创建店铺\n 同时会创建超管和管理员分组数据\n @param params:\n @return:\n \"\"\"\n sql_list = []\n # 创建店铺\n key = 'shop_id, shop_name, logo_url, admin_id, create_time'\n val = '%s, %s, %s, %s, %s'\n value = (\n params['shop_id'],\n params['shop_name'],\n params['logo_url'],\n params['admin_id'],\n params['create_time'],\n )\n #\n sql_list.append({\n self.sql_constants.SQL_TYPE: self.sql_constants.INSERT,\n self.sql_constants.TABLE_NAME: self.tbl_shop,\n self.sql_constants.DICT_DATA: {\n self.sql_constants.KEY: key,\n self.sql_constants.VAL: val\n },\n self.sql_constants.VALUE_TUPLE: value\n })\n # 创建管理员\n key = 'shop_id, admin_id, group_id, create_time'\n\n result = await self.do_sqls(sql_list)\n return result\n","sub_path":"src/module/v1/shop/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"538486749","text":"# -*- coding: utf-8 -*-\r\n# @Time : 2020/11/18\r\n# @Author : J\r\n# @File : Practise-1.py\r\n# @Software: PyCharm\r\n\r\n\r\nimport numpy as np\r\nimport cv2\r\n\r\n\r\nimg = cv2.imread(\"../adaptive.jpg\")\r\ngrayscaled = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\r\nretval,threshold = cv2.threshold(grayscaled,10,255,cv2.THRESH_BINARY)\r\nTH = cv2.adaptiveThreshold(grayscaled,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,115,1)\r\ncv2.imshow(\"orginal\",img)\r\ncv2.imshow(\"threshold\",TH)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"OpenCV/tips/adaptive.py","file_name":"adaptive.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"604239093","text":"#-*- coding: utf-8 -*-\r\n#by forever1296\r\n#패키지 import\r\nimport requests\r\nfrom datetime import datetime\r\nfrom bs4 import BeautifulSoup\r\nimport pymysql.cursors\r\n#오늘 날짜\r\nnow_all = datetime.now()\r\nnow_want = now_all.strftime('%Y%m%d')\r\n\r\n#https://sports.news.naver.com/wfootball/record/ajaxHtmlPlayerRecord.nhn?year=2019&month=12&category=epl&date=20191201\r\n\r\n # 해당 url에서 html을 불러옴.\r\nurl = requests.get('https://sports.news.naver.com/wfootball/record/ajaxHtmlPlayerRecord.nhn?year=2019&month=12&category=ligue1&date=20191201')\r\nurlt = requests.get('https://sports.news.naver.com/wfootball/record/index.nhn?category=ligue1&tab=team')\r\nurlc = url.content\r\nurlct = urlt.content\r\nhtml = str(BeautifulSoup(urlc, \"html.parser\"))\r\nhtmlt = str(BeautifulSoup(urlct, \"html.parser\"))\r\n#datat = str(htmlt.find_all(\"script\", {\"type\": \"text/javascript\"}))\r\nrep1 = html.replace(':','')\r\nrep2 = rep1.replace(',','')\r\nrep1t = htmlt.replace(':','')\r\nrep2t = rep1t.replace(',','')\r\n\r\nsdata = rep2.split('\"')\r\nsdatat = rep2t.split('\"')\r\n#print(sdatat)\r\n\r\nrdata = list()\r\nrdatat = list()\r\nsdatatsp = list()\r\ni=0\r\nj=1\r\n\r\nconn = pymysql.connect(host='localhost',\r\n user='root',\r\n password='root',\r\n db='Sports',\r\n charset='utf8')\r\n\r\nwhile i < len(sdata):\r\n if sdata[i] == 'playerName':\r\n rdata.append(str(j)+'위')\r\n rdata.append(str(sdata[i+2]))\r\n j=j+1\r\n elif sdata[i] =='teamName':\r\n rdata.append(str(sdata[i+2]))\r\n elif sdata[i] == 'goals':\r\n rdata.append(str(sdata[i+3]))\r\n elif sdata[i] == 'assist':\r\n rdata.append(str(sdata[i + 1]))\r\n elif sdata[i] == 'attackPoint':\r\n rdata.append(str(sdata[i+3]))\r\n elif sdata[i] == 'shot':\r\n rdata.append(str(sdata[i+1]))\r\n elif sdata[i] == 'foul':\r\n rdata.append(str(sdata[i + 1]))\r\n elif sdata[i] == 'booking':\r\n rdata.append(str(sdata[i + 1]))\r\n elif sdata[i] == 'dismissal':\r\n rdata.append(str(sdata[i + 1]))\r\n elif sdata[i] == 'cornerKicks':\r\n rdata.append(str(sdata[i + 1]))\r\n elif sdata[i] == 'penaltyKicks':\r\n rdata.append(str(sdata[i + 1]))\r\n elif sdata[i] == 'offside':\r\n rdata.append(str(sdata[i + 1]))\r\n elif sdata[i] == 'onTargetShot':\r\n rdata.append(str(sdata[i + 1]))\r\n elif sdata[i] == 'gameCount':\r\n rdata.append(str(sdata[i + 1]))\r\n i=i+1\r\n\r\nu=0\r\nk=0\r\nwhile u= -5.) & (x <= 5.)), 1., 0.)\n\n\ndef increaseRes(function, x_min=-10, x_max=10, n=100, m=100):\n\n x_s = np.linspace(x_min, x_max, n) # sampling points\n signal = function(x_s) # signal\n fft = np.fft.fft(signal) # fft\n fft_shift = np.fft.fftshift(fft) # fft shift\n fft_shift_pad = np.concatenate((np.zeros(int(m/2)),\n fft_shift,\n np.zeros(int(m/2)))) # fft zero padding\n N2 = n + 2 * int(m/2)\n fft_ishift_pad = np.fft.ifftshift(fft_shift_pad) # inverse fft shift\n ifft_ishift_pad = N2 / N * np.fft.ifft(fft_ishift_pad) # inverse fft\n\n return x_s, \\\n signal, \\\n fft, \\\n fft_shift, \\\n fft_shift_pad, \\\n fft_ishift_pad, \\\n ifft_ishift_pad\n\n\nif __name__ == '__main__':\n\n N = 30 # grid point initial grid\n M = 60 # points to add (should be even)\n x_min = -10\n x_max = 10\n\n for i, func in enumerate([f, g]):\n\n x_s, signal, \\\n fft, fft_shift, \\\n fft_shift_pad, \\\n fft_ishift_pad, \\\n ifft_ishift_pad = increaseRes(func, x_min=-10, x_max=10, n=N, m=M)\n\n fig, axes = plt.subplots(ncols=2, nrows=3, figsize=(15, 10))\n\n # - signal\n ax = axes[0, 0]\n ax.plot(x_s, signal)\n ax.set_title('Original signal', fontsize=14)\n\n # - fft transform\n ax = axes[1, 0]\n ax.plot(np.real(fft), label='real')\n ax.plot(np.imag(fft), label='img')\n ax.plot(np.absolute(fft), label='abs')\n ax.set_title('FFT', fontsize=14)\n ax.legend()\n\n # - shifted fft transform\n ax = axes[2, 0]\n ax.plot(np.real(fft_shift), label='real')\n ax.plot(np.imag(fft_shift), label='img')\n ax.plot(np.absolute(fft_shift), label='abs')\n ax.set_title('Shifted FFT', fontsize=14)\n ax.legend()\n\n # - zero padded shifted fft transform\n ax = axes[2, 1]\n ax.plot(np.real(fft_shift_pad), label='real')\n ax.plot(np.imag(fft_shift_pad), label='img')\n ax.plot(np.absolute(fft_shift_pad), label='abs')\n ax.set_title('Zero padded shifted FFT', fontsize=14)\n ax.legend()\n\n # - ishifted zero padded shifted fft transform\n ax = axes[1, 1]\n ax.plot(np.real(fft_ishift_pad), label='real')\n ax.plot(np.imag(fft_ishift_pad), label='img')\n ax.plot(np.absolute(fft_ishift_pad), label='abs')\n ax.set_title('Inverse shifted zero padded FFT', fontsize=14)\n ax.legend()\n\n # - ishifted zero padded shifted fft transform\n ax = axes[0, 1]\n x_s = np.linspace(x_min, x_max, fft_shift_pad.shape[0])\n ax.plot(x_s, ifft_ishift_pad)\n ax.set_title('Interpolated signal', fontsize=14)\n ax.legend()\n\n plt.savefig('figures/task2_signal%d.png' % (i), transparent=True, bbox_inches='tight', pad_inches=0)\n\n\n\n\n\n","sub_path":"DeepVision/DeepVisions_Solutions/Solution5/solution_ex2.py","file_name":"solution_ex2.py","file_ext":"py","file_size_in_byte":3028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"237826551","text":"from exceptions import CantParseException\n\n\nclass Feed:\n # feed types\n TYPE_RSS1 = 1\n TYPE_RSS2 = 2\n TYPE_ATOM03 = 3\n TYPE_ATOM1 = 4\n TYPE_UNKNOWN = 5\n # feed params\n feed_type = None\n feed = None\n source_tree = None\n items = ()\n namespaces = ()\n\n def guess_rss_type(self):\n if self.source_tree.tag == 'rdf':\n return self.TYPE_RSS1\n elif self.source_tree.tag == 'rss':\n return self.TYPE_RSS2\n elif self.source_tree.tag == 'self':\n if 'version' in self.source_tree.attrib and\\\n self.source_tree.attrib['version'] == '0.3':\n return self.TYPE_ATOM03\n else:\n return self.TYPE_ATOM1\n else:\n return self.TYPE_UNKNOWN\n\n def encode_source_data(self, data):\n return data.encode('utf-8')\n\n def parse_items(self, source_data):\n prepared_items = []\n if self.feed_type == self.TYPE_ATOM1 or self.feed_type == self.TYPE_ATOM03:\n for item in source_tree[0].iter('entry'):\n prepared_items.append(dict(\n title=item.title,\n link=item.link,\n published=item.pubDate,\n category=item.category,\n ))\n elif self.feed_type == self.TYPE_RSS2 or self.feed_type == self.TYPE_RSS1:\n for item in source_tree[0].iter('item'):\n prepared_items.append(dict(\n title=item.title,\n link=item.link,\n published=item.published,\n ))\n else:\n return None\n\n def __init__(self, source_data):\n self.source_tree = etree.fromstring(self.encode_source_data(source_data))\n if self.source_tree:\n self.feed_type = self.guess_rss_type()\n self.items = self.parse_items()\n else:\n raise CantParseException\n","sub_path":"xfrssparser/feed.py","file_name":"feed.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"358222754","text":"import asyncio\nfrom .tsdb_serialization import serialize, LENGTH_FIELD_LENGTH, Deserializer\nfrom .tsdb_ops import *\nfrom .tsdb_error import *\n\nclass TSDBClient(object):\n \"\"\"\n The client. This could be used in a python program, web server, or REPL!\n \"\"\"\n def __init__(self, port=9999):\n self.port = port\n self.deserializer = Deserializer()\n\n def insert_ts(self, primary_key, ts):\n ts_insert = TSDBOp_InsertTS(primary_key, ts)\n self._send(ts_insert.to_json())\n\n def upsert_meta(self, primary_key, metadata_dict):\n ts_update = TSDBOp_UpsertMeta(primary_key, metadata_dict)\n self._send(ts_update.to_json())\n\n def select(self, metadata_dict={},fields=None, additional = None):\n ts_select = TSDBOp_Select(metadata_dict,fields, additional)\n return self._send(ts_select.to_json())\n\n def augmented_select(self, proc, target, arg=None, metadata_dict={}, additional=None):\n ts_augmented_select = TSDBOp_AugmentedSelect(proc, target, arg, metadata_dict, additional)\n return self._send(ts_augmented_select.to_json())\n\n def add_trigger(self, proc, onwhat, target, arg):\n msg = TSDBOp_AddTrigger(proc, onwhat, target, arg)\n return self._send(msg.to_json())\n\n def remove_trigger(self, proc, onwhat):\n msg = TSDBOp_RemoveTrigger(proc, onwhat)\n return self._send(msg.to_json())\n\n # Feel free to change this to be completely synchronous\n # from here onwards. Return the status and the payload\n async def _send_coro(self, msg, loop):\n # Open connection and write the serialized message\n reader, writer = await asyncio.open_connection('', self.port, loop=loop)\n writer.write(serialize(msg))\n await writer.drain()\n # Wait for response\n response = await reader.read()\n writer.close()\n # Deserialize response\n self.deserializer.append(response)\n if self.deserializer.ready():\n deserialized_response = self.deserializer.deserialize()\n status = deserialized_response['status']\n payload = deserialized_response['payload']\n # Print out status and payload\n print('C> status:',str(TSDBStatus(status)))\n print('C> payload:',payload)\n print('-----------')\n print('C> writing')\n\n return status, payload\n\n\n #call `_send` with a well formed message to send.\n #once again replace this function if appropriate\n def _send(self, msg):\n loop = asyncio.get_event_loop()\n coro = asyncio.ensure_future(self._send_coro(msg, loop))\n loop.run_until_complete(coro)\n return coro.result()","sub_path":"tsdb/tsdb_client.py","file_name":"tsdb_client.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"181442877","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.shop, name=\"shop\"),\n path('shoppingcart/', views.shopping_cart, name=\"shopping_cart\"),\n path('checkout/', views.checkout, name=\"checkout\"),\n path('update_item/', views.updateItem, name=\"update_item\"),\n path('process_order/', views.processOrder, name=\"process_order\"),\n path('payment/', views.payment, name=\"payment\"),\n path('paymentSuccess/', views.paymentSuccess, name=\"paymentSuccess\"),\n]\n","sub_path":"shop/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"33709686","text":"import paho.mqtt.client as mqtt #import the client1\nfrom time import sleep \t\t\t #to delay someting\nimport ssl \t\t\t\t\t\t #to decide which TLS version will be used\n\n#--------------------------CALBACKS------------------------------------------\n\n#When CONNACK message receives from broker, on_connect callback will be triggered. The name of the function can be changed.\ndef on_connect(client, userdata, flags, rc):\n print(\"Return code of the EdgeNode's connection request to the MQTT broker is \" + str(rc))\n if (rc==0):\n client.subscribe(\"home\",2) # Topic: home & QoS<=2\n print(flags,userdata,rc)\n else:\n print(\"Connection refused\")\n\n#When a PUBLISH message receives, on_message will be triggered.\ndef on_message(client, userdata, message):\n print(\"Received message '\" + str(message.payload) + \"' on topic '\"\n + message.topic + \"' with QoS \" + str(message.qos))\n global k\n k+=1\n\n#When Subscription Acknowledged receives, on_subscribe will be triggered.\ndef on_subscribe(client, userdata, mid, granted_qos):\n print(userdata,mid,granted_qos) \n\n#---------------------------------------------------------------------------- \nbroker=\"130.149.232.227\" #For doruknet, you need to change IP. This is for DAI-EAP\nclient = mqtt.Client(\"The_Client_Subscribe_2Side\") #Creating a Client object\nclient.on_message=on_message #We are binding the callback on_message(Left-side) with on_message function which we defined (Right-side)\nclient.on_connect=on_connect #Binding on_connect\nclient.on_subscribe=on_subscribe #Binding on_subscribe\nclient.tls_set('','','',tls_version=ssl.PROTOCOL_TLSv1_2)\n#The first three parts is the locations of certificates and key, the last part is the version which we want to use. This part must be before connect().\nclient.connect(host=broker,port=8883) #Host is the hostname or IP address of the remote broker, port can be 1883 if TLS/SSl won't be used\nclient.loop_start() #For more about loops, --http://www.steves-internet-guide.com/loop-python-mqtt-client/\nprint(\"Connecting to broker \"+broker) \nk=0\nwhile k<3: #After 3 messages has been received, loop will stop and the client will disconnect.\n\tsleep(1)\n\tpass\nclient.loop_stop()\nclient.disconnect()\n","sub_path":"SecuritySubscribe2Side.py","file_name":"SecuritySubscribe2Side.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"451339946","text":"# PhatSnacks\n#\n# A Twitter bot: tweet a food at it, it'll reply with a recipe.\n# (forked from Molly White's twitterbot_framework: https://github.com/molly/twitterbot_framework)\nimport os\nimport tweepy\nfrom secrets import *\nfrom time import gmtime, strftime\nimport logging\nimport requests\n\n# ====== Individual bot configuration ==========================\nbot_username = \"phatsnacks1974\"\nlogfile_name = bot_username + \".log\"\nlogging.basicConfig(filename=logfile_name, datefmt=\"%Y%m%d_%H%M\",\n level=logging.DEBUG)\nfood2fork_url = \"http://food2fork.com/api/search\"\n# ==============================================================\n\n\ndef create_tweet(food_name):\n \"\"\"Create the text of the tweet you want to send.\"\"\"\n r = requests.get(food2fork_url, params={\"q\": food_name, \"key\": F2F_KEY})\n try:\n r_json = r.json()\n except Exception as e:\n return \"No recipe found. #sadpanda\"\n # fetch top-ranked recipe\n recipe = r_json[\"recipes\"][0]\n recipe_f2f_url = recipe[\"f2f_url\"]\n recipe_name = recipe[\"title\"]\n recipe_publisher = recipe[\"publisher\"]\n recipe_img = recipe[\"image_url\"]\n text = \"\\\"%s\\\" by %s: %s\" % (recipe_name, recipe_publisher, recipe_f2f_url)\n return text\n\n\ndef tweet(text):\n \"\"\"Send out the text as a tweet.\"\"\"\n # Twitter authentication\n auth = tweepy.OAuthHandler(C_KEY, C_SECRET)\n auth.set_access_token(A_TOKEN, A_TOKEN_SECRET)\n api = tweepy.API(auth)\n\n # Send the tweet and log success or failure\n try:\n api.update_status(text)\n except tweepy.error.TweepError as e:\n logging.error(e.message)\n else:\n logging.info(\"Tweeted: \" + text)\n\n\nif __name__ == \"__main__\":\n food_name = raw_input(\"Enter a food/ingredient: \")\n tweet_text = create_tweet(food_name)\n tweet(tweet_text)\n# print tweet_text\n\n","sub_path":"phatsnacks.py","file_name":"phatsnacks.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"24507929","text":"#Leonardo Fronza e Rodrigo Fernandes\n#segue o pai do vértice até chegar no conjunto ao qual ele foi atribuido\ndef get_super_parent(vertexes, v):\n parent = v\n while (vertexes[parent][\"parent\"] != None):\n parent = vertexes[parent][\"parent\"]\n return parent\n\ndef link(vertexes, v1, v2):\n v1_parent = get_super_parent(vertexes, v1)\n v2_parent = get_super_parent(vertexes, v2)\n #caso os vértices estejam no mesmo conjunto não há o que fazer\n if v1_parent == v2_parent:\n return\n if len(vertexes[v1_parent][\"letters\"]) < len(vertexes[v2_parent][\"letters\"]):\n from_v = v1_parent\n to_v = v2_parent\n else:\n from_v = v2_parent\n to_v = v1_parent\n #move os vértices do conjunto com menos vértices\n #para o conjunto com mais vértices\n while len(vertexes[from_v][\"letters\"]) > 0:\n vertexes[to_v][\"letters\"].append(vertexes[from_v][\"letters\"].pop())\n vertexes[from_v][\"parent\"] = to_v\n\nN = int(input()) #número de casos\nfor n in range(N):\n #V = número de vértices\n #E = número de arestas\n V, E = list(map(int, input().split()))\n vertexes = {}\n for i in range(V):\n #cria um conjunto para cada vértice\n vertexes[chr(ord('a') + i)] = {\"letters\": [chr(ord('a') + i)], \"parent\": None}\n for _ in range(E):\n v1, v2 = input().split()\n #conecta os vértices colocando um como pai do outro e movendo\n #a(s) letra(s) do filho para o pai\n link(vertexes, v1, v2)\n print(\"Case #{0}:\".format(n + 1))\n n_connected_components = 0\n for v in list(vertexes.keys()):\n if len(vertexes[v][\"letters\"]) != 0:\n #incrementa o número de componentes caso o conjunto da letra não esteja vazio\n n_connected_components += 1\n #imprime os vértices que formam um componente conexo\n vertexes[v][\"letters\"].sort()\n print(','.join(map(str, vertexes[v][\"letters\"])) + ',')\n print(\"{0} connected components\\n\".format(n_connected_components))\nprint()\n","sub_path":"Trabalho_02/q3/q3.py","file_name":"q3.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"371710198","text":"import sys\n\n\ndef refactor(contents, old, new):\n for count in range(len(contents)):\n line = contents[count]\n start = 0\n while start < len(line):\n index = line[start: len(line)].find(old)\n if index == -1:\n break\n line = line[0: index] + new + line[index + len(old): len(line)]\n start += index + len(old)\n contents[count] = line\n\n\ndef handler(path, old, new):\n file = open(path, \"r\")\n contents = file.readlines()\n file.close()\n\n refactor(contents, old, new)\n\n file = open(path, \"w\")\n contents = \"\".join(contents)\n file.write(contents)\n file.close()\n\n\ndef extract_from_file(path):\n file = open(path, \"r\")\n contents = file.readlines()\n file.close()\n if len(contents) < 3:\n raise SyntaxError\n\n files = []\n for number in range(len(contents) - 2):\n files.append(contents[number + 2].rstrip())\n return [files, contents[0].rstrip(), contents[1].rstrip()]\n\n\ndef print_exit(files, old, new):\n print(\"Replaced all instances of %s to %s in file(s):\" % (old, new))\n for path in files:\n print(path)\n\n\ndef main():\n del sys.argv[0]\n\n if len(sys.argv) == 1:\n result = extract_from_file(sys.argv[0])\n elif len(sys.argv) == 3:\n result = sys.argv\n result[0] = [result[0]]\n else:\n print(\"Invalid # of arguments!\")\n sys.exit()\n\n for path in result[0]:\n handler(path, result[1], result[2])\n print_exit(result[0], result[1], result[2])\n\n\nmain()\n","sub_path":"util/Simple-Refactor.py","file_name":"Simple-Refactor.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"84395706","text":"from a_builder import connect_ta as ct\r\nfrom a_builder import voca_util\r\nfrom a_builder import updater\r\nfrom threading import Thread\r\nfrom e_database import word_analysis as word_analysis_db\r\nfrom e_database import text_data_manager as text_data_manager_db\r\nfrom e_database import voca_manager as voca_manager_db\r\n\r\ndef extract_voca():\r\n voca_list = voca_manager_db.search_voca('')\r\n vp_data_list = text_data_manager_db.search_all_vp_data()\r\n result_dict_arr = voca_util.extract_voca(voca_list, vp_data_list)\r\n word_analysis_db.delete_all()\r\n for i in range(len(result_dict_arr)):\r\n group_no = result_dict_arr[i]['group_no']\r\n vp_no = result_dict_arr[i]['vp_no']\r\n extracted_voca = result_dict_arr[i]['extracted_voca']\r\n vp_text = result_dict_arr[i]['vp_text'][:10000]\r\n tokenized_text = result_dict_arr[i]['tokenized_text'][:5000]\r\n word_analysis_db.insert_extracted_voca(group_no, vp_no, extracted_voca, vp_text, tokenized_text)\r\n\r\ndef upload_vp_data_to_ta(user, project, data_type, model_type, vp_data_list, voca_list, uploading_config):\r\n ct.upload_vp_data_to_ta(user, project, data_type, model_type, vp_data_list, voca_list, uploading_config)\r\n \r\ndef get_uploading_config(user, project, data_type, model_type):\r\n res = ct.get_uploading_config(user, project, data_type, model_type)\r\n \r\n return res['uploading_config']\r\n \r\nupdate_thread = None\r\ndef create_jw_experiment_report(user, project, data_type, model_type, vp_data, normal_data):\r\n global update_thread\r\n update_thread = updater.updater()\r\n thread = Thread(target = update_thread.create_jw_experiment_report, args = (user, project, data_type, model_type, vp_data, normal_data))\r\n thread.start()\r\n \r\ndef create_doc2vec_experiment_report(user, project, data_type, model_type, vp_data, normal_data):\r\n global update_thread\r\n update_thread = updater.updater()\r\n thread = Thread(target = update_thread.create_doc2vec_experiment_report, args = (user, project, data_type, model_type, vp_data, normal_data))\r\n thread.start()\r\n \r\ndef get_progress_of_boa_from_jw(user, project, data_type, model_type):\r\n global update_thread\r\n if update_thread != None:\r\n end_yn = update_thread.get_end_yn_from_jw()\r\n if end_yn == 'N':\r\n return update_thread.get_progress_of_boa_from_jw()\r\n else:\r\n update_thread = None\r\n else:\r\n return 'end'\r\n\r\ndef get_progress_of_boa_from_doc2vec(user, project, data_type, model_type):\r\n global update_thread\r\n if update_thread != None:\r\n end_yn = update_thread.get_end_yn_from_doc2vec()\r\n if end_yn == 'N':\r\n return update_thread.get_progress_of_boa_from_doc2vec()\r\n else:\r\n update_thread = None\r\n else:\r\n return 'end'\r\n","sub_path":"a_builder/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":2818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"158477203","text":"#http://pinimatic.s3.amazonaws.com\n#http://192.168.1.100:5000\n\nfrom django.core.management.base import BaseCommand, CommandError\nfrom pinry.pins.models import Pin\nimport re\n\nclass Command(BaseCommand):\n args = ''\n help = 'modify the image url domain for all pins, enter new doamin: \\\n modifyimgurls '\n \n def handle(self, *args, **options):\n try:\n new_domain = args[0]\n except:\n raise CommandError('You must specify a domain: modifyimgurls ')\n found = re.findall('\\w*?://[^/]*?', str(new_domain))\n if found:\n pins = Pin.objects.all()\n for pin in pins:\n new_img_url = re.sub('\\w*?://.*?/', new_domain+'/', pin.image.url)\n is_domain = re.findall('\\w*?://.*?/', new_img_url)\n if not is_domain:\n new_img_url = re.sub('/', new_domain+'/', pin.image.url)\n pin.imgUrl = new_img_url\n #print('new_img_url:', pin.imgUrl)\n super(Pin, pin).save()\n self.stdout.write('-Successfully updated url to: \"%s\"' % pin.imgUrl)\n else:\n raise CommandError('You must specify domain: modifyimgurls ')\n \n \n \n \n \n","sub_path":"pinry/pins/management/commands/modifyimgurls.py","file_name":"modifyimgurls.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"426431684","text":"\"\"\"\nSolution to Project Euler problem 1.\n\nhttps://projecteuler.net/problem=1\n\nWritten by Aaron Power\n2017-05-06\n\"\"\"\n\ns = 0\n\nfor i in range(1, 1000):\n if i % 3 == 0 or i % 5 == 0:\n s = s + i\n print(f\"{i}, {s}\")\n\nprint(f\"The sum of all multiples of 3 or 5 below 1000 is: {s}\")\n","sub_path":"!old_solutions/euler_1.py","file_name":"euler_1.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"12158004","text":"import torch\nimport numpy as np\nimport os\nimport my_model as my_model\nimport torch.nn as nn\nimport my_dataset\nimport torch.optim as optim\nimport datetime\nimport cv2\nimport random\nimport time\nfrom cv_bridge import CvBridge, CvBridgeError\nfrom sensor_msgs.msg import Image\nimport rosbag\nimport rospy\n\n\nBATCH_SIZE = 10\nCUDA = 1\nFP16 = 0\nLOAD = 1\ncv2.namedWindow(\"a\", cv2.WINDOW_NORMAL);\ncv2.moveWindow(\"a\", 0,0);\ncv2.setWindowProperty(\"a\", cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN);\n#cv2.namedWindow(\"b\", cv2.WINDOW_NORMAL);\n#cv2.moveWindow(\"b\", 1920,0);\n#cv2.setWindowProperty(\"b\", cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN);\n\n\nmodel = my_model.Model()\nbridge = CvBridge()\nbag = rosbag.Bag('../store/_2019-12-03-17-19-24.bag')\n\nif CUDA:\n model = model.cuda()\n if FP16:\n model = model.half()\n\nif LOAD:\n model.load_state_dict(torch.load('../store/history/2019-12-18-09-28-07/600:0.model'))\nmodel.train()\nm = nn.Sigmoid()\n\n\ndef analysis(image):\n with torch.no_grad():\n model.eval()\n inputs = torch.tensor(image,dtype = torch.float32).cuda()\n if CUDA:\n inputs = inputs.cuda()\n if FP16:\n inputs = inputs.half() \n inputs = inputs / 255\n inputs = inputs.unsqueeze(0).unsqueeze(0)\n confi, outputs , _= model(inputs)\n if confi > 0.95:\n x,y,w,h = outputs[0,0].item(),outputs[0,1].item(),outputs[0,2].item(),outputs[0,3].item()\n x,y,w,h = int(x*2048 - w*1024 + 1024),int(y*1536 - h*768 + 768),int(w*2048),int(h*1546)\n cv2.rectangle(image,(x,y),(x+w,y+h),(0,0,255),2)\n cv2.imshow('a',image)\n\ncount = 0\nfor topic, msg, t in bag.read_messages(topics=['/image_raw']):\n count += 1\n if count % 4 != 0:\n continue\n key = cv2.waitKey(10)\n if key == ord('q'):\n break\n if key == ord(' '):\n continue_flag = 1\n continue\n image = bridge.imgmsg_to_cv2(msg, desired_encoding=\"passthrough\")\n image = cv2.cvtColor(image, cv2.COLOR_BAYER_BG2GRAY) \n analysis(image)\n\n\n","sub_path":"train/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"18574446","text":"import FWCore.ParameterSet.Config as cms\n\n# make a collection of TuneP muons which pass isHighPt ID\njetResolutionSF = cms.EDProducer(\"produceJetResolution\",\n jets_src = cms.InputTag(\"wRJets\"),\n genjets_src = cms.InputTag(\"slimmedGenJets\"),\n rho_src = cms.InputTag(\"fixedGridRhoAll\"),\n OutputCollectionName1 = cms.string(\"JetResolution\"),\n OutputCollectionName2 = cms.string(\"JERsf\"),\n OutputCollectionName3 = cms.string(\"JERsfUp\"),\n OutputCollectionName4 = cms.string(\"JERsfDown\"),\n OutputCollectionName5 = cms.string(\"GenJetPt\"),\n OutputCollectionName6 = cms.string(\"GenJetMatch\")\n)\n\n","sub_path":"python/produceJERsf_cff.py","file_name":"produceJERsf_cff.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"66972399","text":"__author__ = 'Joe Linn'\n\nimport unittest\nfrom tests.base import Base\nimport pylastica\n\n\nclass CommonTest(unittest.TestCase, Base):\n def test_to_dict(self):\n query = pylastica.query.Common('body', 'test query', .001)\n query.set_low_frequency_operator(pylastica.query.Common.OPERATOR_AND)\n\n expected = {\n 'common': {\n 'body': {\n 'query': 'test query',\n 'cutoff_frequency': .001,\n 'low_freq_operator': 'and'\n }\n }\n }\n\n self.assertEqual(expected, query.to_dict())\n\n def test_query(self):\n index = self._create_index('common_test')\n doc_type = index.get_doc_type('test')\n\n #add documents to create common terms\n doc_type.add_documents([pylastica.Document(i, {'body': 'foo bar'}) for i in xrange(5)])\n\n doc_type.add_document(pylastica.Document(5, {'body': 'foo baz'}))\n doc_type.add_document(pylastica.Document(6, {'body': 'foo bar baz'}))\n index.refresh()\n\n query = pylastica.query.Common('body', 'foo bar baz', .5)\n results = doc_type.search(query).results\n\n #documents containing only common words should not be returned\n self.assertEqual(2, len(results))\n\n #the document containing both common words should be scored lowest\n self.assertEqual(results[0].data['body'], 'foo baz')\n\n index.delete()\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/query/test_common.py","file_name":"test_common.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"97737632","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author: yyasumizu\n# @Date: 2019-02-18\n# @Last Modified time: 2019-02-18\n\n'''\nusage :\npython count_intron.py intron.bed bam output-prefix\n\nex.\npython count_intron.py ref/mm10_genes_intron.bed bam/84_DP_RamDA_test.accept.sort.bam intron_count/84_DP_RamDA_test\n\nipynb for the data prep : /home/yyasumizu/RAID6TB/bioinformatics/mac/SingleCell/ramda/intron_count.ipynb\n'''\n\n\nimport os\nimport sys\nimport pandas as pd\nimport pybedtools as pb\n\n\nf_bed_intron = sys.argv[1]\nf_bam = sys.argv[2]\nf_out_prefix = sys.argv[3]\n\n\nref = pb.BedTool(f_bed_intron)\nbam = pb.BedTool(f_bam)\ncounts = ref.coverage(bam, s=True) # only the same strand\n\nbam_count = bam.count()\n\ndf_count = counts.to_dataframe()\ndf_count.columns = ['chr', 'start', 'end', 'symbol', 'score', 'strand', 'n_overlap', 'len_overlap', 'len', 'frac']\n\ndf_count_groupby = df_count.groupby('symbol').sum()\ndf_count_groupby['symbol'] = df_count_groupby.index\n\ndf_count_groupby['rpkm'] = df_count_groupby['n_overlap'] / (df_count_groupby['len'] / 1000) * (bam_count / 1000000)\n\n\ndf_count_groupby[['symbol', 'rpkm']].to_csv(f_out_prefix+'RPKM.txt', index=None, header=None, sep='\\t')\ndf_count_groupby[['symbol', 'n_overlap']].to_csv(f_out_prefix+'count.txt', index=None, header=None, sep='\\t')\n","sub_path":"count_intron.py","file_name":"count_intron.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"419193756","text":"from django.db import models\nfrom django.core.files.storage import FileSystemStorage\n\nfs = FileSystemStorage(location='/media/notes')\n\nfrom courses.models import Courses, Cour_Section, Users\n\n# Create your models here.\nclass Notes(models.Model):\n note_id = models.AutoField(primary_key=True, db_column=\"Note_ID\")\n\n uploader_name = models.ForeignKey('courses.Users', db_column=\"Uploader_Name\")\n\n date = models.DateField(db_column=\"Upload_Date\")\n\n file_name = models.CharField(max_length=500, db_column=\"File_Name\")\n\n #Fix File Typing file = \"\"\n\n class Meta:\n verbose_name = \"Note\"\n\n def __str__(self):\n return ( \"Note ID: \" + str(self.note_id) + \n \", Uploader Name: \" + str(self.uploader_name) +\n \", Date: \" + str(self.date) +\n \", File Name: \" + str(self.file_name) ) \n\nclass UploadedNotes(models.Model):\n note_to_upload = models.FileField(storage=fs)\n\n note_id = models.AutoField(primary_key=True, db_column=\"Note_ID\")\n\n course_id = models.ForeignKey('courses.Courses', db_column=\"Course_ID\")\n\n section_id = models.ForeignKey('courses.Cour_Section', related_name='+',\n db_column=\"Section_ID\")\n\n professor = models.ForeignKey('courses.Cour_Section', related_name='+',\n db_column=\"Professor\")\n\n uploader_name = models.ForeignKey('courses.Users', db_column=\"Uploader_Name\")\n \n date = models.ForeignKey('Notes', db_column=\"Upload_Date\")\n\n class Meta:\n verbose_name = \"Uploaded Note\"\n\n def __str__(self):\n return ( \"Note ID: \" + str(self.note_id) + \n \", Course_ID: \" + str(self.course_id) +\n \", Section_ID: \" + str(self.section_id) +\n \", Professor: \" + str(self.professor) + \n \", Uploader Name: \" + str(self.uploader_name) +\n \", Date: \" + str(self.date) ) \n\n\n\n\n","sub_path":"beartraps/notes/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"620161675","text":"# Create your views here.\nfrom django.http import HttpResponse\nfrom django.template import loader\nfrom django.shortcuts import render\n\nfrom .models import Article,Tag,Category\nimport markdown\n\ndef index(request):\n category_list = Category.objects.all()\n tag_list = Tag.objects.all()\n total = Article.objects.order_by('-id')[:1][0].id\n article_list = Article.objects.order_by('-date_time')\n template = loader.get_template('index.html')\n context = {\n 'article_list': article_list,\n 'category_list': category_list,\n 'tag_list': tag_list,\n 'total': total\n }\n return HttpResponse(template.render(context, request))\n #return render(request,'index.html')\n\ndef test(request):\n return render(request, 'blog/1.html')\n\ndef articles(request, article_id):\n category_list = Category.objects.all()\n tag_list = Tag.objects.all()\n article = Article.objects.get(id=article_id)\n template = loader.get_template('article.html')\n article.content = markdown.markdown(article.content,\n extensions=[\n 'markdown.extensions.extra',\n 'markdown.extensions.codehilite',\n 'markdown.extensions.toc',\n ])\n context = {\n 'article':article,\n 'category_list': category_list,\n 'tag_list': tag_list,\n }\n return HttpResponse(template.render(context, request))","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"218470752","text":"import person\nimport graph\nimport parser\n\n\neveryone = graph.Graph()\ngroups=[]\ntables = []\n\nwith open(\"preferences.cvs\", \"w\") as preferences:\n lines = preferences.split(\",,\")\n for line in lines:\n line = line.split(\",\")\n everyone.addPerson(person.Person(name=line[0], preferences=line[1:]))\n\n#Turn text edges into references to other nodes as objects\nfor person in everyone:\n person.objectifyPreferences()\n\nwith open(\"tablenums.csv\",\"w\") as tables:\n for tableNum in tables.split(\",\"):\n tables+=graph.Table(tableNum=int(tableNum))\n\ntables.sort()\n\n#insert grouping here\n\ngroups.sort()\n\nfor group in groups:\n for table in tables:\n if table.numSpaces() >= group.size():\n table.nodes += group.nodes\n break\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"152215809","text":"\ndef allPrimeLessThan(y) :\n for i in range (2, y) :\n isItPrime(i)\n\ndef isItPrime(x) :\n flag = 1\n\n for i in range(2, x // 2):\n if ((x % i) == 0):\n # print(\"NOT PRIME :: \", x)\n flag = 0\n return \"PRIME\"\n break\n\n if ((flag == 1) and x != 4):\n print(\"Prime Number :::::: \", x)\n return \"Not PRIME\"\n\nallPrimeLessThan(1000)","sub_path":"Week1/21-PrimeBelowANumber.py","file_name":"21-PrimeBelowANumber.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"529987163","text":"# Frequency Counter - sameFrequency\n# Write a function called sameFrequency. Given two positive integers, find out if the two numbers have the same frequency of digits. \n# Time Complexity Should be O(N)\n############### METHOD 01 ###################\n\nfrom collections import Counter\ndef sameFrequency(num1, num2):\n\treturn Counter(str(num1)) == Counter(str(num2))\n\n############### METHOD 02 ###################\ndef sameFrequency(num1, num2):\n\n\tif len(str(num1)) != len(str(num2)): return False\n\n\tnumCount1 = {n:str(num1).count(n) for n in str(num1)}\n\tnumCount2 = {n:str(num2).count(n) for n in str(num2)}\n\n\tfor key,val in numCount1.items():\n\t\tif key not in numCount2.keys():\n\t\t\treturn False\n\t\telif numCount1[key] != numCount2[key]:\n\t\t\treturn False\n\treturn True\n\nprint(sameFrequency(182, 281)) # True\nprint(sameFrequency(34, 14)) # False\nprint(sameFrequency(3589578, 5879385)) # True\nprint(sameFrequency(22, 222)) # False","sub_path":"20_Challenge_01.py","file_name":"20_Challenge_01.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"535633933","text":"#!/usr/bin/env python\n\n# \n# LSST Data Management System\n# Copyright 2014 LSST Corporation.\n# \n# This product includes software developed by the\n# LSST Project (http://www.lsst.org/).\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the LSST License Statement and \n# the GNU General Public License along with this program. If not, \n# see .\n#\n\nimport threading\nfrom lsst.ctrl.ap.replicatorJobServicer import ReplicatorJobServicer\nfrom lsst.ctrl.ap.workerJobServicer import WorkerJobServicer\nfrom lsst.ctrl.ap.heartbeat import Heartbeat\nimport lsst.log as log\nfrom lsst.ctrl.ap.conditionNotifier import ConditionNotifier\n\nclass JobMessageDispatcher(threading.Thread):\n def __init__(self, jsock, dataTable, condition):\n super(JobMessageDispatcher, self).__init__()\n self.jsock = jsock\n self.dataTable = dataTable\n self.condition = condition\n\n def run(self):\n msg = self.jsock.recvJSON()\n log.debug(\"dh: 1: msg = %s\", msg)\n msgType = msg[\"msgtype\"]\n if msgType == \"replicator job\" or msgType == \"wavefront job\":\n handler = ReplicatorJobServicer(self.jsock, self.dataTable, self.condition)\n handler.serviceRequest(msg)\n heartbeat = Heartbeat(self.jsock, 1)\n heartbeat.start()\n while True:\n msg = self.jsock.recvJSON()\n log.debug(\"dh: 2: msg = %s\", msg)\n handler.serviceRequest(msg)\n elif msgType == \"worker job\":\n handler = WorkerJobServicer(self.jsock, self.dataTable, self.condition)\n handler.serviceRequest(msg)\n","sub_path":"python/lsst/ctrl/ap/jobMessageDispatcher.py","file_name":"jobMessageDispatcher.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"586044974","text":"from typing import Tuple\nimport silvereye_wps_demo.models.ecoconstants as eco_constants\n\n\nclass Validators(object):\n\n @staticmethod\n def is_valid_range(var_range: Tuple, var_type: str) -> bool:\n \"\"\"\n validates a (lo, hi) range tuple of type var_type.\n var_type :: \"time\" | \"lat\" | \"lon\"\n returns True if lo < hi\"\"\"\n boundaries = {\n \"time\": {\"min\": eco_constants.TIME_ISO_MIN, \"max\": eco_constants.TIME_ISO_MAX},\n \"lat\": {\"min\": -eco_constants.LAT_MAX, \"max\": -eco_constants.LAT_MIN},\n \"lon\": {\"min\": eco_constants.LON_MIN, \"max\": eco_constants.LON_MAX},\n \"mo\": {\"min\": eco_constants.MONTH_MIN, \"max\": eco_constants.MONTH_MAX}\n }\n (lo, hi) = var_range\n return ((boundaries[var_type][\"min\"] <= lo)\n and (lo < hi)\n and (hi <= boundaries[var_type][\"max\"]))\n\n @staticmethod\n def validate_parameters(time_range: Tuple[str, str],\n lat_range: Tuple[float, float],\n lon_range: Tuple[float, float]) -> None:\n \"\"\"\n Validates the parameters:\n time_range, lat_range, lon_range are tuples of (lo, hi) values\n \"\"\"\n template = \"Invalid {} parameters: Values must be min < lo < hi < max.\"\n if not Validators.is_valid_range(time_range, \"time\"):\n raise ValueError(template.format(\"time\"))\n if not Validators.is_valid_range(lat_range, \"lat\"):\n raise ValueError(template.format(\"latitude\"))\n if not Validators.is_valid_range(lon_range, \"lon\"):\n raise ValueError(template.format(\"longitude\"))\n\n @staticmethod\n def is_valid_year(yr: int) -> bool:\n \"\"\"\n Tests that the given year falls between 1970..2014\n :param yr: int year to test\n :return: bool: True or False\n \"\"\"\n return eco_constants.YEAR_MIN <= yr <= eco_constants.YEAR_MAX\n\n @staticmethod\n def is_valid_month(mo: int) -> bool:\n \"\"\"\n Tests that the given month falls between 1..12\n :param mo: int month to test\n :return: bool: True or False\n \"\"\"\n return eco_constants.MONTH_MIN <= mo <= eco_constants.MONTH_MAX\n\n @staticmethod\n def is_valid_quarter(qtr: int) -> bool:\n \"\"\"\n Tests that the given quarter falls between 1..4\n :param qtr: quarter to test\n :return: bool: True or False\n \"\"\"\n return eco_constants.QTR_MIN <= qtr <= eco_constants.QTR_MAX\n\n @staticmethod\n def is_valid_year_range(yr_range: Tuple[int, int]) -> bool:\n (yr_lo, yr_hi) = yr_range\n return yr_lo < yr_hi \\\n and Validators.is_valid_year(yr_lo) \\\n and Validators.is_valid_year(yr_hi)\n\n @staticmethod\n def is_valid_latitude(lat: float) -> bool:\n \"\"\"\n True if given latitude is within acceptable range\n :param lat: latitude\n :return: boolean\n \"\"\"\n boundaries = {\"min\": - eco_constants.LAT_MAX, \"max\": - eco_constants.LAT_MIN}\n return (boundaries[\"min\"] <= lat) and (lat <= boundaries[\"max\"])\n\n @staticmethod\n def is_valid_longitude(lon: float) -> bool:\n \"\"\"\n True if given longitude is within acceptable range\n :param lon: longitude\n :return: boolean\n \"\"\"\n boundaries = {\"min\": eco_constants.LON_MIN, \"max\": eco_constants.LON_MAX}\n return (boundaries[\"min\"] <= lon) and (lon <= boundaries[\"max\"])\n","sub_path":"src/silvereye_wps_demo/models/helpers/validators.py","file_name":"validators.py","file_ext":"py","file_size_in_byte":3486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"228510507","text":"import os\nfrom dotenv import load_dotenv\nimport requests\nimport json\n\nload_dotenv()\n\nimport random\n\n# COCKTAIL_API = os.getenv(\"COCKTAIL_API\") -- NOT SURE WE NEED THIS\n\ndef liquor_type():\n liquor = input(\"Please select a liquor type: \")\n valid_selections = [\"whiskey\", \"whisky\", \"beer\", \"port\", \"vermouth\", \"everclear\", \"absinthe\", \"cider\", \"brandy\", \"aperol\", \"wine\", \"gin\", \"vodka\", \"rum\", \"tequila\"]\n if liquor not in valid_selections:\n print(\"OOPS, invalid liquor type. Please try again.\")\n exit()\n else:\n print(f\"SELECTED LIQUOR: '{liquor}'\")\n \n \n request_url = f\"https://www.thecocktaildb.com/api/json/v1/1/filter.php?i={liquor}\"\n response = requests.get(request_url)\n liquor_data = json.loads(response.text)\n\n random_drink = liquor_data[\"drinks\"][0]\n\n## Send Email \nimport os\nfrom dotenv import load_dotenv\nfrom sendgrid import SendGridAPIClient\nfrom sendgrid.helpers.mail import Mail\nload_dotenv()\n\nSENDGRID_API_KEY = os.getenv(\"SENDGRID_API_KEY\", default=\"OOPS, please set env var called 'SENDGRID_API_KEY'\")\nSENDER_ADDRESS = os.environ.get(\"SENDER_ADDRESS\", \"OOPS, please set env var called 'SENDER_ADDRESS'\")\n\nclient = SendGridAPIClient(SENDGRID_API_KEY) #> \nprint(\"CLIENT:\", type(client))\n\nsubject = \"This is the recipe for your cocktail, enjoy!\"\n\nhtml_content = \"Cocktail Recipe\"\nprint(\"HTML:\", html_content)\n\nmessage = Mail(from_email=SENDER_ADDRESS, to_emails=SENDER_ADDRESS, subject=subject, html_content=html_content)\n\ntry:\n response = client.send(message)\n\n print(\"RESPONSE:\", type(response)) #> \n print(response.status_code) #> 202 indicates SUCCESS\n print(response.body)\n print(response.headers)\n\nexcept Exception as err:\n print(\"OOPS\")\n print(type(err))\n print(err)\n","sub_path":"app/cocktail_recipes.py","file_name":"cocktail_recipes.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"233397219","text":"import os\nimport pymongo\n\ndef open_db(board_title = None, start_date=None, end_date=None):\n '''\n 打開 DataBase 此處使用MongoDB,並且設定unique Index,方便日後查詢及避免重複抓取資料\n '''\n client = pymongo.MongoClient('mymongo', port=27017)\n client.server_info()\n db = client.ptt\n collect = db[\"pttscrapy\"]\n try:\n finds = collect.find({'title': board_title, 'publishedTime':{'$gte':start_date, '$lte':end_date}})\n collect.create_index([('canonicalUrl'), pymongo.ASCENDING], unique=True)\n except:\n finds = None\n return collect, finds\n\ndef write_db(queue):\n '''\n 寫入資料庫\n '''\n data = queue.get()\n collect, _ = open_db()\n try:\n collect.insert_one(data)\n print('資料寫入成功')\n except Exception as e:\n print(e)\n print('資料寫入失敗')\n print('=' * 30)\n","sub_path":"Database.py","file_name":"Database.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"64887127","text":"#!/usr/bin/env python3\nimport os\nimport shutil\nimport subprocess\n\ndef make_file(name = \"file.txt\", contents = \"File contents\"):\n with open(name, \"w\") as f:\n f.write(contents)\n\ndef make_directory(path = \"folder\"):\n return os.mkdir(path)\n\ndef file_exists(path = None):\n return os.path.isfile(path)\n\ndef is_ddh_installed():\n ret = subprocess.run(['ddh', '--version'], stdout=subprocess.PIPE)\n if ret.returncode != 0:\n return False\n return True\n\ndef make_test_files():\n os.mkdir(\"test_files\")\n os.mkdir(\"test_destination\")\n make_file(\"test_files/abcd.txt\")\n make_file(\"test_files/dupe1.txt\")\n make_file(\"test_files/dupe2.txt\")\n make_file(\"test_files/file2.txt\", \"Other content\")\n\ndef get_dry_run_output():\n ret = subprocess.run(\"ddh test_files --output no --format json -v duplicates\".split(), stdout=subprocess.PIPE)\n lines = ret.stdout.decode('utf-8').split('\\n')\n ret = subprocess.Popen(\"python3 ddh-move.py test_destination --dry-run\".split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n ret.stdin.write(bytes(lines[-2], encoding='utf-8'))\n output = ret.communicate()[0]\n return output.decode('utf-8')\n\ndef move_the_dupes():\n ret = subprocess.run(\"ddh test_files --output no --format json -v duplicates\".split(), stdout=subprocess.PIPE)\n lines = ret.stdout.decode('utf-8').split('\\n')\n ret = subprocess.Popen(\"python3 ddh-move.py test_destination\".split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n ret.stdin.write(bytes(lines[-2], encoding='utf-8'))\n output = ret.communicate()[0]\n\ndef cleanup_test_files():\n shutil.rmtree(\"test_files\", ignore_errors=True)\n shutil.rmtree(\"test_destination\", ignore_errors=True)\n\ndef main():\n assert (True == is_ddh_installed()), \"You need to have ddh installed to run the tests.\"\n\n make_test_files()\n\n #make sure that a --dry-run prints out the correct files\n correct_files = [\"test_files/dupe1.txt\", \"test_files/dupe2.txt\"]\n output = get_dry_run_output()\n for file in correct_files:\n assert file in output,\"--dry-run option did not print the correct files!\"\n\n #move the dupes and ensure the correct files get moved\n move_the_dupes()\n correct_files = [\"dupe1.txt\", \"dupe2.txt\"]\n for file in os.listdir(\"test_destination\"):\n assert file in correct_files,\"The test_destination folder contains an unexpected file: \" + file\n #and the correct files are left behind\n unmoved_files = [\"abcd.txt\", \"file2.txt\"]\n for file in os.listdir(\"test_files\"):\n assert file in unmoved_files,\"The test_files folder contains an unexpected file: \" + file\n\n cleanup_test_files()\n print(\"All tests passed!\")\n\nif __name__ == \"__main__\":\n main()","sub_path":"ddh-move-tests.py","file_name":"ddh-move-tests.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"223465351","text":"#!/usr/bin/env python3\n\nfrom io import open\nimport hashlib\nimport os\nimport crypto\n\n# VALORES DE ENCRIPTACION N6 (E_N6)\n# CAMBIAR A NX (E_NX)\n\n\n# # WARNING: PRIMERO SE DEBE CONCLUIR LOS METODOS RELACIONADOS A LA MANIPULACION DE DB\ndef validation_key (key):\n\t\"\"\"VERIFICA LA VALIDEZ DE UNA LLAVE, EN LA DB\"\"\"\n\t_path = \".master/.access/dkcache/\"\n\tos.chdir(_path)\n\n\tkey_status = False\n\n\tdblink = open(\"Xkeydb0.xrk\", \"r\")\n\tkeyOnLine = \"\"\n\n\tpriv_dbkey = []\n\tpubl_dbkey = []\n\n\tfor line_lecture in dblink.readlines():\n\t\tdelimeter = \" --> \"\n\t\tdel_index = line_lecture.find(delimeter)\n\t\tLINE_HASH = line_lecture[0:del_index]\n\n\t\tkeyOnLine = line_lecture[del_index+5:]\n\n\t\tpriv_dbkey.append(keyOnLine[0:-1])\n\t\tlimit = int(len(keyOnLine) / 4)\n\t\tpubl_dbkey.append(keyOnLine[:limit])\n\n\tif key in priv_dbkey:\n\t\tkey_status = True\n\telif key in publ_dbkey:\n\t\tkey_status = True\n\telse:\n\t\tkey_status = False\n\t\tprint(\"LA LLAVE NO SE ENCUENTRA\")\n\n\t# Nos retornamos al directorio raiz\n\tactual_dir = str(os.getcwd())\n\tactual_dir = actual_dir[:-23]\n\tos.chdir(actual_dir)\n\n\treturn key_status\n\n\n# # NOTE: funcion terminada\ndef savedbMsg (msg, ahash):\n\t\"\"\"GUARDA EL MENSAJE ASOCIADO A SU HASH EN LA BD\"\"\"\n\tif isinstance(msg, str) == True:\n\t\tif len(msg) >= 1:\n\t\t\ttry:\n\t\t\t\tdirectory = \".master/.access/dkcache/\"\n\n\t\t\t\tif os.path.exists(directory):\n\t\t\t\t\tos.chdir(directory)\n\t\t\t\t\tdbfile = open(\"Xmsgdb1.xrk\", \"a\")\n\t\t\t\t\t\n\t\t\t\t\tmsg = msg.split()\n\t\t\t\t\tDIC_LINE = \"{b} --> {a}\\n\".format(a = ahash, b = msg)\n\n\t\t\t\t\tdbfile.write(DIC_LINE)\n\t\t\t\t\tdbfile.close()\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\timport EncryptX.trash\n\t\t\t\t\tEncryptX.trash.garbageCollector('file:Xmsgdb1.xrk')\n\t\t\t\t\tEncryptX.trash.synchronizer(msg_db = \"Xmsgdb1.xrk\", key_db = \"Xkeydb0.xrk\")\n\n\n\t\t\t\t\t# Nos retornamos al directorio raiz\n\t\t\t\t\tactual_dir = str(os.getcwd())\n\t\t\t\t\tactual_dir = actual_dir[:-23]\n\t\t\t\t\tos.chdir(actual_dir)\n\t\t\t\telse:\n\t\t\t\t\tprint(\"THE DIRECTORY DOESN'T EXIST!\")\n\t\t\texcept FileNotFoundError as e:\n\t\t\t\traise e\n\t\t\telse:\n\t\t\t\tpass\n\n\n\n# # NOTE: funcion terminada\ndef update (msg, newhash):\n\t\"\"\"ACTUALIZA LA BASE DE DATOS CON UN NUEVO HASH\"\"\"\n\t \n\t# Si se repite un mensaje pero tienen diferente hash\n\t# Se realiza el reemplazo del viejo con el nuevo\n\t\n\t# PROCESO DE ACTUALIZACION EN MSG DB\n\tif isinstance(msg, str) == True:\n\t\tif len(msg) >= 1:\n\t\t\t_path = \".master/.access/dkcache/\"\n\t\t\tos.chdir(_path)\n\n\t\t\t# Se abre primeramente para el modo lectura\n\t\t\tdb = open(\"Xmsgdb1.xrk\", \"r\")\n\n\t\t\texistent_lines = [] # Lineas de texto\n\t\t\tmsg = msg.split()\n\t\t\toldhash = \"\"\n\n\t\t\tfor line in db.readlines():\n\t\t\t\tif line.find(str(msg)) != -1:\n\t\t\t\t\tOBJ_MSG = line[0:int(len(str(msg)) + 5)]\n\t\t\t\t\tOBJ_LINE = \"{a} --> {b}\\n\".format(a = msg, b = newhash)\n\t\t\t\t\t\n\t\t\t\t\texistent_lines.append(OBJ_LINE)\n\n\t\t\t\t\toldhash = line[int(len(str(msg)) + 5):-1]\n\t\t\t\telse:\n\t\t\t\t\texistent_lines.append(line)\n\n\t\t\tdb.close() \t# Una vez finalzado el almacenamiento de cierra el enlace\n\n\t\t\tfile_lines = \"\".join(existent_lines)\n\n\t\t\t# Se abre el archivo nuevamente para escribir el nuevo contenido\n\t\t\t_db = open(\"Xmsgdb1.xrk\", \"w\")\n\t\t\t_db.write(file_lines)\n\t\t\t_db.close()\t# Se cierra el enlace nuevamente tras concluir la re-escritura\n\t\t\t\n\t\t\timport trash\n\t\t\ttrash.garbageCollector('file:Xmsgdb1.xrk')\n\t\t\ttrash.synchronizer(msg_db = \"Xmsgdb1.xrk\", key_db = \"Xkeydb0.xrk\")\n\n\t\t\t# PROCESO DE ACTUALIZACION EN KEY DB\n\t\t\tk_db \t\t\t= open(\"Xkeydb0.xrk\", \"r\")\n\t\t\t_hash \t\t\t= newhash\n\t\t\t_key\t \t\t= \"\"\n\t\t\tkexistent_lines = []\n\n\t\t\tfor line in k_db.readlines():\n\t\t\t\tif line.find(str(oldhash)) != -1:\n\t\t\t\t\tOBJ_HASH = line[0:int(len(str(_hash)) + 5 )]\n\n\t\t\t\t\t_key = line[int(len(str(_hash)) + 9):-1]\n\t\t\t\t\tOBJ_LINE = \"{a} --> {b}\\n\".format(a = _hash, b = _key)\n\t\t\t\t\t\n\t\t\t\t\tkexistent_lines.append(OBJ_LINE)\n\t\t\t\telse:\n\t\t\t\t\tkexistent_lines.append(line)\n\n\t\t\tk_db.close() \t# Una vez finalzado el almacenamiento de cierra el enlace\n\n\t\t\tkfile_lines = \"\".join(kexistent_lines)\n\n\t\t\t# Se abre el archivo nuevamente para escribir el nuevo contenido\n\t\t\t_kdb = open(\"Xkeydb0.xrk\", \"w\")\n\t\t\t_kdb.write(kfile_lines)\n\t\t\t_kdb.close()\t# Se cierra el enlace nuevamente tras concluir la re-escritura\n\t\t\t\n\t\t\timport trash\n\t\t\ttrash.garbageCollector('file:Xkeydb0.xrk')\n\t\t\ttrash.synchronizer(msg_db = \"Xmsgdb1.xrk\", key_db = \"Xkeydb0.xrk\")\n\n\t\t\t# Nos retornamos al directorio raiz\n\t\t\tactual_dir = str(os.getcwd())\n\t\t\tactual_dir = actual_dir[:-23]\n\n\t\t\tos.chdir(actual_dir)\n\n\t\t\tif oldhash != newhash:\n\t\t\t\tprint(\"*-= {a} HAS BEEN REPLACED BY {b} =-*\".format(a = oldhash, b = newhash))\n\n\n\n# # NOTE: funcion terminada\ndef hash_msg_gen (message):\n\t\"\"\"GENERA UN HASH UNICO PARA CADA MENSAJE\"\"\"\n\n\t\n\t# Hay que convertir de lista a cadena para poder manejarla\n\tif isinstance(message, list) == True:\n\t\tmessage = str(\"\".join(message))\n\t\t\n\telif isinstance(message, list) == False: \n\t\tif isinstance(message, str) == True:\n\t\t\tif len(message) >= 1:\n\t\t\t\tmessage = str(message.split())\n\t\t\t\toutput = hashlib.sha256(message.encode(\"utf-8\"))\n\t\t\t\toutput = str(output)\n\t\t\t\toutput = output[20:-1]\n\n\t\t\t\treturn output\n\telse:\n\t\tprint(\"ERROR - THE TYPE OF DATA IS WRONG. {}\".format(type(message)))\n\n\n\n\"\"\"*** <=== PROCESO DE ENCRIPTACION N-6 CON PAIR CHARS ===> ***\"\"\"\n\n# # NOTE: Funcion terminada\ndef decode (message, keystatus):\n\t\"\"\"CODIFICA LOS MENSAJES RECIBIDOS\"\"\"\n\n\tif keystatus == True and type(message) != None:\n\n\t\t# LISTA DE CARACTERES ASCII IMPRIMIBLES ADMITIDOS\n\t\t# # NOTE: SI UN CARACTER NO ESTA AQUI, PUEDE QUE EL PROGRAMA AUN ASI FUNCIONE\n\t\tchars \t\t=\t[]\t# Lista con los caracteres de la cadena\n\t\tpair_chars\t=\t[]\t# Caracteres de 'chars' traducidos\n\t\tpair_index\t=\t0\n\n\t\tCHARDIC = { \"s\" : \"a\", \"v\" : \"b\", \"2\" : \"c\", \"ñ\" : \"d\", \"7\" : \"e\", \"n\" : \"f\", \"p\" : \"g\", \n\t\t\"6\" : \"h\", \"z\" : \"i\", \"u\" : \"j\", \"4\" : \"k\", \"r\" : \"l\", \"y\" : \"m\", \"f\" : \"n\", \"d\" : \"ñ\",\n\t\t\"9\" : \"o\", \"g\" : \"p\", \"3\" : \"q\", \"l\" : \"r\", \"a\" : \"s\", \"8\" : \"t\", \"j\" : \"u\", \"b\" : \"v\",\n\t\t\"1\" : \"w\", \"0\" : \"x\", \"m\" : \"y\", \"i\" : \"z\", \"w\" : \"1\", \"c\" : \"2\", \"q\" : \"3\", \"k\" : \"4\", \n\t\t\"5\" : \"5\", \"h\" : \"6\", \"e\" : \"7\", \"t\" : \"8\", \"o\" : \"9\", \"x\" : \"0\", \"\\n\" : \"\\n\", \"\\t\" : \"\\t\",\n\t\t\"¶\" : \" \" }\n\n\t\t#print(message)\n\t\tindex_counter = 0\t# Contador del indice del mensaje\n\t\t\n\t\tfor char in message[pair_index:]:\n\t\t\tindex_counter \t+= 1\n\t\t\ttry:\n\t\t\t\tmsg_fragment = message[pair_index:]\n\t\t\t\tpair_index += 2\n\t\t\t\tOBJ_CHAR = str(\"{a}\".format(a = msg_fragment[:2]))\n\t\t\texcept IndexError as e:\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tif msg_fragment != \"\":\n\t\t\t\t\t#print(\"*\", msg_fragment)\n\t\t\t\t\t#print(OBJ_CHAR)\n\t\t\t\t\tpair_chars.append(OBJ_CHAR)\n\t\t\t\t\tindex_counter = 0\n\n\t\t#print(pair_chars)\n\n\t\tDEC_CHARS\t= []\t# Lista de caracteres modificados\n\n\t\tfor i_c in pair_chars:\n\t\t\t#print(i_c)\n\t\t\tif i_c[:1] == \"±\":\n\t\t\t\tOBJ_CHAR = CHARDIC[i_c[1:2]].upper()\n\t\t\t\t#print(\"***\", OBJ_CHAR)\n\t\t\t\tDEC_CHARS.append(OBJ_CHAR)\n\t\t\telif i_c[:1] == \"£\":\n\t\t\t\tOBJ_CHAR = CHARDIC[i_c[1:2]].lower()\n\t\t\t\t#print(\"***\", OBJ_CHAR)\n\t\t\t\tDEC_CHARS.append(OBJ_CHAR)\n\t\t\telif i_c == \"_¶\":\n\t\t\t\tOBJ_CHAR = \" \"\n\t\t\t\t#print(\"***\", OBJ_CHAR)\n\t\t\t\tDEC_CHARS.append(OBJ_CHAR)\n\t\t\telif i_c[:1] == \"æ\":\n\t\t\t\tOBJ_CHAR = \"{}\".format(i_c[1:2])\n\t\t\t\t#print(\"***\", OBJ_CHAR)\n\t\t\t\tDEC_CHARS.append(OBJ_CHAR)\n\t\t\telif i_c[:1] == \"¢\":\n\t\t\t\tif i_c[1:2] == \"n\":\n\t\t\t\t\tOBJ_CHAR = \"\\n\"\n\t\t\t\t\t#print(\"***\", OBJ_CHAR)\n\t\t\t\t\tDEC_CHARS.append(OBJ_CHAR)\n\t\t\t\tif i_c[1:2] == \"t\":\n\t\t\t\t\tOBJ_CHAR = \"\\t\"\n\t\t\t\t\t#print(\"***\", OBJ_CHAR)\n\t\t\t\t\tDEC_CHARS.append(OBJ_CHAR)\n\t\t\t\n\t\t#print(DEC_CHARS, \"\\n\")\n\t\t\n\t\tfinal_message = str(\"\".join(DEC_CHARS))\n\t\t#print(final_message)\n\n\t\treturn final_message\n\n\n# # NOTE: funcion terminada \ndef encode (message, keystatus):\n\t\"\"\"DECODIFICA LOS MENSAJES RECIBIDOS\"\"\"\n\n\tif keystatus == True and type(message) != None:\n\n\t\t# LISTA DE CARACTERES ASCII IMPRIMIBLES ADMITIDOS\n\t\t# # NOTE: SI UN CARACTER NO ESTA AQUI, PUEDE QUE EL PROGRAMA AUN ASI FUNCIONE\n\t\tchars \t\t=\t[]\t# Lista con los caracteres de la cadena\n\t\tenc_chars\t=\t[]\t# Caracteres de 'chars' traducidos\n\n\t\tCHARDIC = { \"a\" : \"s\", \"b\" : \"v\", \"c\" : \"2\", \"d\" : \"ñ\", \"e\" : \"7\", \"f\" : \"n\", \"g\" : \"p\", \n\t\t\"h\" : \"6\", \"i\" : \"z\", \"j\" : \"u\", \"k\" : \"4\", \"l\" : \"r\", \"m\" : \"y\", \"n\" : \"f\" ,\"ñ\" : \"d\",\n\t\t\"o\" : \"9\", \"p\" : \"g\", \"q\" : \"3\", \"r\" : \"l\", \"s\" : \"a\", \"t\" : \"8\", \"u\" : \"j\", \"v\" : \"b\",\n\t\t\"w\" : \"1\", \"x\" : \"0\", \"y\" : \"m\", \"z\" : \"i\", \"1\" : \"w\", \"2\" : \"c\", \"3\" : \"q\", \"4\" : \"k\", \n\t\t\"5\" : \"5\", \"6\" : \"h\", \"7\" : \"e\", \"8\" : \"t\", \"9\" : \"o\", \"0\" : \"x\", \"\\n\" : \"æn\", \"\\t\" : \"æt\",\n\t\t\" \" : \"¶\" }\n\n\t\tfor i in message:\n\t\t\tchars.append(i)\n\t\t#print(chars)\n\n\t\tfor i in chars:\n\t\t\tif i.islower() == True:\n\t\t\t\t#print(\"{} Es minuscula\".format(i))\n\t\t\t\tOBJ_CHAR = \"£{}\".format(CHARDIC[i])\n\t\t\t\tenc_chars.append(OBJ_CHAR)\n\t\t\telif i.isupper() == True:\n\t\t\t\t#print(\"{} Es mayuscula\".format(i))\n\t\t\t\tOBJ_CHAR = \"±{}\".format(CHARDIC[i.lower()])\n\t\t\t\tenc_chars.append(OBJ_CHAR)\n\t\t\telif i == \" \":\n\t\t\t\t#print(i)\n\t\t\t\tenc_chars.append(str(\"_\" + CHARDIC[i]))\n\t\t\telse:\n\t\t\t\tif i not in CHARDIC:\n\t\t\t\t\t# ALMACENA EL RESTO DE CARACTERES QUE NO SE ENCUENTREN DE FORMA ESPECIAL\n\t\t\t\t\t#print(i , \"NO ESTA\")\n\t\t\t\t\tenc_chars.append(str(\"æ{}\".format(i)))\n\t\t\t\telif i == \"\\n\":\n\t\t\t\t\t#print(\"ES UNA SECUENCIA\")\n\t\t\t\t\tOBJ_CHAR = \"¢n\"\n\t\t\t\t\tenc_chars.append(OBJ_CHAR)\n\t\t\t\telif i == \"\\t\":\n\t\t\t\t\t#print(\"ES UNA SECUENCIA\")\n\t\t\t\t\tOBJ_CHAR = \"¢t\"\n\t\t\t\t\tenc_chars.append(OBJ_CHAR)\n\t\t\t\telse:\n\t\t\t\t\t#print(i)\n\t\t\t\t\tOBJ_CHAR = \"æ{}\".format(i)\n\t\t\t\t\tenc_chars.append(OBJ_CHAR)\n\n\t\t#print(enc_chars, \"\\n\")\n\t\t#print(str(\"\".join(enc_chars)))\n\t\tfinal_message = str(\"\".join(enc_chars))\n\n\t\treturn final_message\ndef module_help ():\n\tprint(\"encode() \t | Funcion -> {}\".format(encode.__doc__))\n\tprint(\"decode() \t | Funcion -> {}\".format(decode.__doc__))\n\tprint(\"validation_key() | Funcion -> {}\".format(validation_key.__doc__))\n\tprint(\"hash_msg_gen() | Funcion -> {}\".format(hash_msg_gen.__doc__))\n\tprint(\"savedbMsg() \t | Funcion -> {}\".format(savedbMsg.__doc__))\n\tprint(\"update() \t | Funcion -> {}\".format(update.__doc__))\n\tprint(\"\")","sub_path":"N4Lib/encripNFour.py","file_name":"encripNFour.py","file_ext":"py","file_size_in_byte":9693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"170669354","text":"import time\nfrom watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\nfrom watchdog.events import PatternMatchingEventHandler\n\ndef on_created(event):\n message = \"Watchdog: \"\n if not event.is_directory:\n message = \"file \"\n message += f\"{event.src_path} created\"\n print(message)\n\ndef on_deleted(event):\n message = \"Watchdog: \"\n if not event.is_directory:\n message = \"file \"\n message += f\"{event.src_path} deleted\"\n print(message)\n\ndef on_modified(event):\n message = \"Watchdog: \"\n if not event.is_directory:\n message = \"file \"\n message += f\"{event.src_path} modified\"\n print(message)\n\ndef on_moved(event):\n message = \"Watchdog: \"\n if not event.is_directory:\n message = \"file \"\n message += f\"{event.src_path} moved to {event.dest_path}\"\n print(message)\n\nevent_handler = FileSystemEventHandler()\nevent_handler.on_created = on_created\nevent_handler.on_deleted = on_deleted\nevent_handler.on_modified = on_modified\nevent_handler.on_moved = on_moved\nmy_observer = Observer()\nmy_observer.schedule(event_handler, \"/home/hurrypeng/jfs/\", recursive=True)\nmy_observer.start()\n\ntry:\n while True:\n time.sleep(1)\nexcept KeyboardInterrupt:\n pass","sub_path":"Client/debug/DisGraFS-Client-Ubuntu-x86_64/watcher.py","file_name":"watcher.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"299298790","text":"\"\"\"\nEvalulate likelihood on nondiagonal transitions\n\"\"\"\n\nimport gym\nimport numpy as np\n#import gym_minigrid\nfrom rlkit.envs.gym_minigrid.envs.fourrooms import FourRoomsModEnv, BridgeEnv, WallEnv, TwoRoomsModEnv\nfrom rlkit.envs.gym_minigrid.modenvs import RandomModEnv\nfrom mpl_toolkits.mplot3d import axes3d, Axes3D\nfrom matplotlib import cm\nimport matplotlib.pyplot as plt\nfrom rlkit.torch.networks import Mlp\nfrom rlkit.torch.pytorch_util import from_numpy, get_numpy\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils import data\nfrom collections import OrderedDict\nimport numpy as np\n\n\nclass EnvContainer:\n def __init__(self, env):\n self.env = env\n self.width = self.env.grid.height\n self.height = self.env.grid.height\n #self.room_wh = self.env.room_wh\n\n states = []\n for j in range(self.env.grid.height):\n for i in range(self.env.grid.width):\n if self.env.grid.get(i, j) == None:\n states.append((i, j))\n state_to_idx = {s:i for i, s in enumerate(states)}\n\n self.states = states\n self.states_np = np.array(self.states)\n self.state_to_idx = state_to_idx\n\n transitions = []\n for i, state in enumerate(states):\n next_states = self._gen_transitions(state)\n for ns in next_states:\n transitions.append([state_to_idx[state],state_to_idx[tuple(ns.tolist())]])\n self.transitions = transitions\n self.transitions_np = np.array(self.transitions)\n\n def _gen_transitions(self, state):\n\n actions = np.array([[1, 0], [-1, 0], [0, 1], [0, -1]])\n next_states = [np.array(state)]\n for action in actions:\n ns = np.array(state)[:2] + action\n if ns[0] >= 0 and ns[1] >= 0 and ns[0] < self.width and ns[1] < self.height and \\\n self.env.grid.get(*ns) == None:\n next_states.append(ns)\n return next_states\n\n\n def gen_plot(self, encoder):\n\n #X = np.arange(0, self.width)\n #Y = np.arange(0, self.height)\n #X, Y = np.meshgrid(X, Y)\n Z = np.zeros((self.width, self.height))\n for i, state in enumerate(self.states):\n dist = encoder[i, :]\n Z[state[:2]] = np.argmax(dist) + 1\n return Z\n\n def sample_states(self, bs):\n return self.states_np[np.random.randint(0, len(self.states), bs), :]\n\n def all_states(self):\n return self.states_np\n\nclass AbstractMDPLikelihood:\n def __init__(self, envs):\n self.envs = [EnvContainer(env) for env in envs]\n\n self.n_abstract_mdps = 2\n self.abstract_dim = 4\n self.state_dim = 4\n self.states = []\n self.state_to_idx = None\n\n self.nondiag_ll = False\n\n\n def trans_prob(self, A, i, j):\n if not self.nondiag_ll:\n return A[i, j]\n else:\n if i == j:\n return A[i, j]\n else:\n B = A[i]\n B[i] = 0\n B /= (B.sum() + 1e-8)\n B *= (1 - A[i, j])\n return B[j]\n\n def train(self, A, max_epochs=100):\n\n # Initialize A and B\n n_states = len(self.envs[0].states)\n\n #B = np.ones((n_states, self.abstract_dim)) / n_states # P(o_t|q_t=i)\n B = np.random.uniform(size=(n_states, self.abstract_dim)) + 100\n B /= B.sum(0, keepdims=True)\n O = np.array(self.envs[0].transitions)\n\n num_seq = O.shape[0]\n\n alpha = np.zeros((num_seq, 2, self.abstract_dim)) # P(o_1..o_t, q_t=i | lambda)\n beta = np.zeros((num_seq, 2, self.abstract_dim)) # P(o_t+1...o_T | q_t=i, lambda)\n pi = np.ones(self.abstract_dim) / self.abstract_dim\n prev_likelihood = 0\n\n for epoch in range(1, max_epochs + 1):\n # E step\n alpha[:, 0, :] = pi * B[O[:, 0], :]\n alpha[:, 1, :] = 0\n for j in range(self.abstract_dim):\n for i in range(self.abstract_dim):\n alpha[:, 1, j] += alpha[:, 0, i] * self.trans_prob(A, i, j) * B[O[:, 1], j]\n\n beta[:, 1, :] = 1\n beta[:, 0, :] = 0\n for i in range(self.abstract_dim):\n for j in range(self.abstract_dim):\n beta[:, 0, i] += self.trans_prob(A, i, j) * B[O[:, 1], j] * beta[:, 1, j]\n #import pdb; pdb.set_trace()\n # Normalize to deal with underflow\n alpha /= alpha.sum(-1, keepdims=True)\n beta /= beta.sum(-1, keepdims=True)\n\n gamma = alpha * beta\n\n likelihood = gamma.sum(-1)[:, 0].mean()\n #print(likelihood)\n # normalize gamma\n gamma = gamma / gamma.sum(-1, keepdims=True) # P(q_t=j|O, lambda)\n\n zeta = np.zeros((num_seq, self.abstract_dim, self.abstract_dim)) # P(q_t=i, q_t+1=j|O, lambda)\n norm = (alpha[:, 0, :] * beta[:, 0, :]).sum(-1)\n for i in range(self.abstract_dim):\n for j in range(self.abstract_dim):\n zeta[:, i, j] = alpha[:, 0, i] * self.trans_prob(A, i, j) * B[O[:, 1], j] * beta[:, 1, j] / norm\n\n # M Steps\n for k in range(n_states):\n mask = O == k\n mask = np.expand_dims(mask, -1)\n B[k, :] = (gamma * mask).sum(1).sum(0) / gamma.sum(1).sum(0)\n\n # if likelihood == prev_likelihood and likelihood > 0.5:\n # break\n prev_likelihood = likelihood\n\n B /= B.sum(1, keepdims=True)\n #print(A)\n #print(B[:5])\n self.encoder = B\n return likelihood, B\n\n def kl(self, dist1, dist2):\n return (dist1 * (torch.log(dist1 + 1e-8) - torch.log(dist2 + 1e-8))).sum(1)\n\n def entropy(self, dist):\n return -(dist * torch.log(dist + 1e-8)).sum(-1)\n\n\n def gen_plot(self, likelihood, i, encoder_lst, envs):\n plots = [EnvContainer(env).gen_plot(encoder_lst[j]) for j, env in enumerate(envs)]\n\n plots = np.concatenate(plots, 1)\n\n plt.imshow(plots)\n plt.savefig('/home/jcoreyes/abstract/rlkit/examples/abstractmdp/exps/exp_random/fig_%.6f_%d.png' % (likelihood, i))\n #plt.show()\n\nif __name__ == '__main__':\n envs = [FourRoomsModEnv(gridsize=11, room_wh=(5, 5)),\n #FourRoomsModEnv(gridsize=11, room_wh=(5, 4)),\n FourRoomsModEnv(gridsize=11, room_wh=(5, 5), close_doors=[\"north\", \"south\"]),\n #FourRoomsModEnv(gridsize=11, room_wh=(5, 4), close_doors=[\"north\", \"south\"]),\n RandomModEnv(gridsize=11)\n ]\n tries = 1\n\n\n save_dir = '/home/jcoreyes/abstract/rlkit/examples/abstractmdp/exps/exp2/'\n abstract_t_all = np.load(save_dir + 'abstract_t.npy') # (n_tries, n_abstract_mdps, abstract_dim, abstract_dim)\n mixture = np.load(save_dir + 'mixture.npy')\n likelihood = np.load(save_dir + 'likelihood.npy')\n\n\n #abstract_t = abstract_t_all[likelihood.argmax()]\n\n\n abstract_t = np.array([\n [\n [0.9729, 0.01427, 0.01282, 0],\n [0.0154, 0.97224, 0, 0.012295],\n [0.01389, 0, 0.97237, 0.01373],\n [0, 0.0132, 0.0148, 0.972]\n ],\n [\n [0.98413, 0.01443, 0.0014283, 0],\n [0.015623, 0.9830, 0, 0.001368],\n [0.00154, 0, 0.98408, 0.014379],\n [0, 0.001468, 0.01555, 0.98297]\n ]]\n )\n # abstract_t = np.array([\n # [\n # [0.95, 0.025, 0.025, 0],\n # [0.025, 0.95, 0, 0.025],\n # [0.025, 0, 0.95, 0.025],\n # [0, 0.025, 0.025, 0.95]\n # ],\n # [\n # [0.9, 0.1, 0.00, 0],\n # [0.1, 0.9, 0, 0.0],\n # [0.00, 0, 0.9, 0.1],\n # [0, 0.00, 0.1, 0.9]\n # ]]\n # )\n abstract_t = (abstract_t + .1)\n abstract_t /= abstract_t.sum(2, keepdims=True)\n print(abstract_t)\n n_abstract_mdps = abstract_t.shape[0]\n n_envs = len(envs)\n best_ll = np.zeros((len(envs), n_abstract_mdps))\n best_encoder = [[0]*n_abstract_mdps for _ in range(n_envs)]\n encoder_lst = []\n for i, env in enumerate(envs):\n for abstract_idx in range(n_abstract_mdps):\n for j in range(tries):\n a = AbstractMDPLikelihood([env])\n likelihood, encoder = a.train(abstract_t[abstract_idx], max_epochs=300)\n if likelihood > best_ll[i, abstract_idx]:\n best_ll[i, abstract_idx] = likelihood\n best_encoder[i][abstract_idx] = encoder\n\n for i in range(len(envs)):\n encoder_lst.append(best_encoder[i][best_ll[i].argmax()])\n print(abstract_t)\n print(best_ll)\n a.gen_plot(0, 0, encoder_lst, envs)\n\n #print(a.mean_t)\n #print(a.y1)\n #a.gen_plot(likelihood, i)\n\n\n\n","sub_path":"examples/abstractmdp/random_mdp_hmm_likelihood.py","file_name":"random_mdp_hmm_likelihood.py","file_ext":"py","file_size_in_byte":8813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"594182263","text":"import json\nfrom django.contrib.auth import hashers\n# from rest_framework.authtoken.views import obtain_auth_token\nfrom django.http import HttpResponse\nfrom rest_framework import generics\nfrom rest_framework import exceptions\nfrom . import models\nfrom . import permissions\nfrom .helpers import (create_exception,\n generate_key,\n check_instance)\nfrom .paginations import Pagination\nfrom mongoengine import errors\n\n\nclass Personil(generics.ListCreateAPIView):\n permission_classes = (permissions.IsAdminOrLimitedAuthenticated,)\n\n def get_queryset(self):\n personil = Pagination(self.request.GET, models.Personil.objects)\n\n return personil.paginate()\n\n def get(self, request, *args, **kwargs):\n return HttpResponse(self.get_queryset())\n\n def post(self, request, *args, **kwargs):\n personil = models.Personil(\n username=request.POST.get('username'),\n password=hashers.make_password(request.POST.get('password')),\n token=generate_key(),\n nama_depan=request.POST.get('nama_depan'),\n nama_belakang=request.POST.get('nama_belakang'),\n email=request.POST.get('email')\n )\n\n return create_exception(personil)\n\n\nclass PersonilModifikasi(generics.RetrieveUpdateDestroyAPIView):\n permission_classes = (permissions.IsAdminOrLimitedAuthenticated,)\n\n def get_object(self):\n try:\n return models.Personil.objects.get(username=self.kwargs['username'])\n\n except models.Personil.DoesNotExist:\n raise exceptions.NotFound()\n\n except models.Personil.MultipleObjectsReturned:\n raise exceptions.NotAcceptable()\n\n def get(self, request, *args, **kwargs):\n return check_instance(self.get_object(),\n models.Personil)\n\n def put(self, request, *args, **kwargs):\n def execute():\n try:\n return self.get_object().update(\n set__nama_depan=request.POST.get('nama_depan'),\n set__nama_belakang=request.POST.get('nama_belakang'),\n set__super=bool(request.POST.get('super')),\n set__email=request.POST.get('email')\n )\n\n except errors.ValidationError as err:\n return json.dumps({\n 'detail': err.message\n })\n\n return check_instance(self.get_object(),\n models.Personil,\n execute())\n\n def delete(self, request, *args, **kwargs):\n def execute():\n return self.get_object().delete()\n\n return check_instance(self.get_object(),\n models.Personil,\n execute())\n","sub_path":"perelite_utility/personil.py","file_name":"personil.py","file_ext":"py","file_size_in_byte":2804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"229905456","text":"trunk_template = [\n \"switchport trunk encapsulation dot1q\",\n \"switchport mode trunk\",\n \"switchport trunk allowed vlan\",\n]\n\ntrunk = {\"0/1\": [\"add\", \"10\", \"20\"], \"0/2\": [\"only\", \"11\", \"30\"], \"0/4\": [\"del\", \"17\"]}\nfor i in trunk:\n\tif trunk[i][0].startswith('add'):\n\t\tprint(\"add\")\n\telif trunk[i][0].startswith('del'):\n\t\tprint(\"remove\")\n\telif trunk[i][0].startswith('only'):\n\t\tprint(\"only\")\n\nfor intf, vlan in trunk.items():\n\tprint(\"interface FastEthernet \" + intf)\n\tfor command in trunk_template:\n\t\tif command.endswith(\"access vlan\"):\n\t\t\tprint(f\" {command} {vlan}\")\n\t\telse:\n\t\t\tprint(f\" {command}\")\n","sub_path":"exercises/06_control_structures/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"631168516","text":"import sublime, sublime_plugin\n\nclass OpenTimerPanel(sublime_plugin.WindowCommand):\n\n items = [\n ['Start Timer', 'Start a new Clock In'],\n ['Pause Timer', 'Pause a specific Clock In'],\n ['Discard Timer', 'Stop and discard a specific Clock In']\n ]\n\n command_map = {\n 0: 'start_timer',\n 1: 'pause_timer',\n 2: 'discard_timer'\n }\n\n def run(self):\n window = sublime.active_window()\n window.show_quick_panel(OpenTimerPanel.items, self.after_command_selection)\n\n def after_command_selection(self, index):\n if index == -1:\n return\n\n command = OpenTimerPanel.command_map[index]\n\n window = sublime.active_window()\n window.run_command(command)\n\n ","sub_path":"plugin/commands/OpenTimerPanel.py","file_name":"OpenTimerPanel.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"276781769","text":"# -*- coding: UTF-8 -*-\nimport json\nfrom optparse import OptionParser\nimport os\nimport sys\nfrom time import time\nfrom nltk.corpus import words\n\n__author__ = 'CMendezC'\n\n# Objective: Tagging biological terms from lists of terms related to aspects of interest:\n# 1) Changing POS tag by term tag\n\n# Parameters:\n# 1) --inputPath Path to read input files.\n# 2) --outputPath Path to place output files.\n# 3) --termPath Path to read term lists\n# 4) --termFiles JSON file with terms files and tags\n# 5) --crf Let POS tag instead of substituting it by term or freq tag\n\n# Output:\n# 1) Files with biological terms tagged\n\n# Execution:\n# python biologicalTermTagging.py --inputPath C:\\Users\\cmendezc\\Documents\\GENOMICAS\\AUTOMATIC_SUMMARIZATION_TFS\\corpus\\TF_PMIDs_TXT\\ECK120012096_GntR\\lemma --outputPath C:\\Users\\cmendezc\\Documents\\GENOMICAS\\AUTOMATIC_SUMMARIZATION_TFS\\corpus\\TF_PMIDs_TXT\\ECK120012096_GntR\\term --termPath C:\\Users\\cmendezc\\Documents\\GENOMICAS\\AUTOMATIC_SUMMARIZATION_TFS\\resources\\termLists --termFiles termFilesTag.json\n\n# FhlA\n# python biologicalTermTagging.py --inputPath C:\\Users\\cmendezc\\Documents\\GENOMICAS\\AUTOMATIC_SUMMARIZATION_TFS\\corpus\\TF_PMIDs_TXT_ECK120011394_FhlA\\lemma --outputPath C:\\Users\\cmendezc\\Documents\\GENOMICAS\\AUTOMATIC_SUMMARIZATION_TFS\\corpus\\TF_PMIDs_TXT_ECK120011394_FhlA\\term --termPath C:\\Users\\cmendezc\\Documents\\GENOMICAS\\AUTOMATIC_SUMMARIZATION_TFS\\resources\\termLists --termFiles termFilesTag.json\n\n# MarA\n# python biologicalTermTagging.py --inputPath C:\\Users\\cmendezc\\Documents\\GENOMICAS\\AUTOMATIC_SUMMARIZATION_TFS\\corpus\\TF_PMIDs_TXT_ECK120011412_MarA\\lemma --outputPath C:\\Users\\cmendezc\\Documents\\GENOMICAS\\AUTOMATIC_SUMMARIZATION_TFS\\corpus\\TF_PMIDs_TXT_ECK120011412_MarA\\term --termPath C:\\Users\\cmendezc\\Documents\\GENOMICAS\\AUTOMATIC_SUMMARIZATION_TFS\\resources\\termLists --termFiles termFilesTag.json\n\n# ArgR\n# python biologicalTermTagging.py --inputPath C:\\Users\\cmendezc\\Documents\\GENOMICAS\\AUTOMATIC_SUMMARIZATION_TFS\\corpus\\TF_PMIDs_TXT_ECK120011670_ArgR\\lemma --outputPath C:\\Users\\cmendezc\\Documents\\GENOMICAS\\AUTOMATIC_SUMMARIZATION_TFS\\corpus\\TF_PMIDs_TXT_ECK120011670_ArgR\\term --termPath C:\\Users\\cmendezc\\Documents\\GENOMICAS\\AUTOMATIC_SUMMARIZATION_TFS\\resources\\termLists --termFiles termFilesTag.json\n\n# CytR\n# python biologicalTermTagging.py --inputPath C:\\Users\\cmendezc\\Documents\\GENOMICAS\\AUTOMATIC_SUMMARIZATION_TFS\\corpus\\TF_PMIDs_TXT_ECK120012407_CytR\\lemma --outputPath C:\\Users\\cmendezc\\Documents\\GENOMICAS\\AUTOMATIC_SUMMARIZATION_TFS\\corpus\\TF_PMIDs_TXT_ECK120012407_CytR\\term --termPath C:\\Users\\cmendezc\\Documents\\GENOMICAS\\AUTOMATIC_SUMMARIZATION_TFS\\resources\\termLists --termFiles termFilesTag.json\n\n# Rob\n# python biologicalTermTagging.py --inputPath C:\\Users\\cmendezc\\Documents\\GENOMICAS\\AUTOMATIC_SUMMARIZATION_TFS\\corpus\\TF_PMIDs_TXT_ECK120011190_Rob\\lemma --outputPath C:\\Users\\cmendezc\\Documents\\GENOMICAS\\AUTOMATIC_SUMMARIZATION_TFS\\corpus\\TF_PMIDs_TXT_ECK120011190_Rob\\term --termPath C:\\Users\\cmendezc\\Documents\\GENOMICAS\\AUTOMATIC_SUMMARIZATION_TFS\\resources\\termLists --termFiles termFilesTag.json\n\n###########################################################\n# MAIN PROGRAM #\n###########################################################\n\nif __name__ == \"__main__\":\n # Parameter definition\n parser = OptionParser()\n parser.add_option(\"--inputPath\", dest=\"inputPath\",\n help=\"Path to read input files\", metavar=\"PATH\")\n parser.add_option(\"--outputPath\", dest=\"outputPath\",\n help=\"Path to place transformed files\", metavar=\"PATH\")\n parser.add_option(\"--termPath\", dest=\"termPath\",\n help=\"Path to read term files\", metavar=\"PATH\")\n parser.add_option(\"--termFiles\", dest=\"termFiles\",\n help=\"JSON file with terms files and tags\", metavar=\"FILE\")\n parser.add_option(\"--crf\", default=False,\n action=\"store_true\", dest=\"crf\",\n help=\"Let POS tag instead of substituting it by term or freq tag?\")\n\n (options, args) = parser.parse_args()\n\n if len(args) > 0:\n parser.error(\"None parameters indicated.\")\n sys.exit(1)\n\n # Printing parameter values\n print('-------------------------------- PARAMETERS --------------------------------')\n print(\"Path to read input files: \" + str(options.inputPath))\n print(\"Path to place transformed files: \" + str(options.outputPath))\n print(\"Path to read term files: \" + str(options.termPath))\n print(\"Let POS tag instead of substituting it by term or freq tag? \" + str(options.crf))\n\n ##### LOADING BIOLOGICAL TERM FILES #####\n # hashTermFiles = {\n # 'DFAM': ['domain_families_1grams.txt', 'domain_families_2grams.txt', 'domain_families_3grams.txt', 'domain_families_4grams.txt', 'domain_families_5Moregrams.txt'],\n # 'MF': ['domain_function_1grams.txt', 'domain_function_2grams.txt', 'domain_function_3grams.txt', 'domain_function_4grams.txt' , 'domain_function_5Moregrams.txt'],\n # 'RP': ['regulatory_Processes_GO_1grams.txt', 'regulatory_Processes_GO_2grams.txt', 'regulatory_Processes_GO_3grams.txt', 'regulatory_Processes_GO_4grams.txt', 'regulatory_Processes_GO_5Moregrams.txt'],\n # 'DPOS': ['domain_position_1grams.txt', 'domain_position_2grams.txt', 'domain_position_5Moregrams.txt'],\n # 'DMOT': ['domain_structural_motif_1grams.txt', 'domain_structural_motif_2grams.txt'],\n # 'TF': ['tfs.txt']\n # }\n\n # hashTerms = {\n # 'DFAM': [],\n # 'MF': [],\n # 'RP': [],\n # 'DPOS': [],\n # 'DMOT': [],\n # 'TF': []\n # }\n\n print('Loading biological term files...')\n with open(os.path.join(options.termPath, options.termFiles)) as data_file:\n lists = json.load(data_file)\n\n hashTermFiles = lists[\"hashTermFiles\"]\n hashTerms = lists[\"hashTerms\"]\n\n for key in hashTermFiles.keys():\n for f in hashTermFiles[key]:\n # print('File: ' + f)\n with open(os.path.join(options.termPath, f), \"r\", encoding=\"utf-8\", errors=\"replace\") as iFile:\n for line in iFile:\n line = line.strip('\\n')\n line = line.replace(' ', '-')\n if line not in hashTerms[key]:\n hashTerms[key].append(line)\n print(' Terms read {} size: {}'.format(key, len(hashTerms[key])))\n\n regularWords = words.words('en')\n print()\n\n filesPreprocessed = 0\n t0 = time()\n print(\"Biological term tagging files...\")\n # Walk directory to read files\n for path, dirs, files in os.walk(options.inputPath):\n # For each file in dir\n for file in files:\n print(\" Biological term tagging file...\" + str(file))\n with open(os.path.join(path, file), \"r\", encoding=\"utf-8\", errors=\"replace\") as iFile:\n # Create output file to write\n with open(os.path.join(options.outputPath, file.replace('lem.txt', 'term.txt')), \"w\", encoding=\"utf-8\") as oFile:\n for line in iFile:\n if line == '\\n':\n oFile.write(line)\n else:\n line = line.strip('\\n')\n listLine1 = line.split('\\t')\n if len(listLine1) < 3:\n continue\n word = listLine1[0]\n pos = listLine1[1]\n listLine2 = listLine1[2].split(' ')\n lemma = listLine2[0]\n if len(word) > 1:\n for termTag in hashTerms:\n if termTag == \"TF\":\n for term in hashTerms[termTag]:\n if (word == term) or (word.startswith(term) and lemma not in regularWords):\n #print(\" TAG WORD {} AS TF CAUSE START WITH TF {} OR IT IS EQUAL\".format(word, term))\n if listLine1[1].startswith(\"NN\"):\n # line = listLine1[0] + '\\t' + listLine1[1] + '\\t' + listLine2[0] + ' ' + termTag + ' TermTag'\n line = listLine1[0] + '\\t' + termTag + '\\t' + listLine2[0] + ' ' + termTag + ' TermTag'\n elif termTag == \"EFFECT\":\n if word.lower() in hashTerms[termTag]:\n line = word + '\\t' + termTag + '\\t' + lemma + ' ' + termTag + ' TermTag'\n else:\n if word in hashTerms[termTag]:\n # listLine2 = listLine1[2].split(' ')\n if termTag in [\"GENE\", \"TU\"]:\n if listLine1[1].startswith(\"NN\"):\n # line = listLine1[0] + '\\t' + listLine1[1] + '\\t' + listLine2[0] + ' ' + termTag + ' TermTag'\n line = listLine1[0] + '\\t' + termTag + '\\t' + listLine2[0] + ' ' + termTag + ' TermTag'\n elif termTag in [\"GC\"]:\n if pos not in [\"CC\", \"DT\", \"FW\", \"CD\", \"IN\", \"PRP$\", \"NNP\"]:\n # line = listLine1[0] + '\\t' + listLine1[1] + '\\t' + listLine2[0] + ' ' + termTag + ' TermTag'\n line = word + '\\t' + termTag + '\\t' + lemma + ' ' + termTag + ' TermTag'\n else:\n if termTag in ['FWDOM', 'FWRP']:\n # line = listLine1[0] + '\\t' + listLine1[1] + '\\t' + listLine2[0] + ' ' + termTag + ' FreqTag'\n line = listLine1[0] + '\\t' + termTag + '\\t' + listLine2[0] + ' ' + termTag + ' FreqTag'\n else:\n # line = listLine1[0] + '\\t' + listLine1[1] + '\\t' + listLine2[0] + ' ' + termTag + ' TermTag'\n line = listLine1[0] + '\\t' + termTag + '\\t' + listLine2[0] + ' ' + termTag + ' TermTag'\n oFile.write(line + '\\n')\n filesPreprocessed += 1\n\n # Imprime archivos procesados\n print()\n print(\"Files preprocessed: \" + str(filesPreprocessed))\n print(\"In: %fs\" % (time() - t0))\n","sub_path":"summarizer/biologicalTermTagging.py","file_name":"biologicalTermTagging.py","file_ext":"py","file_size_in_byte":10830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"298138792","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Nick Sweeting (github.com/pirate) 2016\n# MIT License\n\nimport traceback\n\nfrom sources import get_new_lines\nfrom parsers import parse_line, get_sources_info\nfrom loggers import notify, alert\n\ndef watch_sources():\n \"\"\"runloop to parse events from sources and dispatch alerts\"\"\"\n sources_info = '\\n' + get_sources_info()\n first_line = True\n for source, line in get_new_lines():\n if first_line:\n first_line = False\n notify(sources_info, 'Started Watching Sources')\n\n # parse the fetched lines, if not alert-worthy, alert_type will be None\n alert_type, title, content = parse_line(line, source)\n\n if alert_type == 'notify':\n notify(content, title)\n\n if alert_type == 'alert':\n alert(content, title)\n\nif __name__ == \"__main__\":\n try:\n watch_sources()\n except BaseException as e:\n notify(type(e).__name__, 'Stopped Watching Sources')\n if isinstance(e, Exception):\n traceback.print_exc()\n","sub_path":"Security Growler.app/Contents/Resources/growler.py","file_name":"growler.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"361992810","text":"import torch.nn as nn\r\nimport torch.nn.functional as F\r\n\r\nclass LeNet(nn.Module):\r\n # 一般在__init__中定义网络需要的操作算子,比如卷积、全连接算子等等\r\n def __init__(self):\r\n super(LeNet, self).__init__()\r\n # Conv2d的第一个参数是输入的channel数量,第二个是输出的channel数量,第三个是kernel size\r\n self.conv1 = nn.Conv2d(1, 6, 5)\r\n self.conv2 = nn.Conv2d(6, 16, 5)\r\n # 由于上一层有16个channel输出,每个feature map大小为5*5,所以全连接层的输入是16*5*5\r\n self.fc1 = nn.Linear(16*4*4, 120)\r\n self.fc2 = nn.Linear(120, 84)\r\n # 最终有10类,所以最后一个全连接层输出数量是10\r\n self.fc3 = nn.Linear(84, 3)\r\n self.pool = nn.MaxPool2d(2, 2)\r\n\r\n # forward这个函数定义了前向传播的运算,只需要像写普通的python算数运算那样就可以了\r\n def forward(self, x):\r\n x = F.relu(self.conv1(x))\r\n x = self.pool(x)\r\n x = F.relu(self.conv2(x))\r\n x = self.pool(x)\r\n # 下面这步把二维特征图变为一维,这样全连接层才能处理\r\n x = x.view(-1, 16 * 4 * 4)\r\n x = F.relu(self.fc1(x))\r\n x = F.relu(self.fc2(x))\r\n x = self.fc3(x)\r\n return x\r\n\r\n## fcn 层计算\r\n'''\r\nRuntimeError: shape '[-1, 1024]' is invalid for input of size 512\r\n Batch size -4\r\n 4=squartRoot(1024/4/16) \r\n I had to set x= x.view(4,16*4*4)\r\n \r\n'''","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"615860142","text":"from django.urls import path\nfrom django.contrib.auth.decorators import login_required\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('login', views.login, name='login'),\n path('signup', views.signup, name='signup'),\n path('logout', views.logout, name='logout'),\n path('seo', views.seo, name='seo'),\n path('research', views.research, name='research'),\n path('development', views.development, name='development'),\n path('branding', views.branding, name='branding'),\n path('smm', views.smm, name='smm'),\n path('optimization', views.optimization, name='optimization'),\n path('pr', views.pr, name='pr'),\n path('content_marketing', views.content_marketing, name='content_marketing')\n] ","sub_path":"main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"253922077","text":"\"\"\"DNS Authenticator for FreeDNS DNS.\"\"\"\nimport logging\n\nimport zope.interface\nfrom lexicon.providers import freedns\n\nfrom certbot import errors\nfrom certbot import interfaces\nfrom certbot.plugins import dns_common\nfrom certbot.plugins import dns_common_lexicon\n\nlogger = logging.getLogger(__name__)\n\nACCOUNT_URL = 'https://freedns.afraid.org/profile'\n\n\n@zope.interface.implementer(interfaces.IAuthenticator)\n@zope.interface.provider(interfaces.IPluginFactory)\nclass Authenticator(dns_common.DNSAuthenticator):\n \"\"\"DNS Authenticator for FreeDNS\n\n This Authenticator uses the FreeDNS v2 API to fulfill a dns-01 challenge.\n \"\"\"\n\n description = 'Obtain certificates using a DNS TXT record (if you are using FreeDNS for DNS).'\n ttl = 60\n\n def __init__(self, *args, **kwargs):\n super(Authenticator, self).__init__(*args, **kwargs)\n self.credentials = None\n\n @classmethod\n def add_parser_arguments(cls, add): # pylint: disable=arguments-differ\n super(Authenticator, cls).add_parser_arguments(add, default_propagation_seconds=60)\n add('credentials', help='FreeDNS credentials INI file.')\n\n def more_info(self): # pylint: disable=missing-docstring,no-self-use\n return 'This plugin configures a DNS TXT record to respond to a dns-01 challenge using ' + \\\n 'the FreeDNS API.'\n\n def _setup_credentials(self):\n self.credentials = self._configure_credentials(\n 'credentials',\n 'FreeDNS credentials INI file',\n {\n 'username': 'Username for FreeDNS login. (See {0}.)'.format(ACCOUNT_URL),\n 'password': 'Password for the same. Same URL to configure'\n }\n )\n\n def _perform(self, domain, validation_name, validation):\n self._get_freedns_client().add_txt_record(domain, validation_name, validation)\n\n def _cleanup(self, domain, validation_name, validation):\n self._get_freedns_client().del_txt_record(domain, validation_name, validation)\n\n def _get_freedns_client(self):\n return _FreeDNSLexiconClient(self.credentials.conf('token'), self.ttl)\n\n\nclass _FreeDNSLexiconClient(dns_common_lexicon.LexiconClient):\n \"\"\"\n Encapsulates all communication with the FreeDNS via Lexicon.\n \"\"\"\n\n def __init__(self, token, ttl):\n super(_FreeDNSLexiconClient, self).__init__()\n\n config = dns_common_lexicon.build_lexicon_config('dnssimple', {\n 'ttl': ttl,\n }, {\n 'auth_token': token,\n })\n\n self.provider = freedns.Provider(config)\n\n def _handle_http_error(self, e, domain_name):\n hint = None\n if str(e).startswith('401 Client Error: Unauthorized for url:'):\n hint = 'Is your API token value correct?'\n\n return errors.PluginError('Error determining zone identifier for {0}: {1}.{2}'\n .format(domain_name, e, ' ({0})'.format(hint) if hint else ''))\n","sub_path":"certbot-dns-freedns/certbot_dns_freedns/dns_freedns.py","file_name":"dns_freedns.py","file_ext":"py","file_size_in_byte":2947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"316609037","text":"import cv2\n\n\n#Variables\ndrawing = False\npt1 = (0,0)\npt2 = (0,0)\npress = False\n\n\n\ndef draw_rectangle(event,x,y, flags, params):\n \n global pt1,pt2, drawing, press\n \n # when mouse left button pressed\n if event == cv2.EVENT_LBUTTONDOWN:\n #assign top left point of rectangle\n pt1 = (x,y)\n drawing = False\n #mouse button pressed flag\n press = True\n \n # when mouse pointer is moving \n elif event == cv2.EVENT_MOUSEMOVE:\n drawing = True\n if drawing == True & press == True:\n #assign bottom right corner of rectangle\n pt2 = (x,y)\n \n #when mouse button is released \n elif event == cv2.EVENT_LBUTTONUP:\n drawing = True\n #resetting pressed mouse button\n press = False\n \n \n\n\n\n# Capture Video\ncap = cv2.VideoCapture(0)\nwidth = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\nheight = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n\n\n# Create a named window for connections\ncv2.namedWindow(winname = 'frame')\n\n# Bind draw_rectangle function to mouse cliks\ncv2.setMouseCallback('frame', draw_rectangle)\n\n\n\nwhile True:\n # Capture frame-by-frame\n ret, frame = cap.read()\n \n #draw when drawing flag is on\n if drawing == True:\n cv2.rectangle(frame, pt1, pt2, (0,0,255), 5)\n \n # Display the resulting frame\n cv2.imshow('frame', frame)\n \n #close window when Q is pressed\n if cv2.waitKey(10) & 0xFF == ord('q'):\n break\n \n\n\ncap.release()\ncv2.destroyAllWindows()\n \n \n\n\n","sub_path":"Image_Basics_with_OpenCV/draw_on_webcam_video_stream_by_mouse_click.py","file_name":"draw_on_webcam_video_stream_by_mouse_click.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"652587730","text":"import ast\nfrom PyQt4 import QtGui, QtCore\nfrom sift.common import KIND, INFO\nfrom sift.ui.create_algebraic_dialog_ui import Ui_create_algebraic_dialog\n\n\nDIFF_OP_NAME = 'Difference'\nNDI_OP_NAME = 'Normalized Difference Index'\nCUSTOM_OP_NAME = \"Custom...\"\nPRESET_OPERATIONS = {\n DIFF_OP_NAME: ('result = x - y', 2),\n NDI_OP_NAME: ('result = (x - y) / (x + y)', 2),\n}\n\n\nclass CreateAlgebraicDialog(QtGui.QDialog):\n def __init__(self, doc, selected_uuids=None, parent=None):\n super(QtGui.QDialog, self).__init__(parent)\n self.ui = Ui_create_algebraic_dialog()\n self.ui.setupUi(self)\n # NOTE: For now disable the operations area\n self.ui.operations_text.setDisabled(True)\n self._name_validator = QtGui.QRegExpValidator()\n # allow names that don't start with numbers but accept all other \"word\" characters\n self._name_validator.setRegExp(QtCore.QRegExp(r'^\\w[-\\+\\*/\\w\\s]+'))\n self.ui.layer_name_edit.setValidator(self._name_validator)\n self.doc = doc\n\n # setup UI elements\n available_info = {}\n available_short_names = []\n selected_short_names = []\n # use DATASET_NAME as unique group identifier\n for idx, prez, layer in self.doc.current_layers_where(kinds=(KIND.IMAGE, KIND.COMPOSITE)):\n # use the UUID as a representative when talking to the document\n available_info.setdefault(layer[INFO.SHORT_NAME],\n layer[INFO.UUID])\n available_short_names.append(layer[INFO.SHORT_NAME])\n if layer[INFO.UUID] in selected_uuids:\n selected_short_names.append(layer[INFO.SHORT_NAME])\n\n self.ui.layer_name_edit.textEdited.connect(self._validate)\n self.accepted.connect(self._create_algebraic)\n for idx, combo in enumerate(self.layer_combos):\n if len(selected_short_names) > idx:\n a_select = selected_short_names[idx]\n elif len(available_info) > idx:\n a_select = available_short_names[idx]\n else:\n a_select = None\n self._init_combo(combo, available_info, a_select)\n combo.currentIndexChanged.connect(self._validate)\n\n for op_name in PRESET_OPERATIONS.keys():\n self.ui.operation_combo.addItem(op_name)\n self.ui.operation_combo.addItem(CUSTOM_OP_NAME)\n self.ui.operation_combo.setCurrentIndex(0)\n self.ui.operation_combo.currentIndexChanged.connect(self._set_operation)\n self._custom_formula = PRESET_OPERATIONS[DIFF_OP_NAME][0]\n\n self._set_operation()\n self._validate()\n\n @property\n def layer_combos(self):\n return (\n self.ui.x_combo,\n self.ui.y_combo,\n self.ui.z_combo,\n )\n\n @property\n def layer_combos_names(self):\n return zip(\n ('x', 'y', 'z'),\n self.layer_combos,\n )\n\n def _set_operation(self, *args, **kwargs):\n was_custom = self.ui.operations_text.isEnabled()\n if was_custom:\n self._custom_formula = self.ui.operations_text.toPlainText()\n\n operation = self.ui.operation_combo.currentText()\n op_formula, num_layers = PRESET_OPERATIONS.get(operation, (None, 3))\n if op_formula is None:\n op_formula = self._custom_formula\n self.ui.operations_text.setDisabled(False)\n else:\n self.ui.operations_text.setDisabled(True)\n self.ui.operations_text.setPlainText(op_formula)\n\n # enable only the layer combos we need\n for idx, combo in enumerate(self.layer_combos):\n combo.setDisabled(idx >= num_layers)\n\n def _validate(self, *args, **kwargs):\n valid_name = bool(self.ui.layer_name_edit.text())\n ok_button = self.ui.buttons.button(QtGui.QDialogButtonBox.Ok)\n if valid_name:\n ok_button.setDisabled(False)\n else:\n ok_button.setDisabled(True)\n\n def _init_combo(self, c, available_info, select_uuid):\n for idx, (short_name, uuid) in enumerate(available_info.items()):\n c.addItem(short_name, uuid)\n if select_uuid and short_name == select_uuid:\n c.setCurrentIndex(idx)\n\n def _create_algebraic(self):\n new_name = self.ui.layer_name_edit.text()\n namespace = {}\n for name, combo in self.layer_combos_names:\n namespace[name] = combo.itemData(combo.currentIndex())\n operations = self.ui.operations_text.toPlainText()\n info = {\n INFO.SHORT_NAME: new_name,\n }\n\n self.doc.create_algebraic_composite(operations=operations, namespace=namespace, info=info)\n\n def done(self, r):\n if r == QtGui.QDialog.Accepted:\n operation = self.ui.operation_combo.currentText()\n\n status_title = ''\n status_text = ''\n if operation in [DIFF_OP_NAME, NDI_OP_NAME]:\n namespace = {}\n for name, combo in self.layer_combos_names:\n namespace[name] = combo.itemData(combo.currentIndex())\n x = self.doc[namespace['x']]\n y = self.doc[namespace['y']]\n if namespace['x'] == namespace['y']:\n status_title = 'Error: Bad layer selection'\n status_text = 'Error: Subtracting a layer from itself'\n elif x[INFO.STANDARD_NAME] != y[INFO.STANDARD_NAME]:\n status_title = 'Warning: Bad layer selection'\n status_text = 'Warning: Subtracting layers with different units'\n\n try:\n operations = self.ui.operations_text.toPlainText()\n ops_ast = ast.parse(operations, mode='exec')\n ops = compile(ops_ast, '', 'exec')\n result_name = ops_ast.body[-1].targets[0].id\n except (AttributeError, KeyError, IndexError, SyntaxError):\n ret_button = QtGui.QMessageBox.critical(\n self,\n 'Error: Syntax Error',\n 'Error: Syntax Error in Operations code. Must be valid Python 3 syntax.',\n QtGui.QMessageBox.Ok,\n )\n return\n\n if status_title.startswith(\"Warning\"):\n msg_box = QtGui.QMessageBox(\n QtGui.QMessageBox.Warning,\n status_title,\n status_text,\n QtGui.QMessageBox.No | QtGui.QMessageBox.Yes,\n self,\n )\n msg_box.setInformativeText(\"Do you want to create the layer anyway?\")\n msg_box.setDefaultButton(QtGui.QMessageBox.No)\n ret = msg_box.exec_()\n if ret == QtGui.QMessageBox.No:\n return\n elif status_title.startswith('Error'):\n ret_button = QtGui.QMessageBox.critical(\n self,\n status_title,\n status_text,\n QtGui.QMessageBox.Ok,\n )\n return\n\n return super(CreateAlgebraicDialog, self).done(r)\n","sub_path":"sift/view/create_algebraic.py","file_name":"create_algebraic.py","file_ext":"py","file_size_in_byte":7182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"156106343","text":"About = \"\"\"\n___________________________________________\nInstituto Tecnologico de Costa Rica *\nComputer Engineering *\nTutorías taller de programación *\n *\nMilton Villegas Lemus * \nEjemplo de música en Windows *\nJuego destrucción de misiles *\n *\nSantiago Gamboa Ramírez *\nfecha de emision: 05/03/2018 *\nVersion: 1.0.0 *\n____________________________________________*\n\"\"\"\n\n# _____________________________\n# __________/BIBLIOTECAS\n\nimport os # ruta = os.path.join('')\nimport time # time.sleep(x)\nimport random # random.randint(a, b)\n\nfrom tkinter import W, NO, Tk, Toplevel, Entry, Button, Label, Canvas, PhotoImage, messagebox\nfrom threading import Thread # p.start()\n\n# Si winsound no se logra importar, se utiliza una alternativa\n# para sistemas GNU/Linux.\ntry:\n import winsound\nexcept ImportError:\n import shlex\n from subprocess import Popen\n\n def reproducir(ruta):\n if reproducir.Proceso is not None:\n reproducir.Proceso.kill()\n\n if ruta is not None:\n reproducir.Proceso = Popen(f'aplay {shlex.quote(ruta)}', shell=True)\n else:\n reproducir.Proceso = None\n\n reproducir.Proceso = None\nelse:\n def reproducir(ruta):\n winsound.PlaySound(ruta, winsound.SND_ASYNC)\n\n# ____________________________\n# __________/Función para cargar imágenes\ndef cargar_img(Nombre):\n return PhotoImage(file=os.path.join('img', Nombre))\n\n# ____________________________\n# __________/Ventana principal\nRoot = Tk()\nRoot.title('Taller Tkinter')\nRoot.minsize(800, 600)\nRoot.resizable(width = NO, height = NO)\n\n# Se recoloca aquí para que no se recargue la imagen cada vez\n# que se crea un misil.\nImagenMisil = cargar_img('bomba.gif')\n\n# ______________________________\n# __________/Se crea un lienzo para objetos\nCRoot = Canvas(Root, width = 800, height = 600, bg = 'white')\nCRoot.place(x = 0, y = 0)\n\n# ______________________________\n# __________/Se crea una etiqueta con un título\nLabel(CRoot, text = About, font = ('Agency FB', 12), bg = 'white', fg = 'black').place(x = 490, y = 10)\n\n\n# _____________________________________\n# __________/Se crea una entrada de texto y titulo\nLabel(CRoot, text = \"Ingrese su nombre:\", font = ('Agency FB', 14), bg = 'white', fg = 'green').place(x = 560, y = 400)\nENombre = Entry(CRoot, width = 20, font = ('Agency FB', 14))\nENombre.place(x = 560, y = 425)\n\n# ____________________________\n# __________/Cargar una imagen\nLogo = cargar_img(\"logo.gif\")\nImagenCancion = Label(CRoot, image = Logo, bg = 'white')\nImagenCancion.place(x = 20, y = 10)\n\n# ____________________________\n# __________/Función para el botón mute\ndef off():\n reproducir(None)\n\n# ________________________________________________________________\n# __________/Función para reproducir una canción y cambiar la imagen del label\ndef play(Id):\n global Logo, ImagenCancion\n\n off()\n Logo = cargar_img(f'img{Id}.gif')\n ImagenCancion.config(image = Logo)\n\ndef acerca_de():\n Root.withdraw()\n\n About = Toplevel()\n About.title('Acerca de')\n About.resizable(width = NO, height = NO)\n\n def retroceder():\n About.destroy()\n Root.deiconify()\n reproducir(None)\n\n Imagen = cargar_img('foto.gif')\n EtiquetaFoto = Label(About, image = Imagen)\n EtiquetaFoto.grid(row = 0, rowspan = 5)\n EtiquetaFoto.photo = Imagen\n\n Button(About, text = 'Atrás', command = retroceder).grid(row = 0, column = 1)\n\n def info(Fila, Clave, Valor):\n Label(About, text = Clave).grid(row = Fila, column = 1, sticky = W)\n Label(About, text = Valor).grid(row = Fila, column = 2, sticky = W) \n\n info(1, 'Nombre', 'Alejandro Soto Chacón')\n info(2, 'Cédula', '118140028')\n info(3, 'Carné', '2019008164')\n info(4, 'Fecha de nacimiento', '2001-06-20')\n\n reproducir('musica.wav')\n\n# ____________________________\n# __________/Crear una nueva ventana\ndef ventana_juego(NombreJugador):\n # Esconder la pantalla sin destruirla\n Root.withdraw()\n\n # Pantalla secundaria\n Juego = Toplevel()\n Juego.title('EJEMPLO')\n Juego.minsize(800, 600)\n Juego.resizable(width = NO, height = NO)\n\n CJuego = Canvas(Juego, width = 800, height = 600, bg='light blue')\n CJuego.place(x = 0, y = 0)\n\n FondoImg = cargar_img('fondo1.gif')\n FJuego = Label(CJuego, image = FondoImg, bg = 'light blue')\n FJuego.photo = FondoImg\n FJuego.place(x = 0, y = 0)\n\n Label(CJuego, text = \"Jugador: \" + NombreJugador, font = ('Agency FB', 20), fg = 'light blue', bg = 'white').place(x = 10, y = 10)\n\n # ___________________________________\n # __________/Función que ejecuta 15 veces el hilo\n def crear_misil():\n global BaseDestruida, ImagenMisil\n\n Misil = Label(CJuego, image = ImagenMisil, bg = 'light blue')\n\n MisilDestruido = False\n VelocidadX = random.randint(-1, 1) / 5\n AceleracionY = random.randint(1, 5)\n PosicionX = random.randint(0, 800)\n PosicionY = 0\n\n Misil.place(x = PosicionX, y = PosicionY)\n\n # ______________________________________\n # __________/Capturar un click sobre el label bomba\n def destruir(_):\n nonlocal MisilDestruido\n MisilDestruido = True\n\n Misil.bind('', destruir)\n\n # ____________________________\n # __________/Función que mueve un Misil\n def mover_misil_aux(PosicionX, PosicionY, Ciclo):\n global BaseDestruida\n nonlocal MisilDestruido, VelocidadX\n\n if PosicionX < 20 or PosicionX > 780:\n VelocidadX = -VelocidadX\n\n Misil.place(x = int(PosicionX), y = PosicionY)\n time.sleep(2.5e-3 + 0.1 / (1 + Ciclo * AceleracionY))\n \n if PosicionY > 490:\n MisilDestruido = BaseDestruida = True\n elif not BaseDestruida and not MisilDestruido:\n mover_misil_aux(PosicionX + VelocidadX, PosicionY + 1, Ciclo + 1)\n\n mover_misil_aux(PosicionX, PosicionY, 0)\n Misil.destroy()\n \n if not BaseDestruida:\n Thread(target = crear_misil).start()\n crear_misil()\n\n # ___________________________________\n # __________/Función que es llamada con el hilo\n def ataque():\n global BaseDestruida\n\n BaseDestruida = False\n crear_misil()\n\n print(\"Mala suerte, has perdido\")\n if messagebox.askyesno(\"Confirmar\", \"Jugar de nuevo?\"):\n ataque()\n else:\n back()\n\n # _____________________________\n # __________/Volver a la ventana principal\n def back():\n Juego.destroy()\n Root.deiconify()\n\n # ____________________________\n # __________/Botón volver pantalla Juego\n Button(CJuego, text = 'Atras', command = back, bg = 'white', fg = 'green').place(x = 100, y = 560)\n\n # __________________________________________\n # __________/Se crea un hilo para controlar los misiles\n Thread(target = ataque).start()\n\n# ____________________________\n# __________/Función del botón Juego\ndef empezar_juego():\n # Obtener el nombre de un entry\n nombre = str(ENombre.get())\n ventana_juego(nombre)\n\n# ____________________________\n# __________/Botones de ventana principal\n\ndef boton_principal(X, Y, Texto, Comando):\n Button(CRoot, text = Texto, command = Comando, bg = 'green', fg = 'white').place(x = X, y = Y)\n\nboton_principal(560, 470, 'Juego', empezar_juego)\nboton_principal(560, 550, 'Acerca de', acerca_de)\nboton_principal(100, 550, 'Canción 1', lambda: play(1))\nboton_principal(200, 550, 'Canción 2', lambda: play(2))\nboton_principal(300, 550, 'Parar música', off)\n\nRoot.mainloop()\n","sub_path":"Ejemplo_Tkinter.py","file_name":"Ejemplo_Tkinter.py","file_ext":"py","file_size_in_byte":8087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"414745014","text":"#!/usr/bin/env python3\n\nimport os\nimport sys\nimport subprocess\nimport shutil\nfrom collections import OrderedDict\n\nimport urllib.request\n\ncurrent_path = os.path.abspath(os.curdir)\n\n\n# Repositories -------------------------------------------------------------------------------------\n\n# name, (url, recursive clone, develop)\nrepos = [\n # HDL\n (\"migen\", (\"https://github.com/m-labs/\", True, True)),\n\n # LiteX SoC builder\n (\"pythondata-software-compiler_rt\", (\"https://github.com/litex-hub/\", False, True)),\n (\"litex\", (\"https://github.com/enjoy-digital/\", False, True)),\n\n # LiteX cores ecosystem\n (\"liteeth\", (\"https://github.com/enjoy-digital/\", False, True)),\n (\"litedram\", (\"https://github.com/enjoy-digital/\", False, True)),\n (\"litepcie\", (\"https://github.com/enjoy-digital/\", False, True)),\n (\"litesata\", (\"https://github.com/enjoy-digital/\", False, True)),\n (\"litesdcard\", (\"https://github.com/enjoy-digital/\", False, True)),\n (\"liteiclink\", (\"https://github.com/enjoy-digital/\", False, True)),\n (\"litevideo\", (\"https://github.com/enjoy-digital/\", False, True)),\n (\"litescope\", (\"https://github.com/enjoy-digital/\", False, True)),\n (\"litejesd204b\", (\"https://github.com/enjoy-digital/\", False, True)),\n (\"litespi\", (\"https://github.com/litex-hub/\", False, True)),\n\n # LiteX boards support\n (\"litex-boards\", (\"https://github.com/litex-hub/\", False, True)),\n\n # Optional LiteX data\n (\"pythondata-cpu-blackparrot\", (\"https://github.com/litex-hub/\", False, True)),\n (\"pythondata-cpu-mor1kx\", (\"https://github.com/litex-hub/\", False, True)),\n (\"pythondata-cpu-lm32\", (\"https://github.com/litex-hub/\", False, True)),\n (\"pythondata-cpu-microwatt\", (\"https://github.com/litex-hub/\", False, True)),\n (\"pythondata-cpu-picorv32\", (\"https://github.com/litex-hub/\", False, True)),\n (\"pythondata-cpu-rocket\", (\"https://github.com/litex-hub/\", False, True)),\n (\"pythondata-cpu-vexriscv\", (\"https://github.com/litex-hub/\", False, True)),\n (\"pythondata-misc-tapcfg\", (\"https://github.com/litex-hub/\", False, True)),\n]\nrepos = OrderedDict(repos)\n\n# RISC-V toolchain download ------------------------------------------------------------------------\n\ndef sifive_riscv_download():\n base_url = \"https://static.dev.sifive.com/dev-tools/\"\n base_file = \"riscv64-unknown-elf-gcc-8.3.0-2019.08.0-x86_64-\"\n\n # Windows\n if (sys.platform.startswith(\"win\") or sys.platform.startswith(\"cygwin\")):\n end_file = \"w64-mingw32.zip\"\n # Linux\n elif sys.platform.startswith(\"linux\"):\n end_file = \"linux-ubuntu14.tar.gz\"\n # Mac OS\n elif sys.platform.startswith(\"darwin\"):\n end_file = \"apple-darwin.tar.gz\"\n else:\n raise NotImplementedError(sys.platform)\n fn = base_file + end_file\n\n if not os.path.exists(fn):\n url = base_url + fn\n print(\"Downloading\", url, \"to\", fn)\n urllib.request.urlretrieve(url, fn)\n else:\n print(\"Using existing file\", fn)\n\n print(\"Extracting\", fn)\n shutil.unpack_archive(fn)\n\n# Setup --------------------------------------------------------------------------------------------\n\nif os.environ.get(\"TRAVIS\", \"\") == \"true\":\n # Ignore `ssl.SSLCertVerificationError` on CI.\n import ssl\n ssl._create_default_https_context = ssl._create_unverified_context\n\nif len(sys.argv) < 2:\n print(\"Available commands:\")\n print(\"- init\")\n print(\"- install (add --user to install to user directory)\")\n print(\"- update\")\n print(\"- gcc\")\n exit()\n\n# Repositories cloning\nif \"init\" in sys.argv[1:]:\n os.chdir(os.path.join(current_path))\n for name in repos.keys():\n url, need_recursive, need_develop = repos[name]\n # clone repo (recursive if needed)\n print(\"[cloning \" + name + \"]...\")\n full_url = url + name\n opts = \"--recursive\" if need_recursive else \"\"\n subprocess.check_call(\n \"git clone \" + full_url + \" \" + opts,\n shell=True)\n\n# Repositories installation\nif \"install\" in sys.argv[1:]:\n for name in repos.keys():\n url, need_recursive, need_develop = repos[name]\n # develop if needed\n print(\"[installing \" + name + \"]...\")\n if need_develop:\n os.chdir(os.path.join(current_path, name))\n if \"--user\" in sys.argv[1:]:\n subprocess.check_call(\n \"python3 setup.py develop --user\",\n shell=True)\n else:\n subprocess.check_call(\n \"python3 setup.py develop\",\n shell=True)\n os.chdir(os.path.join(current_path))\n\n if \"--user\" in sys.argv[1:]:\n if \".local/bin\" not in os.environ.get(\"PATH\", \"\"):\n print(\"Make sure that ~/.local/bin is in your PATH\")\n print(\"export PATH=$PATH:~/.local/bin\")\n\n# Repositories update\nif \"update\" in sys.argv[1:]:\n for name in repos.keys():\n # update\n print(\"[updating \" + name + \"]...\")\n os.chdir(os.path.join(current_path, name))\n subprocess.check_call(\n \"git pull --ff-only\",\n shell=True)\n os.chdir(os.path.join(current_path))\n\n# RISC-V GCC installation\nif \"gcc\" in sys.argv[1:]:\n sifive_riscv_download()\n if \"riscv64\" not in os.environ.get(\"PATH\", \"\"):\n print(\"Make sure that the downloaded RISC-V compiler is in your $PATH.\")\n print(\"export PATH=$PATH:$(echo $PWD/riscv64-*/bin/)\")\n","sub_path":"litex_setup.py","file_name":"litex_setup.py","file_ext":"py","file_size_in_byte":5532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"427897667","text":"import os\r\nimport mysql.connector\r\nfrom Aluno import *\r\nfrom Professor import *\r\nfrom Departamento import *\r\n\r\n#Declaração dos tipos de usuario\r\naluno = Aluno()\r\nprofessor = Professor()\r\ndepartamento = Departamento()\r\n\r\n#Escolha do tipo de usuário\r\nos.system('cls')\r\nopt = 0\r\nfim = False\r\nwhile((opt < 1 or opt > 3) and not fim):\r\n print(\"Gerência acadêmica\")\r\n print(\"Selecione o seu tipo de usuário:\")\r\n print(\"1 | Aluno(a)\")\r\n print(\"2 | Professor(a)\")\r\n print(\"3 | Coordenador(a) de Departamento\")\r\n print(\"0 | Sair\\n\")\r\n opt = int(input())\r\n\r\n\t#Aluno\r\n if(opt == 1):\r\n os.system('cls')\r\n aluno.telaAlunoLogar()\r\n\r\n #Professor\r\n elif(opt == 2):\r\n os.system('cls')\r\n professor.telaProfessorLogar()\r\n\r\n #Coordenador\r\n elif(opt == 3): #Completar opção do departamento\r\n os.system('cls')\r\n departamento.telaDepartamentoLogar()\r\n\r\n elif(opt == 0):\r\n fim = True\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"11737500","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\n\nimport asyncio\nfrom whoosh.fields import *\nfrom whoosh.index import create_in\nfrom whoosh.index import open_dir\n\nfrom whoosh.fields import *\nfrom jieba.analyse import ChineseAnalyzer\nfrom whoosh.qparser import QueryParser\nimport io, os, sys, time\nsys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')\nanalyser = ChineseAnalyzer()\nschema = Schema(full_line=TEXT(stored=True, analyzer=analyser))\nix = create_in(\"shegongku\", schema=schema, indexname='allin1line')\ndef traverseFile(root):\n flist = []\n for f in os.listdir(root):\n f_path = os.path.join(root, f)\n if os.path.isfile(f_path):\n flist.append(f_path)\n else:\n flist += traverseFile(f_path)\n return flist\n\n# 处理数据文件,每个文件每一行,加进去\nwriter1 = ix.writer()\nfor fn in traverseFile(\"shegongku/db\"):\n with open(fn, 'r', encoding='utf-8') as f:\n #print(fn, \"...\")\n lines=0\n while True:\n line1 = f.readline()\n if line1:\n writer1.add_document(full_line=line1)\n lines+=1;\n else:\n break\n print(fn, lines, \"added\")\nwriter1.commit()\nprint(\"index finished\")\n\nindex1 = open_dir(\"shegongku\", indexname='allin1line')\nparser1 = QueryParser(\"full_line\", index1.schema)\n\n\nasync def handle_echo(reader, writer):\n key1 = await reader.read(1024)\n addr = writer.get_extra_info('peername')\n print(f\"Received {key1!r} from {addr!r}\")\n with index1.searcher() as searcher:\n print(\"key=\", key1.decode())\n myquery = parser1.parse(key1)\n results1 = searcher.search(myquery, limit=2000)\n str = \"\"\n for result in results1:\n str += \"
  • \" + dict(result)['full_line'] + \"
  • \"\n writer.write(str.encode())\n await writer.drain()\n print(str)\n print(\"key end:\", key1.decode())\n \n writer.close()\n\n\nasync def main():\n server = await asyncio.start_server(handle_echo, '127.0.0.1', 8088)\n addr = server.sockets[0].getsockname()\n print(f'Serving on {addr}')\n async with server:\n await server.serve_forever()\n\n\nasyncio.run(main())\n","sub_path":"201600301212-林奎良/whoosh/woosh-cgi/w4server.py","file_name":"w4server.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"486312368","text":"import requests\nimport csv\nimport time\nimport urllib3\nimport argparse\nimport dsFunc\n\ninst = input('To edit production server, enter the name of the secrets file: ')\nsecrets = dsFunc.instSelect(inst)\n\nbaseURL = secrets.baseURL\nemail = secrets.email\npassword = secrets.password\nfilePath = secrets.filePath\nverify = secrets.verify\nskipColl = secrets.skipColl\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-1', '--key', help='the first key to be output. '\n 'optional - if not provided, the script will ask for '\n 'input')\nparser.add_argument('-2', '--key2', help='the second key to be output. '\n 'optional - if not provided, the script will ask for '\n 'input')\nparser.add_argument('-i', '--handle', help='handle of the community to '\n 'retreive. optional - if not provided, the script will '\n 'ask for input')\nargs = parser.parse_args()\n\nif args.key:\n key = args.key\nelse:\n key = input('Enter first key: ')\nif args.key2:\n key2 = args.key2\nelse:\n key2 = input('Enter second key: ')\nif args.handle:\n handle = args.handle\nelse:\n handle = input('Enter community handle: ')\n\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\nstartTime = time.time()\ndata = {'email': email, 'password': password}\nheader = {'content-type': 'application/json', 'accept': 'application/json'}\nsession = requests.post(baseURL + '/rest/login', headers=header, verify=verify,\n params=data).cookies['JSESSIONID']\ncookies = {'JSESSIONID': session}\n\n\nstatus = requests.get(baseURL + '/rest/status', headers=header,\n cookies=cookies, verify=verify).json()\nuserFullName = status['fullname']\nprint('authenticated', userFullName)\n\nendpoint = baseURL + '/rest/handle/' + handle\ncommunity = requests.get(endpoint, headers=header, cookies=cookies,\n verify=verify).json()\ncommunityID = community['uuid']\n\nitemList = []\nendpoint = baseURL + '/rest/communities'\ncollections = requests.get(baseURL + '/rest/communities/' + str(communityID)\n + '/collections', headers=header, cookies=cookies,\n verify=verify).json()\nfor j in range(0, len(collections)):\n collectionID = collections[j]['uuid']\n print(collectionID)\n if collectionID not in skipColl:\n offset = 0\n items = ''\n while items != []:\n items = requests.get(baseURL + '/rest/collections/'\n + str(collectionID)\n + '/items?limit=200&offset=' + str(offset),\n headers=header, cookies=cookies,\n verify=verify)\n while items.status_code != 200:\n time.sleep(5)\n items = requests.get(baseURL + '/rest/collections/'\n + str(collectionID)\n + '/items?limit=200&offset='\n + str(offset), headers=header,\n cookies=cookies, verify=verify)\n items = items.json()\n for k in range(0, len(items)):\n itemID = items[k]['uuid']\n itemList.append(itemID)\n offset = offset + 200\n print(offset)\n\ndsFunc.elapsedTime(startTime, 'Item list creation time')\n\nvalueList = []\nfor number, itemID in enumerate(itemList):\n itemsRemaining = len(itemList) - number\n print('Items remaining: ', itemsRemaining, 'ItemID: ', itemID)\n metadata = requests.get(baseURL + '/rest/items/' + str(itemID)\n + '/metadata', headers=header, cookies=cookies,\n verify=verify).json()\n itemTuple = (itemID,)\n tupleValue1 = ''\n tupleValue2 = ''\n for l in range(0, len(metadata)):\n if metadata[l]['key'] == key:\n metadataValue = metadata[l]['value']\n tupleValue1 = metadataValue\n if metadata[l]['key'] == key2:\n metadataValue = metadata[l]['value']\n tupleValue2 = metadataValue\n itemTuple = itemTuple + (tupleValue1, tupleValue2)\n valueList.append(itemTuple)\n print(itemTuple)\nprint(valueList)\n\ndsFunc.elapsedTime(startTime, 'Value list creation time')\n\nf = csv.writer(open(filePath + key + '-' + key2 + 'Values.csv', 'w'))\nf.writerow(['itemID'] + [key] + [key2])\nfor i in range(0, len(valueList)):\n f.writerow([valueList[i][0]] + [valueList[i][1]] + [valueList[i][2]])\n\nlogout = requests.post(baseURL + '/rest/logout', headers=header,\n cookies=cookies, verify=verify)\n\n# print script run time\ndsFunc.elapsedTime(startTime, 'Script run time')\n","sub_path":"compareTwoKeysInCommunity.py","file_name":"compareTwoKeysInCommunity.py","file_ext":"py","file_size_in_byte":4763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"232471706","text":"from flask import Flask, render_template, request, jsonify, send_from_directory\nfrom pymongo import MongoClient\nfrom bson.objectid import ObjectId\nfrom flask_cors import CORS\nimport yaml\nimport os\n\t\napp = Flask(__name__, template_folder='public')\nconfig = yaml.load(open('database.yaml'))\nclient = MongoClient(config['uri'])\ndb = client['flask_app']\nCORS(app)\n\nROOT_PATH = os.path.dirname(os.path.realpath(__file__))\nPUBLIC_PATH = os.path.join(ROOT_PATH, 'angular1')\nAPI_VERSION= 'v1'\nAPI_SLUG= '/api/'\n\n\n@app.route(API_SLUG+API_VERSION+'/ping', methods=['GET'])\ndef dummy_endpoint():\n \"\"\" Testing endpoint \"\"\"\n return jsonify({'status': 'success'})\n\n@app.errorhandler(404)\ndef not_found(error):\n \"\"\" error handler \"\"\"\n return jsonify({'status': '404'}), 404\n\n\t\n@app.route('/')\ndef index():\n \"\"\" static files serve \"\"\"\n return send_from_directory(PUBLIC_PATH, 'index.html')\n\t\n@app.route('/')\ndef static_proxy(path):\n \"\"\" static folder serve \"\"\"\n file_name = path.split('/')[-1]\n dir_name = os.path.join(PUBLIC_PATH, '/'.join(path.split('/')[:-1]))\n return send_from_directory(dir_name, file_name)\n\t\n\t\n@app.route(API_SLUG+API_VERSION+'/data', methods=['POST', 'GET'])\ndef data():\n \n # POST a data to database\n if request.method == 'POST':\n body = request.json\n first_name = body['first_name']\n last_name = body['last_name']\n\n # db.users.insert_one({\n db['users'].insert_one({\n \"first_name\": first_name,\n \"last_name\": last_name\n })\n return jsonify({\n\t\t\t'message': 'Kayıt Başarılı',\n 'status': 'success',\n 'first_name': first_name,\n 'last_name': last_name\n })\n \n # GET all data from database\n if request.method == 'GET':\n allData = db['users'].find()\n dataJson = []\n for data in allData:\n id = data['_id']\n first_name = data['first_name']\n last_name = data['last_name']\n dataDict = {\n 'id': str(id),\n 'first_name': first_name,\n 'last_name': last_name\n }\n dataJson.append(dataDict)\n print(dataJson)\n return jsonify(dataJson)\n\n@app.route(API_SLUG+API_VERSION+'/data/', methods=['GET', 'DELETE', 'PUT'])\ndef onedata(id):\n\n # GET a specific data by id\n if request.method == 'GET':\n data = db['users'].find_one({'_id': ObjectId(id)})\n id = data['_id']\n first_name = data['first_name']\n last_name = data['last_name']\n dataDict = {\n 'id': str(id),\n 'first_name': first_name,\n 'last_name': last_name\n }\n print(dataDict)\n return jsonify(dataDict)\n \n # DELETE a data\n if request.method == 'DELETE':\n db['users'].delete_many({'_id': ObjectId(id)})\n print('\\n # Deletion successful # \\n')\n return jsonify({\n\t\t'status': 'success',\n\t\t'message': 'Kullanıcı silindi'\n\t\t})\n\n # UPDATE a data by id\n if request.method == 'PUT':\n body = request.json\n first_name = body['first_name']\n last_name = body['last_name']\n\n db['users'].update_one(\n {'_id': ObjectId(id)},\n {\n \"$set\": {\n \"first_name\":first_name,\n \"last_name\":last_name\n }\n }\n )\n\n print('\\n # Update successful # \\n')\n return jsonify({'status': 'success', 'message': 'Güncelleme başarılı'})\n\nif __name__ == '__main__':\n app.debug = True\n app.run()\n","sub_path":"Flask/angular1.py","file_name":"angular1.py","file_ext":"py","file_size_in_byte":3610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"275688115","text":"import re \nimport sys\nimport base64\nimport lxml\nimport os\nfrom lxml import etree\nimport csv\n\ndef main():\n xtree = etree.parse(sys.argv[1]).getroot()\n# print(xtree)\n# print(etree.tostring(xtree, pretty_print=True))\n for email in xtree.findall(\".//{http://schemas.microsoft.com/Contact/Extended/MSWABMAPI}PropTag0x66001102\"):\n# print(etree.text_content(email))\n# print(etree.strip_tags(etree.dump(email)))\n# print(etree.dump(email))\n# print(email.text)\n group_content = base64.b64decode(email.text).decode('utf-16')\n# print(group_content)\n contacts = []\n for path in group_content.split('/PATH:\"')[1:]:\n contact_file_path = path.split('\"')[0]\n contact_file_path = contact_file_path.replace('\\\\', '/').replace(\"C:/Users/user/Contacts/\", './Contacts/')\n print(contact_file_path)\n try:\n ctree = etree.parse(contact_file_path).getroot()\n# print(etree.tostring(ctree, pretty_print=True))\n# print(ctree)\n# print(ctrs)\n#{http://schemas.microsoft.com/Contact}contact\n# for n in ctree.findall(\".//{http://schemas.microsoft.com/Contact}c:EmailAdd:\n addrz = [x.text for x in ctree.findall(\".//{http://schemas.microsoft.com/Contact}Address\")]\n namez = [x.text for x in ctree.findall(\".//{http://schemas.microsoft.com/Contact}FormattedName\")]\n\n contacts.append(list(zip(addrz, namez))[0])\n\n os.unlink(contact_file_path)\n except Exception as e:\n print(str(e))\n print(contacts)\n with open(\"outputs/\"+os.path.basename(sys.argv[1])+'.csv', mode='a') as outhandle:\n csvout = csv.writer(outhandle)\n for contact in contacts:\n csvout.writerow(contact)\n\n# print(\"outputs/\"+os.path.basename(sys.argv[1])+'.csv')\n\n \n \n# print(etree.dump(email))\n# for name in xtree.iter():\n# print(dir(name.tag))\n# print(name)\n# print(name.tag)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"parse_group_files.py","file_name":"parse_group_files.py","file_ext":"py","file_size_in_byte":2119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"325972695","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"bphAnalysis\")\n\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(1000) )\nprocess.load(\"Configuration.Geometry.GeometryRecoDB_cff\")\nprocess.load(\"Configuration.StandardSequences.MagneticField_cff\")\n\nprocess.load('Configuration.StandardSequences.Services_cff')\nprocess.load('SimGeneral.HepPDTESSource.pythiapdt_cfi')\nprocess.load('FWCore.MessageService.MessageLogger_cfi')\nprocess.load('Configuration.EventContent.EventContent_cff')\nprocess.load('Configuration.StandardSequences.GeometryRecoDB_cff')\nprocess.load('Configuration.StandardSequences.MagneticField_AutoFromDBCurrent_cff')\nprocess.load('Configuration.StandardSequences.EndOfProcess_cff')\nprocess.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_condDBv2_cff')\nprocess.load(\"TrackingTools/TransientTrack/TransientTrackBuilder_cfi\")\n\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 1\nprocess.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) )\nprocess.options.allowUnscheduled = cms.untracked.bool(True)\n\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring('file:/lustre/cmswork/abragagn/store/data/Run2017F/Charmonium/MINIAOD/31Mar2018-v1/90000/58FBECAC-9137-E811-83C4-003048F34A5E.root')\n)\n\nfrom Configuration.AlCa.GlobalTag_condDBv2 import GlobalTag\n#process.GlobalTag = GlobalTag(process.GlobalTag, '94X_dataRun2_ReReco_EOY17_v2', '')\nprocess.GlobalTag = GlobalTag(process.GlobalTag, 'auto:run2_data', '')\n\n#from PhysicsTools.PatAlgos.tools.coreTools import runOnData\n#runOnData( process, outputModules = [] )\n\nfrom RecoEgamma.EgammaTools.EgammaPostRecoTools import setupEgammaPostRecoSeq\nsetupEgammaPostRecoSeq(process,\n runEnergyCorrections=True,\n era='2017-Nov17ReReco')\n\n### vtxTagInfo\n\nprocess.load('RecoBTag/SoftLepton/softLepton_cff')\n#process.load('RecoBTag/SoftLepton/softPFMuonTagInfos_cfi')\n#process.load('RecoBTag/SoftLepton/softPFElectronTagInfos_cfi')\nprocess.load('RecoBTag/SecondaryVertex/pfInclusiveSecondaryVertexFinderTagInfos_cfi')\nprocess.load('RecoBTag/ImpactParameter/pfImpactParameterTagInfos_cfi')\n\n#process.load('RecoBTag/SecondaryVertex/secondaryVertexTagInfos_cfi')\n\nprocess.softPFMuonsTagInfos.primaryVertex = cms.InputTag(\"offlineSlimmedPrimaryVertices\")\nprocess.softPFMuonsTagInfos.jets = cms.InputTag(\"slimmedJets\")\nprocess.softPFMuonsTagInfos.muons = cms.InputTag(\"slimmedMuons\")\n\nprocess.softPFElectronsTagInfos.primaryVertex = cms.InputTag(\"offlineSlimmedPrimaryVertices\")\nprocess.softPFElectronsTagInfos.jets = cms.InputTag(\"slimmedJets\")\nprocess.softPFElectronsTagInfos.electrons = cms.InputTag(\"slimmedElectrons\")\n\nprocess.pfImpactParameterTagInfos.primaryVertex = cms.InputTag(\"offlineSlimmedPrimaryVertices\")\nprocess.pfImpactParameterTagInfos.jets = cms.InputTag(\"slimmedJets\")\nprocess.pfImpactParameterTagInfos.candidates = cms.InputTag(\"packedPFCandidates\")\n\nprocess.tagInfoProd = cms.Sequence(\n process.softPFMuonsTagInfos\n + process.softPFElectronsTagInfos\n + process.pfImpactParameterTagInfos\n * process.pfSecondaryVertexTagInfos\n )\n\n### vtxTagInfo end\n\n\nprocess.pdAnalyzer = cms.EDAnalyzer('PDNtuplizer',\n\n ## optional\n eventList = cms.string('evtlist'),\n verbose = cms.untracked.string('f'),\n evStamp = cms.untracked.string('f'),\n\n ## mandatory\n ## ntuple file name: empty string to drop ntuple filling\n ntuName = cms.untracked.string('ntu.root'),\n ## histogram file name\n histName = cms.untracked.string('his.root'),\n\n labelTrigResults = cms.string('TriggerResults::HLT'), \n# labelTrigEvent = cms.string(''),\n labelTrigObjects = cms.string('slimmedPatTrigger'),\n labelBeamSpot = cms.string('offlineBeamSpot'),\n labelMets = cms.string('slimmedMETs'),\n labelMuons = cms.string('slimmedMuons'),\n labelElectrons = cms.string('slimmedElectrons'),\n labelConversions = cms.string('reducedEgamma:reducedConversions'),\n# labelTaus = cms.string('slimmedTaus'),\n labelTaus = cms.string(''),\n\n labelJets = cms.string('slimmedJets'),\n labelPCCandidates = cms.string('packedPFCandidates::PAT'),\n\n labelGeneralTracks = cms.string(''),\n labelPVertices = cms.string('offlineSlimmedPrimaryVertices'),\n labelSVertices = cms.string('pfSecondaryVertexTagInfos'),\n labelSVTagInfo = cms.string(''),\n labelPUInfo = cms.string(''),\n labelGen = cms.string(''),\n labelGPJ = cms.string(''),\n\n labelCSV = cms.string('pfCombinedInclusiveSecondaryVertexV2BJetTags'),\n labelTCHE = cms.string('trackCountingHighEffBJetTags'),\n labelTags = cms.VPSet(\n cms.PSet( type = cms.string('pfDeepCSVJetTags_probudsg'),\n label = cms.string('pfDeepCSVJetTags:probudsg') ),\n cms.PSet( type = cms.string('pfDeepCSVJetTags_probc'),\n label = cms.string('pfDeepCSVJetTags:probc') ),\n cms.PSet( type = cms.string('pfDeepCSVJetTags_probcc'),\n label = cms.string('pfDeepCSVJetTags:probcc') ),\n cms.PSet( type = cms.string('pfDeepCSVJetTags_probb'),\n label = cms.string('pfDeepCSVJetTags:probb') ),\n cms.PSet( type = cms.string('pfDeepCSVJetTags_probbb'),\n label = cms.string('pfDeepCSVJetTags:probbb') ),\n cms.PSet( type = cms.string('pfDeepFlavourJetTags_probg'),\n label = cms.string('pfDeepFlavourJetTags:probg') ),\n cms.PSet( type = cms.string('pfDeepFlavourJetTags_probuds'),\n label = cms.string('pfDeepFlavourJetTags:probuds') ),\n cms.PSet( type = cms.string('pfDeepFlavourJetTags_probc'),\n label = cms.string('pfDeepFlavourJetTags:probc') ),\n cms.PSet( type = cms.string('pfDeepFlavourJetTags_probb'),\n label = cms.string('pfDeepFlavourJetTags:probb') ),\n cms.PSet( type = cms.string('pfDeepFlavourJetTags_probbb'),\n label = cms.string('pfDeepFlavourJetTags:probbb') ),\n cms.PSet( type = cms.string('pfDeepFlavourJetTags_problepb'),\n label = cms.string('pfDeepFlavourJetTags:problepb') )\n ),\n\n vs = cms.VPSet(\n cms.PSet( type = cms.string('svtK0short'),\n label = cms.string('slimmedKshortVertices::PAT') ),\n cms.PSet( type = cms.string('svtLambda0'),\n label = cms.string('slimmedLambdaVertices::PAT') )\n ),\n vertReco = cms.vstring('svtBuJPsiK','svtBdJPsiKx','svtBsJPsiPhi'),\n\n pvRefitPtMin = cms.double( 0.55 ),\n\n acceptNewTrigPaths = cms.string('f'),\n write_hltlist = cms.string('f'),\n\n selectAssociatedPF = cms.string('f'),\n selectAssociatedTk = cms.string('f'),\n recoverMuonTracks = cms.string('t'),\n writeAllPrimaryVertices = cms.string('t'),\n\n jetPtMin = cms.double( 5.0 ),\n jetEtaMax = cms.double( 2.5 ),\n trkDzMax = cms.double( 0.8 ),\n trkPtMin = cms.double( 0.5 ),\n trkEtaMax = cms.double( 3.0 ),\n dRmatchHLT = cms.double( 0.5 ),\n dPmatchHLT = cms.double( 0.5 ),\n\n\n savedTriggerPaths = cms.vstring(\n '*'\n ),\n\n ## trigger objects to save on ntuple:\n savedTriggerObjects = cms.vstring(\n 'hltJet',\n 'hltMuon',\n 'hltElectron',\n 'hltTrack'\n ),\n\n ## event user info to save on ntuple:\n savedEventInfo = cms.VPSet(\n cms.PSet( type = cms.string('fixedGridRhoFastjetAll'),\n label = cms.string('fixedGridRhoFastjetAll::RECO') ),\n cms.PSet( type = cms.string('fixedGridRhoFastjetAllCalo'),\n label = cms.string('fixedGridRhoFastjetAllCalo::RECO') )\n ),\n\n ## jet user info to save on ntuple:\n savedJetInfo = cms.vstring(\n# 'puBeta*'\n ),\n\n## Electron user info to save on ntuple:\n savedEleInfo = cms.vstring(\n '*'\n )\n\n)\n\n#process.evNumFilter = cms.EDFilter('EvNumFilter',\n# eventList = cms.string('evList')\n#)\n\n#############################################################\n#### PATH definition\n#############################################################\n# Let it run\nprocess.p = cms.Path(\n# process.evNumFilter *\n process.egammaPostRecoSeq *\n process.tagInfoProd *\n process.pdAnalyzer\n)\n\n","sub_path":"cfg_data_mini.py","file_name":"cfg_data_mini.py","file_ext":"py","file_size_in_byte":8230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"137064584","text":"import csv\nimport docx\nfrom docx.enum.section import WD_ORIENT\nfrom docx.shared import Pt\n\ninFile = open('tmp.txt')\ninReader = csv.reader(inFile)\nid_pwds = list(inReader)\n\ndoc = docx.Document()\n\nstyle = doc.styles['Normal']\nfont = style.font\nfont.name = 'MSゴシック'\nfont.size = Pt(24)\n\nlistStyle = doc.styles['List']\nlistFont = listStyle.font\nlistFont.size = Pt(34)\n\nfootStyle = doc.styles['List 2']\nfootFont = footStyle.font\nfootFont.size = Pt(20)\n\nsection = doc.sections[-1]\nsection.orientation = WD_ORIENT.LANDSCAPE\n\nnew_width, new_height = section.page_height, section.page_width\nsection.orientation = WD_ORIENT.LANDSCAPE\nsection.page_width = new_width\nsection.page_height = new_height\n\nfor (id, pwd) in id_pwds:\n doc.add_heading('Linux実技試験用 アカウント', 0)\n doc.add_paragraph('以下のユーザー名とパスワードを用いて、Linuxにログインし、実技問題を解答すること。')\n doc.add_paragraph(' ')\n\n p1 = doc.add_paragraph('ユーザー名 ')\n p1.add_run(id).bold = True\n p1.style = listStyle\n\n p2 = doc.add_paragraph('パスワード ')\n p2.add_run(pwd).bold = True\n p2.style = listStyle\n\n doc.add_paragraph('')\n\n pn = doc.add_paragraph()\n pn.add_run('学籍番号 氏名 .').underline = True\n pf = doc.add_paragraph('退室する際は、この用紙を、教員が指定した場所に提出すること。')\n pf.style = footStyle\n\n doc.add_page_break()\n\ndoc.save('id_pass.docx')\n","sub_path":"20180614-pOut.py","file_name":"20180614-pOut.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"609899750","text":"\"\"\"\r\nmiddle 2021-12-07 一维dp\r\n核心思想:选与不选,相邻的不选。\r\nhttps://leetcode-cn.com/problems/house-robber/solution/da-jia-jie-she-by-leetcode-solution/\r\n状态定义:`dp[i]`表示前 `i` 间房屋能偷窃到的最高总金额。\r\n\"\"\"\r\nclass Solution(object):\r\n def rob(self, nums):\r\n if len(nums) == 0:\r\n return 0\r\n elif len(nums)==1:\r\n return nums[0]\r\n elif len(nums)==2:\r\n return max(nums[0],nums[1])\r\n else:\r\n return self.dp_opt(nums) # 7_dynamic_programming\r\n # return self.rec_opt(len(nums)-1,nums) # 递归\r\n # 动态规划\r\n def dp_opt(self,nums):\r\n # dp = np.zeros(len(nums),dtype=int)\r\n dp = [0 for _ in range(len(nums))]\r\n dp[0] = nums[0]\r\n dp[1] = max(nums[0],nums[1])\r\n\r\n for n in range(2,len(nums)):\r\n # 这个n的含义还是不太懂\r\n # opt(n),n包含两种情况——选或者不选,\r\n # 代表到第n步的时候,所有的最优解\r\n A = dp[n-2]+nums[n] # 选这家\r\n B = dp[n-1] # 不选这家\r\n dp[n] = max(A,B)\r\n # print(dp)\r\n return dp[len(nums)-1]\r\n\r\n # 递归\r\n def rec_opt(self,n,nums):\r\n if n==0:\r\n return nums[0]\r\n elif n==1:\r\n return max(nums[0],nums[1])\r\n else:\r\n A = self.rec_opt(n-2,nums)+nums[n]\r\n B = self.rec_opt(n-1,nums)\r\n return max(A,B)\r\n\r\nif __name__ == '__main__':\r\n nums = [2,7,9,3,1]\r\n print(Solution().rob(nums))","sub_path":"07_动态规划/198-打家劫舍.py","file_name":"198-打家劫舍.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"133707631","text":"from integra.tests.common import TransactionCase\n\nclass TestProductIdChange(TransactionCase):\n \"\"\"Test that when an included tax is mapped by a fiscal position, the included tax must be\n subtracted to the price of the product.\n \"\"\"\n\n def setUp(self):\n super(TestProductIdChange, self).setUp()\n self.fiscal_position_model = self.registry('account.fiscal.position')\n self.fiscal_position_tax_model = self.registry('account.fiscal.position.tax')\n self.tax_model = self.registry('account.tax')\n self.pricelist_model = self.registry('product.pricelist')\n self.res_partner_model = self.registry('res.partner')\n self.product_tmpl_model = self.registry('product.template')\n self.product_model = self.registry('product.product')\n self.so_line_model = self.registry('sale.order.line')\n\n def test_product_id_change(self):\n cr, uid = self.cr, self.uid\n pricelist = self.pricelist_model.search(cr, uid, [('name', '=', 'Public Pricelist')])[0]\n partner_id = self.res_partner_model.create(cr, uid, dict(name=\"George\"))\n tax_include_id = self.tax_model.create(cr, uid, dict(name=\"Include tax\",\n type='percent',\n amount='0.21',\n price_include=True))\n tax_exclude_id = self.tax_model.create(cr, uid, dict(name=\"Exclude tax\",\n type='percent',\n amount='0.00'))\n product_tmpl_id = self.product_tmpl_model.create(cr, uid, dict(name=\"Voiture\",\n list_price='121',\n taxes_id=[(6, 0, [tax_include_id])]))\n product_id = self.product_model.create(cr, uid, dict(product_tmpl_id=product_tmpl_id))\n fp_id = self.fiscal_position_model.create(cr, uid, dict(name=\"fiscal position\",\n sequence=1))\n fp_tax_id = self.fiscal_position_tax_model.create(cr, uid, dict(position_id=fp_id,\n tax_src_id=tax_include_id,\n tax_dest_id=tax_exclude_id))\n res = self.so_line_model.product_id_change(cr, uid, [], pricelist, product_id, partner_id=partner_id,\n fiscal_position=fp_id)\n self.assertEquals(100, res['value']['price_unit'], \"The included tax must be subtracted to the price\")\n","sub_path":"integra/addons/sale/tests/test_product_id_change.py","file_name":"test_product_id_change.py","file_ext":"py","file_size_in_byte":2785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"265064623","text":"#!/usr/bin/env python\n#\n# Copyright 2012 Ezox Systems LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"Defines how the assets are combined, compiled, and moved into the static\ndirectory structures.\n\nYou currently must add you coffeescripts to the list in _bundle_app_coffee.\nThis is to ensure files are included in the correct order in the compiled\njavascript.\n\nSome common things to do here:\n Compile coffeescript, uglify the resultant js into demo.js.\n Compile your JST templates into template.js.\n Compile and minify your less into demo.css.\n Combine third party js into one libs.js package.\n\"\"\"\n\nimport logging\n\nfrom os import path\n\nfrom webassets import Bundle\nfrom webassets import Environment\nfrom webassets.script import CommandLineEnvironment\n\nfrom . import BASE_LOCATION\nfrom . import INPUT_FILES\nfrom . import _bundle_images\n\n\ndef _bundle_app_coffee(app, env, debug=False):\n \"\"\"Compile the apps coffeescript and bundle it into demo.js\"\"\"\n COFFEE_PATH = 'coffee'\n scripts = (\n path.join(COFFEE_PATH, 'app.coffee'),\n path.join(COFFEE_PATH, 'menu.coffee'),\n path.join(COFFEE_PATH, 'router.coffee'),\n )\n\n if not scripts:\n return\n\n all_js = Bundle(\n *scripts,\n filters='coffeescript',\n output=path.join('..', '..', app, 'static', 'script', '%s.js' % (app.lower(),))\n )\n env.add(all_js)\n\n if not debug:\n all_js.filters = 'closure_js'\n\n\ndef _bundle_app_jsts(app, env, debug=False):\n \"\"\"Compile and bundle JSTs into template.js\"\"\"\n all_js = Bundle(\n path.join('templates', '**', '*.jst'), debug=False, filters='jst',\n output=path.join('..', '..', app, 'static', 'script', 'template.js')\n )\n env.add(all_js)\n\n if not debug:\n all_js.filters = 'closure_js'\n\n\ndef _bundle_3rd_party_js(app, env, debug=False):\n \"\"\"Combine thrid party js libs into libs.js.\n\n For debug, they are left uncompressed. For production the minified\n versions are used. We suggest using hte vendor supplied minified version\n of each library.\n \"\"\"\n JSPATH = path.join('js', 'lib')\n\n if debug:\n scripts = ()\n if not scripts:\n return\n\n all_js = Bundle(\n *scripts,\n output=path.join('..', '..', app, 'static', 'script', 'libs.js')\n )\n else:\n JSPATH = path.join(JSPATH, 'min')\n\n scripts = ()\n if not scripts:\n return\n\n all_js = Bundle(\n *scripts,\n output=path.join('..', '..', app, 'static', 'script', 'libs.js')\n )\n\n env.add(all_js)\n if debug:\n all_js.build()\n\n\ndef _bundle_3rd_party_css(app, env, debug=False):\n \"\"\"Bundle any thrid party CSS files.\"\"\"\n if debug:\n items = ()\n if not items:\n return\n\n bundle = Bundle(\n *items,\n output=path.join('..', '..', app, 'static', 'css', 'lib.css')\n )\n else:\n items = ()\n if not items:\n return\n\n bundle = Bundle(\n *items,\n output=path.join('..', '..', app, 'static', 'css', 'lib.css')\n )\n\n env.add(bundle)\n\n\ndef _bundle_app_less(app, env, debug):\n \"\"\"Compile and minify demo's less files into demo.css.\"\"\"\n bundle = Bundle(\n Bundle(path.join('less', '%s.less' % (app.lower(),)), filters='less'),\n output=path.join('..', '..', app, 'static', 'css', '%s.css' % (app.lower(),))\n )\n\n if not debug:\n bundle.filters = 'cssmin'\n\n env.add(bundle)\n\n\ndef _setup_env(app, debug=True, cache=True):\n \"\"\"Setup the webassets environment.\"\"\"\n env = Environment(INPUT_FILES, path.join(BASE_LOCATION, app))\n # We use underscore's templates by default.\n env.config['JST_COMPILER'] = '_.template'\n if debug:\n env.config['CLOSURE_COMPRESSOR_OPTIMIZATION'] = 'WHITESPACE_ONLY'\n env.manifest = False\n else:\n env.config['CLOSURE_COMPRESSOR_OPTIMIZATION'] = 'ADVANCED_OPTIMIZATIONS'\n\n env.debug = False\n env.cache = cache\n\n #javascript\n _bundle_app_jsts(app, env, debug)\n _bundle_app_coffee(app, env, debug)\n _bundle_3rd_party_js(app, env, debug)\n\n #css\n _bundle_app_less(app, env, debug)\n _bundle_3rd_party_css(app, env, debug)\n\n #images\n _bundle_images(app, env)\n\n return env\n\n\ndef _load_logger():\n # Setup a logger\n log = logging.getLogger('webassets')\n log.addHandler(logging.StreamHandler())\n log.setLevel(logging.DEBUG)\n return log\n\n\ndef build(app='', debug=True, cache=True):\n env = _setup_env(app, debug, cache)\n log = _load_logger()\n cmdenv = CommandLineEnvironment(env, log)\n\n cmdenv.build()\n\ndef watch(app='', debug=False, cache=False):\n env = _setup_env(app, debug, cache)\n log = _load_logger()\n cmdenv = CommandLineEnvironment(env, log)\n\n cmdenv.watch()\n","sub_path":"skel/local/scripts/assets/app_assets.py","file_name":"app_assets.py","file_ext":"py","file_size_in_byte":5370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"422788899","text":"import pygame, time, random\npygame.init()\n\n#CHANGE THESE VALUES\n\n#If True a user prompt will be run from the console allowing the below variables (excluding patterns) to be changed\nmenuBool = False\n\n#number of columns and rows on the plane - must be Int (Can be diff6erent!)\ncolumns = 10\nrows = 10\n\n#x,y of each tile. If increasing tileSize, considerdecreasing the rows and columns variables above...\ntileSize = 50\n\n#Enter the desired fps of the display - note the higher the fps the faster each pattern will be completed\n#This is the desired FPS, if the value is too high, the program will only run at the fastest it can\n#If you wish to leave the fps uncapped, set the value to 0\nfps = 0\n\n#write in patterns here (can include any number of patterns, just add the variable to the list 'patterns' below)\n#patterns can be any number of columns and rows, and can also be non-uniform (eg. 4 rows in column 1, then 7 rows in column 2)\npattern1 = [[1,0],[0,1]]\npattern2 = [[0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]]\npattern3 = [[1,1],[0,0]]\npattern4 = [[0,1,0],[0,0]]\npattern5 = [[1,0,1,0,1],[1,0,1,0,1]]\npattern6 = [[1,1,0,0],[0,0,1,1]]\npattern7 = [[1,0,0,0,1],[1,1,1,1,1,0],[0,1,0,1]]\n\npatterns = [pattern1, pattern2, pattern3, pattern4, pattern5, pattern6, pattern7]\n\n#Output the generated patterns if True\noutputPatterns = False\n\n########################################\n### DO NOT CHANGE ANY VARIABLES BELOW ##\n########################################\n\n\nprint('------------------------------------')\nprint('Pattern generator - Guy Turner (2017)')\nprint('------------------------------------')\nprint(' guyturnertech.com')\nprint('------------------------------------')\n\nif menuBool == True:\n \n print('\\n')\n columns = int(input('Enter the number of columns you want: '))\n rows = int(input('Enter the number of rows you want: '))\n tileSize = int(input('Enter the size of tile you want: '))\n fps = int(input('Enter the desired fps: '))\n\n\n\ndisplay_width = columns * tileSize\ndisplay_height = rows * tileSize\n\n#define pygame window characteristics, and clock (used for FPS)\nDisplay = pygame.display.set_mode((display_width,display_height))\npygame.display.set_caption('Squares')\nclock = pygame.time.Clock()\n\n#load images and apply the correct transformations (scaling)\nsquare = pygame.image.load('resources/squareB.jpg')\nsquare = pygame.transform.scale(square, (tileSize, tileSize))\nsquare90 = pygame.image.load('resources/square90B.jpg')\nsquare90 = pygame.transform.scale(square90, (tileSize, tileSize))\nrotations = [square, square90]\n\n'''\nThe below algorithm converts any inputted patern into a list compatible with the output plane size\n\nFirstly it checks if the columns or rows are equal to the plane size, if not, the sequence is either duplicated or reduced\nso that there are the correct number of columns in each list position. Then if needed the pattern is ammended to have the same \nnumber of rows (replicating itself based off of row 1 to the next entry, then row 2 and so on)\n'''\n\nfor pattern in patterns:\n if len(pattern) == columns & len(pattern[0]) == rows:\n print('equal rows & columns')\n\n else:\n #columns check\n if len(pattern[0]) == rows:\n print(\"equal columns\")\n\n elif len(pattern[0]) < rows:\n for item in pattern:\n index = 0\n while len(item) < rows:\n item.append(item[index])\n index +=1\n\n if index >= len(item) - 1:\n index = 0\n \n elif len(pattern[0]) > rows:\n for item in pattern:\n i = 0\n val = True\n while val == True:\n if len(item) == rows:\n val = False\n else:\n if i % 2 == 0:\n item.pop()\n else:\n item.pop(0)\n i +=1\n\n #row checks\n if len(pattern) == columns:\n print(\"equal rows\")\n\n elif len(pattern) < columns:\n index = 0\n while len(pattern) < columns:\n pattern.append(pattern[index])\n index +=1\n\n if index >= len(pattern) - 1:\n index = 0\n\n elif len(pattern) > columns:\n i = 0\n val = True\n while val == True:\n if len(pattern) == columns:\n val = False\n else:\n if i % 2 == 0:\n pattern.pop()\n else:\n pattern.pop(0)\n \n i +=1\n\n#Outputs the generated patterns to the console\nif outputPatterns == True:\n print('Patterns:')\n for item in patterns:\n print(item)\n print(' ')\n\n#create pos checker list for efficiency (instead of using random and checking the same tile more than once...)\nglobal scannerMatrix\ndef generateScannerPos():\n global scannerMatrix\n scannerMatrix = []\n for x in range(columns):\n for y in range(rows):\n scannerMatrix.append([x,y])\n random.shuffle(scannerMatrix)\n\ngenerateScannerPos()\n\n#Randomly generates the plane on launch, all tiles are randomly orientated and then compared to begin generating the first pattern\ncolumn = []\nj = 0\nwhile j < columns:\n row = []\n i = 0\n while i < rows:\n squareChoice = random.randint(0,1)\n row.append(squareChoice)\n i += 1\n column.append(row)\n j += 1\n\ndef displayImages():\n for rowindex, row in enumerate(column):\n for imageindex, image in enumerate(row):\n Display.blit(rotations[image], (rowindex*tileSize, imageindex*tileSize))\n\ngameExit = False\ncurrentPos = 0\ncurrentPattern = 0\n\nwhile not gameExit:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n gameExit = True\n\n selectedRow = scannerMatrix[currentPos][1]\n selectedColumn = scannerMatrix[currentPos][0]\n selectedSquare = column[selectedColumn][selectedRow]\n\n if selectedSquare == patterns[currentPattern][selectedColumn][selectedRow]:\n pass\n\n else:\n if selectedSquare == 0:\n column[selectedColumn][selectedRow] = 1\n\n elif selectedSquare == 1:\n column[selectedColumn][selectedRow] = 0\n\n \n displayImages()\n\n pygame.display.update()\n currentPos += 1\n\n if column == patterns[currentPattern]:\n print('Completed pattern')\n time.sleep(0.3)\n print('Moving to next pattern...')\n if currentPattern >= len(patterns)-1:\n currentPattern = 0\n else:\n currentPattern += 1\n \n generateScannerPos()\n currentPos = 0\n\n clock.tick(fps)\n\npygame.quit()\n","sub_path":"squares Master.py","file_name":"squares Master.py","file_ext":"py","file_size_in_byte":7318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"33315735","text":"import fragmenter\nimport cmiles\nimport openeye\n\nimport warnings\nimport logging\nfrom typing import Any, Dict, List, Optional, Union\n\nclass QCFractalDataset(object):\n \"\"\"\n Abstract base class for QCFractal dataset.\n\n Attributes\n ----------\n name : str\n The dataset name\n description : str\n A detailed description of the dataset\n input_oemols : list of OEMol\n Original molecules prior to processing\n oemols : list of multi-conformer OEMol\n Unique molecules in the dataset\n\n \"\"\"\n\n def __init__(self, name, description, input_oemols, oemols):\n \"\"\"\n Create a new QCFractalDataset\n\n Parameters\n ----------\n name : str\n The dataset name\n description : str\n A detailed description of the dataset\n input_oemols : list of OEMol\n The original molecules provided to the generator for dataset construction.\n oemols : list of multi-conformer OEMol\n Molecules that survived after enumeration, fragmentation, deduplication, filtering, and conformer expansion.\n \"\"\"\n self.name = name\n self.description = description\n\n # Store copies of molecules\n from openeye import oechem\n self.input_oemols = [ oechem.OEMol(oemol) for oemol in input_oemols ]\n self.oemols = [ oechem.OEMol(oemol) for oemol in oemols ]\n\n def mol_to_qcschema_dict(self, oemol):\n \"\"\"\n Render a given OEMol as a QCSchema dict.\n\n {\n 'initial_molecules' : [ qcschema_mol_conf1, qcschema_mol_conf2, ... ],\n 'cmiles_identifiers' : ...\n }\n\n Returns\n -------\n qcschema_dict : dict\n The dict containing all conformations as a list in qcschma_dict['initial_molecules']\n and CMILES identifiers as qcschema_dict['cmiles_identifiers']\n \"\"\"\n # Generate CMILES ids\n import cmiles\n try:\n cmiles_ids = cmiles.get_molecule_ids(oemol)\n except:\n from openeye import oechem\n smiles = oechem.OEMolToSmiles(oemol)\n logging.info('cmiles failed to generate molecule ids {}'.format(smiles))\n self.cmiles_failures.add(smiles)\n continue\n\n # Extract mapped SMILES\n mapped_smiles = cmiles_ids['canonical_isomeric_explicit_hydrogen_mapped_smiles']\n\n # Create QCSchema for all conformers defined in the molecule\n qcschema_molecules = [ cmiles.utils.mol_to_map_ordered_qcschema(conformer, mapped_smiles) for conformer in oemol.GetConfs() ]\n\n # Create the QCSchema dict that includes both the specified molecules and CMILES ids\n qcschema_dict = {\n 'initial_molecules': qcschema_molecules,\n 'cmiles_identifiers': cmiles_ids\n }\n\n return qcschema_dict\n\n def render_molecules(self, filename, rows=10, cols=6):\n \"\"\"\n Create a PDF showing all unique molecules in this dataset.\n\n Parmeters\n ---------\n filename : str\n Name of file to be written (ending in .pdf or .png)\n rows : int, optional, default=10\n Number of rows\n cols : int, optional, default=6\n Number of columns\n \"\"\"\n from openeye import oedepict\n\n # Configure display settings\n itf = oechem.OEInterface()\n PageByPage = True\n suppress_h = True\n ropts = oedepict.OEReportOptions(rows, cols)\n ropts.SetHeaderHeight(25)\n ropts.SetFooterHeight(25)\n ropts.SetCellGap(2)\n ropts.SetPageMargins(10)\n report = oedepict.OEReport(ropts)\n cellwidth, cellheight = report.GetCellWidth(), report.GetCellHeight()\n opts = oedepict.OE2DMolDisplayOptions(cellwidth, cellheight, oedepict.OEScale_Default * 0.5)\n opts.SetAromaticStyle(oedepict.OEAromaticStyle_Circle)\n pen = oedepict.OEPen(oechem.OEBlack, oechem.OEBlack, oedepict.OEFill_On, 1.0)\n opts.SetDefaultBondPen(pen)\n oedepict.OESetup2DMolDisplayOptions(opts, itf)\n\n # Render molecules\n for oemol in self.oemols:\n # Render molecule\n cell = report.NewCell()\n oemol_copy = oechem.OEMol(oemol)\n oedepict.OEPrepareDepiction(oemol_copy, False, suppress_h)\n disp = oedepict.OE2DMolDisplay(oemol_copy, opts)\n oedepict.OERenderMolecule(cell, disp)\n\n # Write the report\n oedepict.OEWriteReport(filename, report)\n\n def write_smiles(self, filename, mapped=False):\n \"\"\"\n Write canonical isomeric SMILES entries for all unique molecules in this set.\n\n Parameters\n ----------\n filename : str\n Filename to which SMILES are to be written\n mapped : bool, optional, default=False\n If True, will write explicit hydrogen canonical isomeric tagged SMILES\n \"\"\"\n if filename.endswith('.gz'):\n import gzip\n open_fun = gzip.open\n else:\n open_fun = open\n\n import cmiles\n with open_fun(filename, 'w') as outfile:\n for oemol in self.oemols:\n smiles = cmiles.utils.mol_to_smiles(oemol, mapped=mapped)\n outfile.write(smiles + '\\n')\n\n def to_json(self, filename):\n raise Exception('Abstract base class does not implement this method')\n\n def submit(self,\n address: Union[str, 'FractalServer'] = 'api.qcarchive.molssi.org:443',\n username: Optional[str] = None,\n password: Optional[str] = None,\n verify: bool = True):\n \"\"\"\n Submit the dataset to QCFractal server for computation.\n \"\"\"\n raise Exception('Not implemented')\n\nclass OptimizationDataset(QCFractalDataset):\n\n def to_json(self, filename):\n \"\"\"\n Render the OptimizationDataset to QCSchema JSON\n\n [\n {\n 'cmiles_identifiers' : ...,\n 'initial_molecules' : [ qcschema_mol_conf1, qcschema_mol_conf2, ... ]\n },\n\n ...\n ]\n\n Parameters\n ----------\n filename : str\n Filename (ending in .json or .json.gz) to be written\n\n \"\"\"\n if filename.endswith('.json.gz'):\n import gzip\n open_fun = gzip.open\n else:\n open_fun = open\n\n import json\n with open_fun(filename, 'w') as outfile:\n outfile.write(json.dumps(self.optimization_input, indent=2, sort_keys=True).encode('utf-8'))\n\nclass TorsionDriveDataset(QCFractalDataset):\n\n def to_json(self, filename):\n \"\"\"\n Render the TorsionDriveDataset to QCSchema JSON\n\n [\n \"index\" : {\n 'atom_indices' : ...,\n 'cmiles_identifiers' : ...,\n 'initial_molecules' : [ qcschema_mol_conf1, qcschema_mol_conf2, ... ]\n },\n\n ...\n ]\n\n Parameters\n ----------\n filename : str\n Filename (ending in .json or .json.gz) to be written\n\n \"\"\"\n if filename.endswith('.json.gz'):\n import gzip\n open_fun = gzip.open\n else:\n open_fun = open\n\n import json\n with open_fun(filename, 'w') as outfile:\n outfile.write(json.dumps(self.qcschema_dict, indent=2, sort_keys=True).encode('utf-8'))\n\n def render_molecules(self, filename, rows=10, cols=6):\n \"\"\"\n Create a PDF showing all unique molecules in this dataset.\n\n Parmeters\n ---------\n filename : str\n Name of file to be written (ending in .pdf or .png)\n rows : int, optional, default=10\n Number of rows\n cols : int, optional, default=6\n Number of columns\n \"\"\"\n from openeye import oedepict\n\n # Configure display settings\n itf = oechem.OEInterface()\n PageByPage = True\n suppress_h = True\n ropts = oedepict.OEReportOptions(rows, cols)\n ropts.SetHeaderHeight(25)\n ropts.SetFooterHeight(25)\n ropts.SetCellGap(2)\n ropts.SetPageMargins(10)\n report = oedepict.OEReport(ropts)\n cellwidth, cellheight = report.GetCellWidth(), report.GetCellHeight()\n opts = oedepict.OE2DMolDisplayOptions(cellwidth, cellheight, oedepict.OEScale_Default * 0.5)\n opts.SetAromaticStyle(oedepict.OEAromaticStyle_Circle)\n pen = oedepict.OEPen(oechem.OEBlack, oechem.OEBlack, oedepict.OEFill_On, 1.0)\n opts.SetDefaultBondPen(pen)\n oedepict.OESetup2DMolDisplayOptions(opts, itf)\n\n # Render molecules\n for json_molecule in json_molecules.values():\n # Create oemol\n import cmiles\n oemol = cmiles.utils.load_molecule(json_molecule['initial_molecules'][0])\n\n # Get atom indices\n atom_indices = json_molecule['atom_indices'][0]\n\n # Render molecule\n cell = report.NewCell()\n oemol_copy = oechem.OEMol(oemol)\n oedepict.OEPrepareDepiction(oemol_copy, False, suppress_h)\n disp = oedepict.OE2DMolDisplay(oemol_copy, opts)\n\n # Highlight central torsion bond and atoms selected to be driven for torsion\n class NoAtom(oechem.OEUnaryAtomPred):\n def __call__(self, atom):\n return False\n class AtomInTorsion(oechem.OEUnaryAtomPred):\n def __call__(self, atom):\n return atom.GetIdx() in atom_indices\n class NoBond(oechem.OEUnaryBondPred):\n def __call__(self, bond):\n return False\n class BondInTorsion(oechem.OEUnaryBondPred):\n def __call__(self, bond):\n return (bond.GetBgn().GetIdx() in atom_indices) and (bond.GetEnd().GetIdx() in atom_indices)\n class CentralBondInTorsion(oechem.OEUnaryBondPred):\n def __call__(self, bond):\n return (bond.GetBgn().GetIdx() in atom_indices[1:3]) and (bond.GetEnd().GetIdx() in atom_indices[1:3])\n\n atoms = mol.GetAtoms(AtomInTorsion())\n bonds = mol.GetBonds(NoBond())\n abset = oechem.OEAtomBondSet(atoms, bonds)\n oedepict.OEAddHighlighting(disp, oechem.OEColor(oechem.OEYellow), oedepict.OEHighlightStyle_BallAndStick, abset)\n\n atoms = mol.GetAtoms(NoAtom())\n bonds = mol.GetBonds(CentralBondInTorsion())\n abset = oechem.OEAtomBondSet(atoms, bonds)\n oedepict.OEAddHighlighting(disp, oechem.OEColor(oechem.OEOrange), oedepict.OEHighlightStyle_BallAndStick, abset)\n\n oedepict.OERenderMolecule(cell, disp)\n\n # Write the report\n oedepict.OEWriteReport(filename, report)\n","sub_path":"qcsubmit/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":10778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"8019716","text":"from pyspark.sql import SparkSession\nfrom pyspark.sql.types import *\nfrom pyspark.ml import PipelineModel\n\nspark = SparkSession.builder \\\n .appName(\"Titanic-api\") \\\n .master(\"local[*]\") \\\n .getOrCreate()\n \nmodel = PipelineModel.load(\"/user/admin/models/spark\")\n\nfeatures = ['Age', 'Fare']\n\n\ndef predict(args):\n wine=args[\"feature\"].split(\";\")\n feature = spark.createDataFrame([map(float,wine[:11])], features)\n result=model.transform(feature).collect()[0].prediction\n if result == 1.0:\n return {\"result\": \"N'a pas survecu\"}\n else:\n return {\"result\" : \"A survecu\"}\n \n# pre-heat the model\npredict({\"feature\": \"70;12\"})","sub_path":"Workshop_Titanic/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"457055627","text":"import pytest\r\nimport time\r\nimport sys\r\nfrom os.path import dirname, abspath\r\nsys.path.insert(0, dirname(dirname(abspath(__file__))))\r\nfrom page_obj.scg.scg_def_physical_interface import *\r\nfrom page_obj.scg.scg_def_vlan_interface import *\r\nfrom page_obj.scg.scg_def_bridge import *\r\nfrom page_obj.common.rail import *\r\nfrom page_obj.scg.scg_def_physical_interface import *\r\nfrom page_obj.common.ssh import *\r\nfrom page_obj.scg.scg_def_dhcp import *\r\nfrom page_obj.scg.scg_def import *\r\n\r\ntest_id = \"139087\"\r\ndef test_c139087(browser):\r\n\ttry:\r\n\t\tlogin_web(browser, url=dev1)\r\n\t\tdhcp_server_add_jyl(browser, interface=interface_name_3, dhcp_type=\"dhcp_server\", dhcp_gw=\"13.1.1.254\",\r\n\t\t dhcp_sm=\"255.255.255.0\", dns_server1=\"117.117.117.117\", wins_server1=\"118.118.118.118\",\r\n\t\t ip_range1_1=\"13.1.1.2\", ip_range1_2=\"13.1.1.20\")\r\n\t\tlogin_web(browser, url=dev3)\r\n\t\ttime.sleep(1)\r\n\t\tphysical_intertface_obtain_ip_address_from_dhcp1_jyl(browser, physical_interface=interface_name_2)\r\n\t\ttime.sleep(1)\r\n\t\t# 获取信息\r\n\t\twebinfo1 = browser.find_element_by_xpath('//*[@id=\"box\"]/div[3]/ul/li[2]').text\r\n\t\t# print(webinfo1)\r\n\t\t# 点击返回\r\n\t\ttime.sleep(1)\r\n\r\n\t\ta = Shell_SSH()\r\n\t\ta.connect(dev3)\r\n\t\ta.execute(\"en\")\r\n\t\ta.execute(\"conf t\")\r\n\t\ta.execute(\"interface gigabitethernet \"+interface_name_2)\r\n\t\ta.execute(\"no ip address 13.1.1.3\")\r\n\t\ta.execute(\"exit\")\r\n\t\ta.close()\r\n\t\tvlan_add_jyl(browser, physicl_interface=interface_name_2, vlan_id=\"22\", work_mode=\"route\")\r\n\t\ttime.sleep(1)\r\n\t\ttime.sleep(5)\r\n\t\ta = Shell_SSH()\r\n\t\ta.connect(dev3)\r\n\t\ta.execute(\"en\")\r\n\t\ta.execute(\"conf t\")\r\n\t\ta.execute(\"interface vlan \"+interface_name_2+'.22')\r\n\t\ta.execute(\"ip address 13.1.1.3 255.255.255.0\")\r\n\t\ta.execute(\"exit\")\r\n\t\ta.execute(\"interface gigabitethernet \"+interface_name_2)\r\n\t\ta.execute(\"switchmode access\")\r\n\t\ta.execute(\"exit\")\r\n\t\ta.close()\r\n\r\n\t\ttime.sleep(5)\r\n\r\n\t\ttime.sleep(1)\r\n\t\tvlan_interface_obtain_ip_fromdhcp1_jyl(browser, vlan_interface=interface_name_2+\".22\")\r\n\t\ttime.sleep(1)\r\n\t\ttime.sleep(5)\r\n\t\twebinfo2 = browser.find_element_by_xpath('//*[@id=\"box\"]/div[3]/ul/li[2]').text\r\n\t\t# print(webinfo2)\r\n\t\t# 点击返回\r\n\t\tbrowser.find_element_by_xpath('//*[@id=\"link_but\"]').click()\r\n\t\ttime.sleep(1)\r\n\t\t# 点击取消\r\n\t\tbrowser.find_element_by_xpath('//*[@id=\"container\"]/div[2]/form/div[3]/div[2]/div/input[4]').click()\r\n\t\tvlan_delete_jyl(browser)\r\n\t\ttime.sleep(1)\r\n\r\n\t\ta = Shell_SSH()\r\n\t\ta.connect(dev3)\r\n\t\ta.execute(\"en\")\r\n\t\ta.execute(\"conf t\")\r\n\t\ta.execute(\"interface gigabitethernet \"+interface_name_2)\r\n\t\ta.execute(\"no ip address 13.1.1.3\")\r\n\t\ta.execute(\"exit\")\r\n\t\ta.close()\r\n\t\ttime.sleep(2)\r\n\t\tphysics_interface_change_transparent_interface(browser, interface2=interface_name_2)\r\n\t\tbridge_add_jyl(browser, bridge_name=\"br_1\", allow_ping=\"yes\")\r\n\t\tbridge_edit_interface_jyl(browser, interface=interface_name_2, bridge_interface=\"br_1\")\r\n\t\ttime.sleep(1)\r\n\t\tbridge_edit_ip_add_jyl(browser, bridge_interface=\"br_1\", address_mode=\"manual\", ip=\"13.1.1.3\", mask=\"24\")\r\n\t\ttime.sleep(1)\r\n\t\tbridge_interface_obtain_ip_from_dhcp1_jyl(browser, bridge=\"br_1\", work_mode=\"dhcp\")\r\n\t\ttime.sleep(1)\r\n\t\twebinfo3 = browser.find_element_by_xpath('//*[@id=\"box\"]/div[3]/ul/li[2]').text\r\n\t\t# print(webinfo3)\r\n\t\ttime.sleep(1)\r\n\t\t# 点击返回\r\n\t\tbrowser.find_element_by_xpath('//*[@id=\"link_but\"]').click()\r\n\t\t# 点击取消\r\n\t\tbrowser.find_element_by_xpath('//*[@id=\"container\"]/div[2]/form/div[3]/div[2]/div/input[3]').click()\r\n\r\n\t\ttime.sleep(1)\r\n\t\tdelete_bridge_jyl(browser)\r\n\t\ttime.sleep(1)\r\n\t\ta = Shell_SSH()\r\n\t\ta.connect(dev3)\r\n\t\ta.execute(\"en\")\r\n\t\ta.execute(\"conf t\")\r\n\t\ta.execute(\"interface gigabitethernet \"+interface_name_2)\r\n\t\ta.execute(\"work-mode route\")\r\n\t\ta.execute(\"ip address 13.1.1.3 255.255.255.0\")\r\n\t\ta.execute(\"exit\")\r\n\t\tlogin_web(browser, url=dev1)\r\n\t\tdhcp_server_edit_or_delete_jyl(browser, fuction=\"delete\")\r\n\r\n\t\ttry:\r\n\t\t\tassert \"配置了静态ip地址\" in webinfo1\r\n\t\t\tassert \"配置了静态ip地址\" in webinfo2\r\n\t\t\tassert \"配置了静态ip地址\" in webinfo3\r\n\t\t\trail_pass(test_run_id, test_id)\r\n\t\texcept:\r\n\t\t\trail_fail(test_run_id, test_id)\r\n\t\t\tassert \"配置了静态ip地址\" in webinfo1\r\n\t\t\tassert \"配置了静态ip地址\" in webinfo2\r\n\t\t\tassert \"配置了静态ip地址\" in webinfo3\r\n\r\n\texcept Exception as err:\r\n\t\t# 如果上面的步骤有报错,重新设备,恢复配置\r\n\t\tprint(err)\r\n\t\treload(hostip=[dev1, dev3])\r\n\t\trail_fail(test_run_id, test_id)\r\n\t\tassert False\r\n\r\n\r\nif __name__ == '__main__':\r\n\tpytest.main([\"-v\", \"-s\", \"test_c\" + str(test_id) + \".py\"])","sub_path":"pyautoTest-master(ICF-7.5.0)/test_case/scg/scg_DHCP_Client/test_c139087.py","file_name":"test_c139087.py","file_ext":"py","file_size_in_byte":4521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"623852275","text":"import math as math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#Linkovi\n\nfile_in =\"C:/Users/matij/Desktop/Projekat_2018_dinamicko_trenje/analiticki_potencijal/analitickiSaTrenjemSveKomponente/\"\n\nfile_out =\"C:/Users/matij/Desktop/Projekat_2018_dinamicko_trenje/analiticki_potencijal/analitickiSaTrenjemSveKomponente/\"\n\nm,x,y,z,vx,vy,vz= np.loadtxt(file_in + \"cestica.txt\", unpack=True)\nt = np.loadtxt(file_in + \"vreme.txt\", unpack = True) \n\n\ndef intenzitet(a,b,c):\n return (a*a + b*b + c*c)**0.5\n\nubrzanje = []\nvreme = []\n\nfor i in range(1,len(m)):\n v1 = intenzitet(vx[i-1],vy[i-1],vz[i-1])\n v2 = intenzitet(vx[i],vy[i],vz[i])\n t1 = t[i-1]\n t2 = t[i]\n ubrzanje.append((v2-v1)/(t2-t1))\n vreme.append(t1)\n \nfor i in range(len(ubrzanje)):\n ubrzanje[i] = ubrzanje[i]*1e13\n \n\nfile = open(file_out + \"ubrzanje.txt\",\"w\")\nfor i in range(len(ubrzanje)):\n file.write(str(vreme[i]) + \" \" + str(ubrzanje[i]) + \"\\n\")\nfile.close\n\nplt.plot(vreme,ubrzanje,c='black')\nplt.xlabel(\"$T[Gyr]$\")\nplt.ylabel(r\"$a[10^{-13} kpc/s^2]$\")\nplt.xlim(min(vreme),max(vreme))\nplt.savefig(file_out + \"ubrzanje\",dpi = 300)\nplt.show()\n","sub_path":"analytical-potential/analytical-potential-dynamical-friction/acceleration.py","file_name":"acceleration.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"478272605","text":"import pytest\n\nfrom instagraph.persistence.pg.actions import PgActions\nfrom instagraph.persistence.pg.users import PgUsers\n\n\n@pytest.mark.postgresql\ndef test_actions_followers_explored(pgsql):\n users = PgUsers(pgsql)\n users.user(1234)\n actions = PgActions(pgsql)\n actions.mark_followers_explored(1234)\n assert actions.followers_explored(1234)\n\n\n@pytest.mark.postgresql\ndef test_actions_following_explored(pgsql):\n users = PgUsers(pgsql)\n users.user(1234)\n actions = PgActions(pgsql)\n actions.mark_following_explored(1234)\n assert actions.following_explored(1234)\n\n\n@pytest.mark.postgresql\ndef test_actions_info_saved(pgsql):\n users = PgUsers(pgsql)\n users.user(1234)\n actions = PgActions(pgsql)\n actions.mark_info_saved(1234)\n assert actions.info_saved(1234)\n\n\n@pytest.mark.postgresql\ndef test_actions_posts_info_saved(pgsql):\n users = PgUsers(pgsql)\n users.user(1234)\n actions = PgActions(pgsql)\n actions.mark_posts_info_saved(1234)\n assert actions.posts_info_saved(1234)\n","sub_path":"test/test_actions.py","file_name":"test_actions.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"199864244","text":"activate_this = '/var/www/Flaskapp/app_virtual_env/samee/bin/activate_this.py'\nexecfile(activate, dict(__file__=activate_this))\nimport sys\nsys.path.insert(0,'/var/www/Flaskapp/')\n\n\n\n\nfrom video_api_final import application\n\nif __name__ == \"__main__\":\n application.run()\n","sub_path":"video_api.wsgi","file_name":"video_api.wsgi","file_ext":"wsgi","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"539584246","text":"#Program for demonstrating autoaiming. Created TastyDucks 3/18/17\n\nimport sys\nimport cv2\nimport evsslogger\nimport targeter\nfrom subprocess import call\nimport traceback\nimport time\n\nlogger = evsslogger.getLogger()\nevsslogger.initLogging()\n\nif len(sys.argv) > 1:\n\tInput = sys.argv[1]\n\tif len(sys.argv) > 2:\n\t\tlogger.info(\"Ignoring extra value input after first perameter in command call...\")\nelse:\n\tlogger.warn(\"Invalid input! No target index specified when command was called. (Examples of valid calls: \\\"python targetingdemo.py 0\\\", or \\\"python targetingdemo.py 1\\\".)\\r\\nInput set to default of \\\"0\\\".\")\n\tInput = \"0\"\n\nTargeter = targeter.Targeter()\nTargeter.daemon = True\nTargeter.name = \"Targeter\"\nTargeter.setTarget(int(Input))\n\nCam = None\n\nif Input == \"0\":\n\tlogger.info(\"Starting demo for target \\\"0\\\" (HIGH BOILER)...\")\n\ttime.sleep(1)\n\ttry:\n\t\tcall([\"v4l2-ctl\", \"-c\", \"exposure_auto=1\"])\n\t\tcall([\"v4l2-ctl\", \"-c\", \"exposure_absolute=5\"])\n\t\tcall([\"v4l2-ctl\", \"-c\", \"brightness=30\"])\n\t\tCam = cv2.VideoCapture(0)\n\texcept:\n\t\tlogger.error(\"Unable to setup Cam 0 for capture.\")\n\t\ttraceback.print_exc()\n\tif Cam:\n\t\twhile True:\n\t\t\tReturn = Targeter.GetTarget(Cam, 0)\n\t\t\tlogger.info(\"Return data: \" + str(Return[1:]))\n\t\t\tcv2.imshow(\"Targeting Data Image:\", Return[0])\n\t\t\tcv2.waitKey(1)\nelif Input == \"1\":\n\tlogger.info(\"TARGETING DEMO: Starting demo for target \\\"1\\\" (GEAR DELIVERY)...\")\n\ttime.sleep(1)\n\ttry:\n\t\tcall([\"v4l2-ctl\", \"--device=2\", \"-c\", \"exposure_auto=1\"])\n\t\tcall([\"v4l2-ctl\", \"--device=1\", \"-c\", \"exposure_absolute=5\"])\n\t\tcall([\"v4l2-ctl\", \"--device=1\", \"-c\", \"brightness=30\"])\n\t\tCam = cv2.VideoCapture(1)\n\texcept:\n\t\tlogger.error(\"Unable to setup Cam 0 for capture.\")\n\t\ttraceback.print_exc()\n\tif Cam:\n\t\twhile True:\n\t\t\tReturn = Targeter.GetTarget(Cam, 1)\n\t\t\tlogger.info(\"Return data: \" + str(Return[1:]))\n\t\t\tcv2.imshow(\"Targeting Data Image:\", Return[0])\n\t\t\tcv2.waitKey(1)\nelse:\n\tprint(\"TARGETING DEMO ERROR: Invalid input \\\"\" + str(Input) + \"\\\"! Valid target indexes are \\\"0\\\" (HIGH BOILER), and \\\"1\\\" (GEAR DELIVERY).\")\n\n","sub_path":"Jetson/Server/targetingdemo.py","file_name":"targetingdemo.py","file_ext":"py","file_size_in_byte":2027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"422207656","text":"\"\"\"\nGiven an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.\n\nNote:\nYour algorithm should have a linear runtime complexity. Could you implement it without using extra memory?\n\"\"\"\n# hashtable\n# Space: O(n)\n# skip solution\n\n# maths\n# e.g [a,a,a,b,b,b,c] => 3*(a+b+c) - (3*a+3*b+c) = 2*c\nclass Solution(object):\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n return (3* sum(set(nums)) - sum(nums)) // 2\n\n# bit manipulation\n# generalize to k case\nclass Solution(object):\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n res = 0\n for i in range(32):\n bitsum = 0\n for num in nums:\n if (num >> i) & 1:\n bitsum = (bitsum+1) % 3\n if bitsum:\n res |= (bitsum << i)\n return res","sub_path":"leetcode/137_single_number_ii.py","file_name":"137_single_number_ii.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"633932222","text":"import os\nimport re\nfrom glob import glob\nimport my_dl_lib.generic_dataset\nimport matplotlib.gridspec as gridspec\n# import matplotlib\n# matplotlib.use('agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy\nimport scipy.misc\nimport tensorflow as tf\nfrom my_dl_lib.generic_gan import discriminator\nfrom my_dl_lib.generic_gan import generator\nfrom my_dl_lib.generic_gan import input_data\n\n\nclass GenericGAN:\n\n def __init__(self, discriminator_input_height, discriminator_input_width, discriminator_number_of_input_channels=3,\n discriminator_number_of_filters_at_first_layer=64, discriminator_arch_file=None,\n generator_input_dim=100, generator_output_height=28, generator_output_width=28,\n generator_output_channels=1, generator_architecture_file=None, tensor_board_logs_dir='./logs',\n is_input_an_image=True, checkpoint_dir='./checkpoints/gan', generated_samples_dir='GAN_samples',\n y_labels_dim=None, with_activation_function_on_last_layer_of_generator=False, gan_type='dcgan'):\n\n self.gan_type = gan_type\n self.num_of_iterations_traind = 0 # Helper variable to count how many training iterations we did so far.\n self.saver = None\n self.checkpoint_dir = checkpoint_dir\n self.generated_samples_dir = generated_samples_dir\n self.is_input_an_image = is_input_an_image\n self.tensor_board_logs_dir = tensor_board_logs_dir\n\n self.generator = generator.GenericGenerator(generator_input_dim, generator_output_height,\n generator_output_width, generator_output_channels,\n generator_architecture_file,\n y_labels_dim=y_labels_dim,\n add_activation_at_end=\n with_activation_function_on_last_layer_of_generator,\n gan_type=self.gan_type)\n\n self.y_place_holder = tf.placeholder(tf.float32, shape=[None, y_labels_dim], name='y_input_placeholder')\n\n self.discriminator = discriminator.GenericDiscriminator(discriminator_input_height, discriminator_input_width,\n discriminator_number_of_input_channels,\n discriminator_number_of_filters_at_first_layer,\n discriminator_arch_file,\n y_labels_dim=y_labels_dim,\n y_placeholder=self.y_place_holder,\n gan_type=self.gan_type)\n\n generator_output = self.generator.last_layer_generator_tensor\n self.discriminator_of_generator = discriminator.GenericDiscriminator(discriminator_input_height, discriminator_input_width,\n discriminator_number_of_input_channels,\n discriminator_number_of_filters_at_first_layer,\n discriminator_arch_file, inputs=generator_output,\n y_labels_dim=y_labels_dim,\n y_placeholder=self.y_place_holder,\n gan_type=self.gan_type)\n\n self.total_discriminator_loss = self.discriminator.cost + self.discriminator_of_generator.cost\n self.total_discriminator_loss_summary = tf.summary.scalar(\"Discriminator_total_loss\",\n self.total_discriminator_loss)\n\n '''\n Once we have our 2 loss functions (d_loss and g_loss), we need to define our optimizers. Keep in mind that the \n optimizer for the generator network needs to only update the generator’s weights, not those of the \n discriminator. In order to make this distinction, we need to create 2 lists, one with the discriminator’s \n weights and one with the generator’s weights. This is where naming all of your Tensorflow variables can come \n in handy.\n '''\n t_vars = tf.trainable_variables()\n # TODO: Delete this.\n print(\"Trainable Vars:\")\n for i, var in enumerate(t_vars):\n print(\"%d : \" % i, end='')\n print(var)\n\n self.discriminator_vars = [var for var in t_vars if 'discriminator' in var.name]\n print(\"Discriminator Vars:\")\n for i, var in enumerate(self.discriminator_vars):\n print(\"%d : \" % i, end='')\n print(var)\n self.generator_vars = [var for var in t_vars if 'generator' in var.name]\n print(\"Generator Vars:\")\n for i, var in enumerate(self.generator_vars):\n print(\"%d : \" % i, end='')\n print(var)\n print(\"Done\")\n\n def train(self, discriminator_x_train, discriminator_y_train,\n num_of_iterations, batch_size, learning_rate=0.0002,\n momentum_term_adam=0.5, crop_images=False):\n \"\"\"\n\n :return:\n \"\"\"\n with tf.variable_scope(\"train\"):\n discriminator_updates = tf.train.AdamOptimizer(learning_rate, beta1=momentum_term_adam) \\\n .minimize(self.total_discriminator_loss, var_list=self.discriminator_vars)\n\n generator_updates = tf.train.AdamOptimizer(learning_rate, beta1=momentum_term_adam) \\\n .minimize(self.discriminator_of_generator.generator_cost, var_list=self.generator_vars)\n\n self.session = tf.Session()\n sess = self.session\n init = tf.global_variables_initializer()\n sess.run(init)\n\n # Create a saver object :\n self.saver = tf.train.Saver(max_to_keep=1000)\n\n # Merge all the summaries and write them out:\n # self.merged_summaries = tf.summary.merge_all()\n self.generator_merged_summaries = tf.summary.merge([self.discriminator_of_generator.loss_summary,\n self.discriminator_of_generator.generator_loss_summary])\n\n self.discriminator_merged_summaries = tf.summary.merge([self.discriminator.loss_summary,\n self.total_discriminator_loss_summary])\n\n # Create Writer object to visualize the graph later:\n self.generator_train_writer = tf.summary.FileWriter(self.tensor_board_logs_dir + '/generator_train',\n sess.graph)\n self.discriminator_train_writer = tf.summary.FileWriter(self.tensor_board_logs_dir + '/discriminator_train',\n sess.graph)\n\n self.val_writer = tf.summary.FileWriter(self.tensor_board_logs_dir + '/val')\n self.test_writer = tf.summary.FileWriter(self.tensor_board_logs_dir + '/test')\n\n # generator_iterator = generic_dataset.GenericDataSetIterator(generator_x_train, generator_y_train)\n discriminator_iterator = my_dl_lib.generic_dataset.GenericDataSetIterator(discriminator_x_train, discriminator_y_train)\n j = 0\n for i in range(num_of_iterations):\n # generator_x_batch, generator_y_batch = generator_iterator.next_batch(batch_size)\n generator_x_batch = np.random.uniform(-1, 1, [batch_size, self.generator.input_dim]).astype(np.float32)\n\n discriminator_x_batch, discriminator_y_batch = discriminator_iterator.next_batch(batch_size)\n\n discriminator_x_batch = np.array([x['cardiac_cycle'] for x in discriminator_x_batch])\n\n if crop_images:\n discriminator_x_batch = np.array([get_image(img_file,\n input_height=108,\n input_width=108,\n resize_height=64,\n resize_width=64,\n crop=True,\n grayscale=False) for img_file in discriminator_x_batch])\n\n '''\n while j < 500: # Start by only updating the discriminator:\n # Update the Discriminator network :\n print(\"**Iterating on discriminator Only. Iteration %d**\", j)\n summary, _ = sess.run([self.discriminator_merged_summaries, discriminator_updates],\n feed_dict={self.discriminator.input_placeholder: discriminator_x_batch,\n self.generator.x_input_placeholder: generator_x_batch})\n j += 1\n self.discriminator_train_writer.add_summary(summary, i)\n generator_x_batch = np.random.uniform(-1, 1, [batch_size, self.generator.input_dim]).astype(np.float32)\n\n discriminator_x_batch, _ = discriminator_iterator.next_batch(batch_size)\n '''\n # Update the Discriminator network :\n if self.gan_type == 'conditional_dcgan' or self.gan_type == 'vanilla_conditional_gan':\n summary, _ = sess.run([self.discriminator_merged_summaries, discriminator_updates],\n feed_dict={self.discriminator.input_placeholder: discriminator_x_batch,\n self.generator.x_input_placeholder: generator_x_batch,\n self.discriminator.y_input_placeholder: discriminator_y_batch,\n self.generator.y_input_placeholder: discriminator_y_batch})\n\n self.discriminator_train_writer.add_summary(summary, i)\n\n # Update Generator network:\n summary, _ = sess.run([self.generator_merged_summaries, generator_updates],\n feed_dict={self.generator.x_input_placeholder: generator_x_batch,\n self.generator.y_input_placeholder: discriminator_y_batch,\n self.discriminator_of_generator.y_input_placeholder: discriminator_y_batch})\n\n self.generator_train_writer.add_summary(summary, i)\n\n # Update Generator twice to make sure that d_loss does not go to zero (different from paper)\n generator_loss, summary, _ = sess.run(\n [self.discriminator_of_generator.generator_cost, self.generator_merged_summaries,\n generator_updates],\n feed_dict={self.generator.x_input_placeholder: generator_x_batch,\n self.generator.y_input_placeholder: discriminator_y_batch,\n self.discriminator_of_generator.y_input_placeholder: discriminator_y_batch})\n else:\n summary, _ = sess.run([self.discriminator_merged_summaries, discriminator_updates],\n feed_dict={self.discriminator.input_placeholder: discriminator_x_batch,\n self.generator.x_input_placeholder: generator_x_batch})\n\n self.discriminator_train_writer.add_summary(summary, i)\n\n # Update Generator network:\n summary, _ = sess.run([self.generator_merged_summaries, generator_updates],\n feed_dict={ self.generator.x_input_placeholder: generator_x_batch})\n\n self.generator_train_writer.add_summary(summary, i)\n\n # Update Generator twice to make sure that d_loss does not go to zero (different from paper)\n generator_loss, summary, _ = sess.run([self.discriminator_of_generator.generator_cost, self.generator_merged_summaries, generator_updates],\n feed_dict={self.generator.x_input_placeholder: generator_x_batch})\n\n '''\n while generator_loss > 2:\n generator_x_batch = np.random.uniform(-1, 1, [batch_size, self.generator.input_dim]).astype(np.float32)\n generator_loss, summary, _ = sess.run(\n [self.discriminator_of_generator.generator_cost, self.generator_merged_summaries,\n generator_updates],\n feed_dict={self.generator.x_input_placeholder: generator_x_batch})\n print(\"inside while, generator loss is \", generator_loss)\n '''\n self.generator_train_writer.add_summary(summary, i)\n\n if i % 10 == 0:\n\n if self.gan_type == 'conditional_dcgan' or self.gan_type == 'vanilla_conditional_gan':\n loss_discriminator_from_generator_input = sess.run(self.discriminator_of_generator.cost,\n feed_dict={self.generator.x_input_placeholder:\n generator_x_batch,\n self.generator.y_input_placeholder:\n discriminator_y_batch,\n self.discriminator_of_generator.y_input_placeholder:\n discriminator_y_batch})\n\n loss_discriminator_from_real_input = sess.run(self.discriminator.cost,\n feed_dict={self.discriminator.input_placeholder:\n discriminator_x_batch,\n self.discriminator.y_input_placeholder: discriminator_y_batch})\n\n loss_generator = sess.run(self.discriminator_of_generator.generator_cost,\n feed_dict={self.generator.x_input_placeholder: generator_x_batch,\n self.generator.y_input_placeholder: discriminator_y_batch,\n self.discriminator_of_generator.y_input_placeholder: discriminator_y_batch})\n else:\n loss_discriminator_from_generator_input = sess.run(self.discriminator_of_generator.cost,\n feed_dict={self.generator.x_input_placeholder:\n generator_x_batch})\n\n loss_discriminator_from_real_input = sess.run(self.discriminator.cost,\n feed_dict={self.discriminator.input_placeholder:\n discriminator_x_batch})\n\n loss_generator = sess.run(self.discriminator_of_generator.generator_cost,\n feed_dict={self.generator.x_input_placeholder: generator_x_batch})\n\n print(\"Iteration number %d, discriminator_loss: %.8f, generator_loss: %.8f\" %\n (i, loss_discriminator_from_generator_input + loss_discriminator_from_real_input, loss_generator))\n\n if i % 100 == 0:\n # Save the model :\n save_path = self.saver.save(sess, os.path.join(self.checkpoint_dir, 'iter_' + str(i)))\n print(\"Model saved in file: %s\" % save_path)\n\n if self.is_input_an_image:\n # sample from the generator and plot :\n random_samples = np.random.uniform(-1, 1, size=(64, self.generator.input_dim))\n y_samples = discriminator_y_train[:64]\n output_images = self.generator.run_generator(sess, random_samples, y_samples)\n # self.plot(output_images, type='mnist')\n\n manifold_h = int(np.floor(np.sqrt(64)))\n manifold_w = int(np.ceil(np.sqrt(64)))\n assert manifold_h * manifold_w == 64\n size = manifold_h, manifold_w\n\n self.save_batch_of_images(output_images, size, os.path.join(self.generated_samples_dir,\n 'sample_iter_' + str(i) + '.png'))\n '''\n if output_images[0].shape[2] == 1:\n fig = plt.figure()\n plt.imshow(output_images[0][:, :, 0], cmap='Greys_r')\n plt.savefig(os.path.join(self.generated_samples_dir, str(i) + \"_mnist.png\"))\n else:\n # RGB image:\n assert output_images[0].shape[2] == 3\n manifold_h = int(np.floor(np.sqrt(64)))\n manifold_w = int(np.ceil(np.sqrt(64)))\n assert manifold_h * manifold_w == 64\n size = manifold_h, manifold_w\n self.save_batch_of_images(output_images, size, os.path.join(self.generated_samples_dir,\n 'sample_iter_' + str(i) + '.png'))\n '''\n else:\n # sample from the generator and plot :\n random_samples = np.random.uniform(-1, 1, size=(5, self.generator.input_dim))\n # Valid only for ECG - Generate for each beat type 5 samples:\n if self.gan_type == 'conditional_dcgan' or self.gan_type == 'vanilla_conditional_gan':\n N_sample = [1, 0, 0, 0, 0]\n S_sample = [0, 1, 0, 0, 0]\n V_sample = [0, 0, 1, 0, 0]\n F_sample = [0, 0, 0, 1, 0]\n Q_sample = [0, 0, 0, 0, 1]\n\n # y_samples = discriminator_y_train[:5]\n y_samples = np.array([N_sample, S_sample, V_sample, F_sample, Q_sample])\n output_generator = self.generator.run_generator(sess, random_samples, y_samples)\n plt.figure()\n plt.subplot(3, 2, 1)\n plt.plot(output_generator[0])\n plt.title(\"N sample from generator\")\n plt.subplot(3, 2, 2)\n plt.plot(output_generator[1])\n plt.title(\"S sample from generator\")\n plt.subplot(3, 2, 3)\n plt.plot(output_generator[2])\n plt.title(\"V sample from generator\")\n plt.subplot(3, 2, 4)\n plt.plot(output_generator[3])\n plt.title(\"F sample from generator\")\n plt.subplot(3, 2, 5)\n plt.plot(output_generator[4])\n plt.title(\"Q sample from generator\")\n plt.savefig(os.path.join(self.generated_samples_dir, str(i) + \"_ecg_gan.png\"))\n else:\n output_generator = self.generator.run_generator(sess, random_samples, None)\n plt.figure()\n plt.subplot(3, 2, 1)\n plt.plot(output_generator[0])\n plt.title(\"1\")\n plt.subplot(3, 2, 2)\n plt.plot(output_generator[1])\n plt.title(\"2\")\n plt.subplot(3, 2, 3)\n plt.plot(output_generator[2])\n plt.title(\"3\")\n plt.subplot(3, 2, 4)\n plt.plot(output_generator[3])\n plt.title(\"4\")\n plt.subplot(3, 2, 5)\n plt.plot(output_generator[4])\n plt.title(\"5\")\n plt.savefig(os.path.join(self.generated_samples_dir, str(i) + \"_ecg_gan.png\"))\n '''\n for j,e in enumerate(output_generator):\n # print(e)\n plt.figure()\n plt.plot(e)\n plt.savefig(os.path.join(self.generated_samples_dir, str(i) + str(j) + \"_ecg_gan.png\"))\n # plt.show()\n '''\n\n def continue_training_from_meta(self, model_name, discriminator_x_train, discriminator_y_train, num_of_iterations,\n batch_size):\n\n # Load the parameters:\n with tf.Session() as sess:\n new_saver = tf.train.import_meta_graph(model_name + 'meta')\n new_saver.restore(sess, tf.train.latest_checkpoint('./'))\n graph = tf.get_default_graph()\n\n with tf.variable_scope(\"train\"):\n discriminator_updates = graph.get_tensor_by_name(\"discriminator_updates:0\")\n\n generator_updates = graph.get_tensor_by_name(\"generator_updates:0\")\n\n # Create a saver object :\n self.saver = tf.train.Saver()\n\n # Merge all the summaries and write them out:\n # self.merged_summaries = tf.summary.merge_all()\n self.generator_merged_summaries = graph.get_tensor_by_name(\"generator_merged_summaries:0\")\n\n self.discriminator_merged_summaries = graph.get_tensor_by_name(\"discriminator_merged_summaries:0\")\n\n # Create Writer object to visualize the graph later:\n self.generator_train_writer = graph.get_tensor_by_name(\"generator_train_writer:0\")\n\n self.discriminator_train_writer = graph.get_tensor_by_name(\"discriminator_train_writer:0\")\n\n discriminator_iterator = my_dl_lib.generic_dataset.GenericDataSetIterator(discriminator_x_train,\n discriminator_y_train)\n for i in range(num_of_iterations):\n # generator_x_batch, generator_y_batch = generator_iterator.next_batch(batch_size)\n generator_x_batch = np.random.uniform(-1, 1, [batch_size, self.generator.input_dim]).astype(np.float32)\n\n discriminator_x_batch, _ = discriminator_iterator.next_batch(batch_size)\n\n # Update the Discriminator network:\n summary, _ = sess.run([self.discriminator_merged_summaries, discriminator_updates],\n feed_dict={self.discriminator.input_placeholder: discriminator_x_batch,\n self.generator.x_input_placeholder: generator_x_batch})\n\n self.discriminator_train_writer.add_summary(summary, i)\n\n # Update Generator network:\n summary, _ = sess.run([self.generator_merged_summaries, generator_updates],\n feed_dict={self.generator.x_input_placeholder: generator_x_batch})\n\n self.generator_train_writer.add_summary(summary, i)\n\n # Update Generator twice to make sure that d_loss does not go to zero (different from paper)\n summary, _ = sess.run([self.generator_merged_summaries, generator_updates],\n feed_dict={self.generator.x_input_placeholder: generator_x_batch})\n\n self.generator_train_writer.add_summary(summary, i)\n\n if i % 10 == 0:\n loss_discriminator_from_generator_input = sess.run(self.discriminator_of_generator.cost,\n feed_dict={self.generator.x_input_placeholder:\n generator_x_batch})\n\n loss_discriminator_from_real_input = sess.run(self.discriminator.cost,\n feed_dict={self.discriminator.input_placeholder:\n discriminator_x_batch})\n\n loss_generator = sess.run(self.discriminator_of_generator.generator_cost,\n feed_dict={self.generator.x_input_placeholder: generator_x_batch})\n\n print(\"Iteration number %d, discriminator_loss: %.8f, generator_loss: %.8f\" %\n (i, loss_discriminator_from_generator_input + loss_discriminator_from_real_input,\n loss_generator))\n\n # Save the model :\n save_path = self.saver.save(sess, os.path.join(self.checkpoint_dir, 'iter_' + str(i) + '.ckpt'))\n print(\"Model saved in file: %s\" % save_path)\n\n if i % 100 == 0:\n if self.is_input_an_image:\n # sample from the generator and plot :\n y_samples = discriminator_y_train[:64]\n random_samples = np.random.uniform(-1, 1, size=(64, self.generator.input_dim))\n output_images = self.generator.run_generator(sess, random_samples, y_samples)\n\n manifold_h = int(np.floor(np.sqrt(64)))\n manifold_w = int(np.ceil(np.sqrt(64)))\n assert manifold_h * manifold_w == 64\n size = manifold_h, manifold_w\n\n self.save_batch_of_images(output_images, size, os.path.join(self.generated_samples_dir,\n 'sample_iter_' + str(i) + '.png'))\n\n else:\n # sample from the generator and plot :\n random_samples = np.random.uniform(-1, 1, size=(5, self.generator.input_dim))\n output_generator = self.generator.run_generator(sess, random_samples)\n for j, e in enumerate(output_generator):\n print(e)\n plt.figure()\n plt.plot(e)\n plt.savefig(os.path.join(self.generated_samples_dir, str(i) + str(j) + \"_ecg_gan.png\"))\n # plt.show()\n\n\n @staticmethod\n def plot(samples, type='mnist'):\n if type == 'mnist':\n fig = plt.figure(figsize=(4, 4))\n gs = gridspec.GridSpec(4, 4)\n gs.update(wspace=0.05, hspace=0.05)\n\n for i, sample in enumerate(samples):\n ax = plt.subplot(gs[i])\n plt.axis('off')\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n ax.set_aspect('equal')\n if type == 'mnist':\n plt.imshow(sample.reshape(28, 28), cmap='Greys_r')\n else:\n plt.plot(sample)\n return fig\n else:\n fig = plt.figure()\n plt.plot(samples[0])\n # print(samples[0])\n return fig\n\n @staticmethod\n def save_batch_of_images(images, size, image_path):\n \"\"\"\n given a batch of images saves to one image marging all to one.\n :param images: [batch size, h, w, c]\n :param size:\n :param image_path: path to save\n :return:\n \"\"\"\n\n images = (images + 1.) / 2.\n h, w = images.shape[1], images.shape[2]\n if images.shape[3] in (3, 4):\n c = images.shape[3]\n img = np.zeros((h * size[0], w * size[1], c))\n for idx, image in enumerate(images):\n i = idx % size[1]\n j = idx // size[1]\n img[j * h:j * h + h, i * w:i * w + w, :] = image\n manipulated_img = img\n elif images.shape[3] == 1:\n img = np.zeros((h * size[0], w * size[1]))\n for idx, image in enumerate(images):\n i = idx % size[1]\n j = idx // size[1]\n img[j * h:j * h + h, i * w:i * w + w] = image[:, :, 0]\n manipulated_img = img\n else:\n raise ValueError('in merge(images,size) images parameter '\n 'must have dimensions: HxW or HxWx3 or HxWx4')\n\n manipulated_img = np.squeeze(manipulated_img)\n\n return scipy.misc.imsave(image_path, manipulated_img)\n\n def load_checkpoint(self):\n \"\"\"\n Loads a model that was already trained with a checkpoint file\n :return:\n \"\"\"\n # TODO: complete this .....\n print(\" [*] Reading checkpoints...\")\n checkpoint_dir = self.checkpoint_dir\n ckpt = tf.train.get_checkpoint_state(checkpoint_dir)\n if ckpt and ckpt.model_checkpoint_path:\n ckpt_name = os.path.basename(ckpt.model_checkpoint_path)\n\n self.saver.restore(self.session, os.path.join(checkpoint_dir, ckpt_name))\n\n counter = int(next(re.finditer(\"(\\d+)(?!.*\\d)\", ckpt_name)).group(0))\n print(\" [*] Success to read {}\".format(ckpt_name))\n return True, counter\n else:\n print(\" [*] Failed to find a checkpoint\")\n return False, 0\n\n\n# Helper functions for celebA data:\ndef get_image(image_path, input_height, input_width, resize_height=64, resize_width=64, crop=True, grayscale=False):\n \"\"\"\n Opens a jpg file into an array and also might resize the image to desired shape.\n :param image_path:\n :param input_height:\n :param input_width:\n :param resize_height:\n :param resize_width:\n :param crop:\n :param grayscale:\n :return:\n \"\"\"\n image = scipy.misc.imread(image_path).astype(np.float)\n return transform(image, input_height, input_width, resize_height, resize_width, crop)\n\n\ndef transform(image, input_height, input_width, resize_height=64, resize_width=64, crop=True):\n \"\"\"\n transforms an image to desired shape.\n :param image:\n :param input_height:\n :param input_width:\n :param resize_height:\n :param resize_width:\n :param crop:\n :return:\n \"\"\"\n if crop:\n cropped_image = center_crop(image, input_height, input_width, resize_height, resize_width)\n else:\n cropped_image = scipy.misc.imresize(image, [resize_height, resize_width])\n return np.array(cropped_image)/127.5 - 1.\n\n\ndef center_crop(x, crop_h, crop_w, resize_h=64, resize_w=64):\n if crop_w is None:\n crop_w = crop_h\n h, w = x.shape[:2]\n j = int(round((h - crop_h)/2.))\n i = int(round((w - crop_w)/2.))\n return scipy.misc.imresize( x[j:j+crop_h, i:i+crop_w], [resize_h, resize_w])\n\n\nif __name__ == \"__main__\":\n\n print(\"Testing GAN on celcbA images:\")\n mnist_gan = GenericGAN(discriminator_input_height=28, discriminator_input_width=28,\n discriminator_number_of_input_channels=1, discriminator_number_of_filters_at_first_layer=64,\n discriminator_arch_file=None, generator_input_dim=100, generator_output_height=28,\n generator_output_width=28, generator_output_channels=1, generator_architecture_file=None,\n tensor_board_logs_dir='./logs/dcgan/mnist', is_input_an_image=True,\n checkpoint_dir='./saved_models/dcgan/mnist', generated_samples_dir='samples/dcgan/mnist',\n y_labels_dim=10, with_activation_function_on_last_layer_of_generator=True,\n gan_type='vanilla_conditional_gan')\n\n # load the mnist data :\n mnist_data = input_data.read_data_sets(\"mnist_data\", one_hot=True)\n train_set = mnist_data.train\n x = train_set.images\n x = x.reshape((55000, 28, 28, 1)).astype(np.float32)\n y_tags = train_set.labels\n\n mnist_gan.train(discriminator_x_train=x, discriminator_y_train=y_tags, num_of_iterations=1000000, batch_size=128,\n learning_rate=0.0002, momentum_term_adam=0.5)\n\n\n '''\n print(\"Testing GAN on celcbA images:\")\n # load the celebA data :\n celebA_list_of_images_names = glob(os.path.join(\"./data\", 'celebA', '*.jpg'))\n # For debugging - check image dimensions and print them:\n imreadImg = scipy.misc.imread(celebA_list_of_images_names[0]).astype(np.float)\n print(\"image dims:\", imreadImg.shape)\n print(\"Number of images: \", len(celebA_list_of_images_names))\n # Crop the images\n '''\n '''\n train_images = [get_image(img_file,\n input_height=108,\n input_width=108,\n resize_height=64,\n resize_width=64,\n crop=True,\n grayscale=False) for img_file in celebA_list_of_images_names]\n '''\n '''\n # Test on celebA:\n celebA_gan = GenericGAN(discriminator_input_height=64, discriminator_input_width=64,\n discriminator_number_of_input_channels=3, discriminator_number_of_filters_at_first_layer=64,\n discriminator_arch_file=None, generator_input_dim=100, generator_output_height=64,\n generator_output_width=64, generator_output_channels=3, generator_architecture_file=None,\n tensor_board_logs_dir='./logs/celebA', is_input_an_image=True,\n checkpoint_dir='./saved_models/dcgan/celebA',\n generated_samples_dir='samples/dcgan/celebA')\n\n celebA_gan.train(discriminator_x_train=np.array(celebA_list_of_images_names), discriminator_y_train=np.array(celebA_list_of_images_names), num_of_iterations=1000000,\n batch_size=128, learning_rate=0.0002, momentum_term_adam=0.5, crop_images=True)\n\n '''\n\n\n\n\n\n\n\n","sub_path":"my_dl_lib/generic_gan/gan.py","file_name":"gan.py","file_ext":"py","file_size_in_byte":34291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"403699486","text":"from flask import Flask, render_template, request, redirect, url_for\nfrom flask_sqlalchemy import SQLAlchemy\nfrom twilio_tools import send_message\nfrom flask_apscheduler import APScheduler\nimport schedule_tools\nimport time\nfrom datetime import datetime\nimport twilio_tools\nimport random\n\napp = Flask(__name__)\n\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'\ndb = SQLAlchemy(app)\nscheduler = APScheduler()\nscheduler.init_app(app)\n\n\nclass User_db (db.Model):\n #id = db.Column(db.Integer, primary_key=True)\n\n # string of 1's and 0's in a particular order to denote which muscle groups have been used\n # '10' is number muscle groups\n last_worked_mgroups = db.Column(db.String(10), default='0000000000')\n\n phone_number = db.Column(db.String(10), primary_key=True)\n difficulty = db.Column(db.String())\n goal = db.Column(db.String())\n time = db.Column(db.Integer)\n\n def __repr__(self):\n return \"Last worked muscle groups: {}\\nNum: {}\\nDifficulty: {}\\nGoal: {}\\n Time: {}\".format(\\\n self.last_worked_mgroups, self.phone_number, self.difficulty, self.goal, self.time)\n \n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n print(\"Got POST request to /\")\n #msg = request.form['msg']\n #num = request.form['num']\n #send_message(msg, num)\n\n # \n #User_db.query.get_or_404()\n\n # new user settings\n new_user_settings = User_db()\n new_user_settings.phone_number = request.form['phone_number']\n new_user_settings.difficulty = request.form['difficulty']\n new_user_settings.goal = request.form['goal']\n new_user_settings.time = request.form['time']\n \n #print(\"TIME: \\n\" + str(new_user_settings.time))\n #print(new_user_settings.time)\n #print(\"TIME1: \\n\" + str(new_user_settings.time[0]))\n #print(\"TIME2: \\n\" + str(new_user_settings.time[1]))\n\n #print(new_user_settings.phone_number)\n\n #exists = db.session.query(User_db.phone_number).filter_by(phone_number=new_user_settings.phone_number).scalar() is not None\n #exists = db.session.query(db.exists().where(User_db.phone_number == new_user_settings.phone_number)).scalar()\n #exists = User_db.query(User_db.query.exists().where(User_db.phone_number == new_user_settings.phone_number)).scalar()\n\n #q = User_db.query.filter(User_db.phone_number == new_user_settings.phone_number)\n #print(q)\n #if(User_db.query(q.exists())):\n #if exists:\n # New user is already in database, just remove that entry so we can add it again\n #db.session.remove()\n User_db.query.filter(User_db.phone_number == new_user_settings.phone_number).delete()\n \n #print(\"lwmg: \" + new_user_settings.last_worked_mgroups)\n #jank\n if not new_user_settings.last_worked_mgroups:\n new_user_settings.last_worked_mgroups = '0000000000'\n\n \n print(\"Scheduling message for \" + str(new_user_settings.phone_number) + \" at \" + str(new_user_settings.time))\n nums, mgroups = schedule_tools.schedule_message_sends(scheduler, [new_user_settings])\n \n ##################\n # Update mgroup ##\n num = nums[0]\n new_worked_mgroups = mgroups[0]\n \n new_user_settings.last_worked_mgroups = new_worked_mgroups\n ###################\n\n db.session.add(new_user_settings)\n db.session.commit()\n \n \n\n # etc...\n\n #return redirect('success.html')\n return render_template('success.html', time=new_user_settings.time, img=random.choice([\"TerminatorThumbsUp.png\", \"Arnold_Thumbs.png\"]))\n else:\n return render_template('index.html')\n\n#@app.route('/update_worked_mgroups', methods=['POST'])\n'''\nCalled by schedule_tools\n'''\ndef update_worked_mgroups(phone_number, new_worked_mgroups):\n #userset = User_db.query.filter(User_db.phone_number==phone_number).first()\n #userset.last_worked_mgroups = new_worked_mgroups\n #db.session.commit()\n pass\n\n\ndef print_date_time():\n print()\n print(time.strftime(\"%A, %d. %B %Y %I:%M:%S %p\"))\n\ndef print_all():\n print(User_db.query.all())\n\n\n\ndef schedule_all():\n nums, mgroupsarr = schedule_tools.schedule_message_sends(scheduler, User_db.query.all())\n\n for i in range(len(nums)):\n num = nums[i]\n new_worked_mgroups = mgroupsarr[i]\n \n userset = User_db.query.filter(User_db.phone_number==num).first()\n userset.last_worked_mgroups = new_worked_mgroups\n db.session.commit()\n\n\nif __name__ == '__main__':\n #schedule_tools.schedule_the_message_send_scheduler(scheduler)\n #scheduler.add_job(func=print_date_time, trigger=\"interval\", seconds=3, id='dateprinter')\n\n #scheduler.add_job(func=lambda: schedule_tools.schedule_message_sends(scheduler, User_db.query.all()), trigger=\"cron\", hour=0, id='dateprinter')\n scheduler.add_job(func=schedule_all, trigger=\"cron\", hour=0, id='dateprinter')\n\n #scheduler.add_job(func=print_date_time, trigger='interval', seconds=5, id=\"timeprinter\")\n #scheduler.add_job(func=print_all, trigger='interval', seconds=5, id=\"printer\")\n\n\n \n #hour = 18\n #minute = 55\n # does not work nevermind does?\n #scheduler.add_job(func=lambda: twilio_tools.send_message(\"\\nThis is a test\\n\", \"3195411516\"), \\\n # trigger=\"date\", id=\"testthing\", run_date=datetime(int(datetime.now().year), int(datetime.now().month), int(datetime.now().day), int(hour), int(minute), 0))\n \n #print(\"AAAAAAAAAAAAAAAAAA\")\n\n scheduler.start()\n\n\n\n # Remember to take off debug mode on upload. This also fixes sheduler running things twice\n app.run(debug = False)\n #app.run(debug = True)\n \n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"541914748","text":"import json\nfrom tqdm import tqdm\nimport csv\nimport requests\nfilename = \"movie_ids_11_09_2020.json\"\nraw_json = {}\nresult_jsons = []\nprint(filename)\nwith open(filename, \"r\", encoding='UTF-8') as fr:\n for i, line in enumerate(tqdm(fr, total=556140)):\n raw_json = json.loads(line)\n result_jsons.append(raw_json)\nprint(len(result_jsons))\nresult_jsons = sorted(result_jsons, key=lambda i: i['popularity'], reverse=True)[:10000]\n# fw = open(\"sorted_movie.json\", \"w\", encoding='UTF-8')\n# json.dumps(raw_json, fw, sort_keys=\"popularity\")\nwith open('movies.csv', \"w\", newline='', encoding='UTF-8') as csvfile:\n fieldname = ['tmdb_id', 'title', 'description', 'poster', 'popularity', 'genres', 'rating', 'rating_count', 'release_date']\n csv_writter = csv.DictWriter(csvfile, fieldnames=fieldname)\n url = 'https://api.themoviedb.org/3/movie/'\n param = {'api_key': 'a32f475cc38fc86be6398e58d22b946f', 'language': 'en-US'}\n for i, item in enumerate(tqdm(result_jsons)):\n if (i == 0):\n csv_writter.writeheader()\n request_url = url+str(item['id'])\n r = requests.get(request_url, params=param)\n result = json.loads(r.text)\n data_movie = {\n 'tmdb_id': result['id'],\n 'title': result['title'],\n 'description': result['overview'],\n 'poster': result['poster_path'],\n 'popularity': result['popularity'],\n 'genres': result['genres'],\n 'rating': result['vote_average'],\n 'rating_count': result['vote_count'],\n 'release_date': result['release_date'] \n }\n csv_writter.writerow(data_movie)\n print(\"df\")","sub_path":"filmfinder/sort_json_file_by_popularity.py","file_name":"sort_json_file_by_popularity.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"438827787","text":"#!/usr/bin/python\n\nimport numpy as np\nimport urllib\n# url with dataset\nurl = \"pima-indians-diabetes.txt\"\n# download the file\nraw_data = urllib.urlopen(url)\n# load the CSV file as a numpy matrix\ndataset = np.loadtxt(raw_data, delimiter=\",\", usecols=range(9))\n#dataset = np.loadtxt(raw_data)\n# separate the data from the target attributes\nX = dataset[:,0:7]\ny = dataset[:,8]\n\n\nfrom sklearn import preprocessing\n# normalize the data attributes\nnormalized_X = preprocessing.normalize(X)\n# standardize the data attributes\nstandardized_X = preprocessing.scale(X)\n\n\nfrom sklearn import metrics\nfrom sklearn.tree import DecisionTreeClassifier\n# fit a CART model to the data\nmodel = DecisionTreeClassifier()\nmodel.fit(X, y)\nprint(model)\n# make predictions\nexpected = y\npredicted = model.predict(X)\n# summarize the fit of the model\nprint(metrics.classification_report(expected, predicted))\nprint(metrics.confusion_matrix(expected, predicted))\n","sub_path":"dataprocess.py","file_name":"dataprocess.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"26826529","text":"import FWCore.ParameterSet.Config as cms\n\n#------------------------------------------------------------------------------- \n# Options settings\n#------------------------------------------------------------------------------- \nimport FWCore.ParameterSet.VarParsing as opts\nimport copy\n\noptions = opts.VarParsing ('analysis')\noptions.setDefault( 'maxEvents' , 10000 );\n\noptions.register('Debug',\n 0,\n opts.VarParsing.multiplicity.singleton,\n opts.VarParsing.varType.int,\n 'Debugging output level' )\n\noptions.register(\"filename\",\n \"ntuple.root\",\n opts.VarParsing.multiplicity.singleton,\n opts.VarParsing.varType.string,\n 'Histogram filename')\n\noptions.parseArguments()\n\n#------------------------------------------------------------------------------- \n# Setting up process\n#------------------------------------------------------------------------------- \nprocess = cms.Process(\"LHEWeighter\")\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 1000\nprocess.MessageLogger.categories.append('HLTrigReport')\n\nprocess.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) )\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(options.maxEvents) )\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(\n 'file:////wk_cms/yichen/miniAODs/MC_reMiniAOD_25ns/TTJets_TuneCUETP8M1_13TeV-madgraphMLM-pythia8.root'\n#'file:/wk_cms/yichen/miniAODs/MC_reMiniAOD_25ns/TTJets_amcatnlo.root'\n#'/store/mc/RunIISpring15MiniAODv2/TTJets_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/MINIAODSIM/74X_mcRun2_asymptotic_v2-v1/40000/3641AC41-DC6D-E511-AFF5-90B11C05054D.root'\n#'/store/mc/RunIISpring15MiniAODv2/TTJets_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/MINIAODSIM/74X_mcRun2_asymptotic_v2-v3/60000/0257DC71-1B6A-E511-8BE0-3417EBE643F6.root'\n )\n )\n\n#process.load(\"PhysicsTools.PatAlgos.producersLayer1.patCandidates_cff\")\nprocess.load(\"Configuration.EventContent.EventContent_cff\")\nprocess.load('Configuration.StandardSequences.GeometryDB_cff')\nprocess.load('Configuration.StandardSequences.MagneticField_38T_cff')\nprocess.load('Configuration.StandardSequences.Services_cff')\nprocess.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_condDBv2_cff')\nprocess.load(\"RecoEgamma/PhotonIdentification/PhotonIDValueMapProducer_cfi\")\nprocess.GlobalTag.globaltag=\"74X_mcRun2_asymptotic_v2\"\n\n#------------------------------------------------------------------------------- \n# ED analyzer settings\n#------------------------------------------------------------------------------- \nprocess.TFileService = cms.Service(\"TFileService\",\n fileName = cms.string( options.filename )\n )\n\nprocess.mcweighter = cms.EDAnalyzer(\n \"MCWeighter\",\n )\n\nprocess.outpath = cms.EndPath(\n process.mcweighter\n )\n","sub_path":"MCWeighter/test/MCWeighter_cfg.py","file_name":"MCWeighter_cfg.py","file_ext":"py","file_size_in_byte":2866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"256922378","text":"import queue\nimport numpy as np\n\nclass firstBreadthSolver:\n\n def __init__(self,maze):\n ## Initialize the varaibles\n self.maze = maze\n self.mazeDims = len(maze[0])\n self.start = None\n self.end = None\n self.que = queue.Queue()\n self.searching = True\n self.truthTable = np.ones((len(maze[0]), len(maze[0])),dtype=bool)\n\n def generateTtable(self):\n ## Generate the truth table\n for i in range(self.mazeDims):\n for j in range(self.mazeDims):\n if self.maze[i,j] == \" \" or self.maze[i,j] == \"E\":\n self.truthTable[i,j] = False\n\n def getStartPos(self):\n ## Get the start and end position of the maze\n for i in range(self.mazeDims):\n if self.maze[0,i] == \"S\":\n self.start = (0,i)\n for i in range(self.mazeDims):\n if self.maze[-1,i] == \"E\":\n self.end = (self.mazeDims-1,i)\n \n def calculatePosition(self,x,y,letter):\n ## calculate the new position based on the letter\n if letter == \"L\":\n y -= 1\n elif letter == \"R\":\n y += 1\n elif letter == \"U\":\n x -= 1\n elif letter == \"D\":\n x += 1\n return x,y\n \n def readPhrase(self,item):\n ## Take the item which contains directions\n ## Read it and find the path\n x,y = self.start[0],self.start[1]\n if item != \"\":\n for letter in item:\n x,y = self.calculatePosition(x,y,letter)\n return x,y\n \n def printPositions(self,item):\n ## Take the phrase and print it\n x,y = self.start[0],self.start[1]\n for letter in item:\n x,y = self.calculatePosition(x,y,letter)\n self.maze[x,y] = \"o\"\n \n def addOrEnd(self,qItem,x,y,letter):\n ## Determine if the phrase has reached the end or\n ## or if it should be added to the queue\n if self.end[0] == x and self.end[1] == y:\n self.searching = False\n self.printPositions(qItem)\n else:\n self.que.put(\"\".join([qItem,letter]))\n self.truthTable[x,y] = True\n \n def getNewItems(self, qItem):\n ## Get the paths\n x,y = self.readPhrase(qItem)\n if x <= self.mazeDims-2 and self.truthTable[x+1,y] == False:\n self.addOrEnd(qItem,x+1,y,\"D\")\n if x >= 1 and self.truthTable[x-1,y] == False:\n self.addOrEnd(qItem,x-1,y,\"U\")\n if y <= self.mazeDims-2 and self.truthTable[x,y+1] == False:\n self.addOrEnd(qItem,x,y+1,\"R\")\n if y >= 1 and self.truthTable[x,y-1] == False:\n self.addOrEnd(qItem,x,y-1,\"L\")\n \n def process(self):\n ## the power house that will run the entire solution\n ## returns the solution matrix\n self.generateTtable()\n self.getStartPos()\n self.que.put(\"\")\n while self.searching == True:\n qItem = self.que.get()\n self.getNewItems(qItem)\n return self.maze","sub_path":"firstBreadth.py","file_name":"firstBreadth.py","file_ext":"py","file_size_in_byte":3077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"282663595","text":"import cv2 as cv\nimport numpy as np\n\n'''\nCamshift 算法\n\nCamshift它是MeanShift算法的改进,称为连续自适应的MeanShift算法.\n它的基本思想是视频图像的所有帧作MeanShift运算,并将上一帧的结果(即Search Window的中心和大小)作为下一帧MeanShift算法的Search Window的初始值,如此迭代下去。\n\n'''\n\ncap = cv.VideoCapture(\"../code_images/slow.mp4\")\n\n# 取出视频的第一帧\nret, frame = cap.read()\n\n# 设置追踪窗口的初始位置\nr, h, c, w = 200, 50, 250, 100\ntrack_window = (c, r, w, h)\n\n# 设置用于追踪的ROI\nroi = frame[r:r + h, c:c + w]\nhsv_roi = cv.cvtColor(frame, cv.COLOR_BGR2HSV)\nmask = cv.inRange(hsv_roi, np.array((0., 60., 32.)), np.array((180., 255., 255.)))\nroi_hist = cv.calcHist([hsv_roi], [0], mask, [180], [0, 180])\ncv.normalize(roi_hist, roi_hist, 0, 255, cv.NORM_MINMAX)\n\nterm_crit = (cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 1)\n\nwhile True:\n\n ret, frame = cap.read()\n\n if ret == True:\n hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)\n dst = cv.calcBackProject([hsv], [0], roi_hist, [0, 180], 1)\n\n # 使用CamShift得到一个新的位置\n ret, track_window = cv.CamShift(dst, track_window, term_crit)\n\n # 将追踪窗口画在图像上\n pts=cv.boxPoints(ret)\n pts=np.int0(pts)\n img=cv.polylines(frame,[pts],True,255,2)\n\n cv.imshow(\"image\", img)\n\n k = cv.waitKey(60) & 0xff\n if k == 27:\n break\n else:\n cv.imwrite(chr(k) + \".jpg\", img)\n\n else:\n break\n\ncv.destroyAllWindows()\ncap.release()\n","sub_path":"code/case_34_camShift.py","file_name":"case_34_camShift.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"390527106","text":"from django.conf.urls.defaults import url, patterns\nfrom feeds import RSSv1LatestArticles, RSSv2LatestArticles, AtomLatestArticles, LatestArticles\nfrom views import ArticleDetailView\n\n\nurlpatterns = patterns('',\n url(r'^$', LatestArticles(), name='news_index'),\n\n url(r'^article/edit/$', 'news.views.edit_article', name='news_article_edit'),\n url(r'^article/edit/(?P[\\d]+)/$', 'news.views.edit_article', name='news_article_edit'),\n url(r'^article/delete/(?P[\\d]+)/$', 'news.views.delete_article', name='news_article_delete'),\n url(r'^article/(?P[\\d]+)/$', ArticleDetailView.as_view(), name='news_article'),\n url(r'^article/(?P[^/]+)/$', ArticleDetailView.as_view(), name='news_article'),\n\n url(r'^rss/v1/$', RSSv1LatestArticles(), name='news_feed_rss'),\n url(r'^rss/v2/$', RSSv2LatestArticles(), name='news_feed_rss2'),\n url(r'^atom/v1/$', AtomLatestArticles(), name='news_feed_atom'),\n)\n\n","sub_path":"news/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"561738268","text":"from __future__ import unicode_literals, division, absolute_import\nfrom datetime import datetime, timedelta\nimport logging\nimport os\nimport posixpath\nimport socket\nimport sys\nfrom urllib2 import URLError\n\nfrom sqlalchemy import Table, Column, Integer, Float, String, Unicode, Boolean, DateTime, func\nfrom sqlalchemy.schema import ForeignKey\nfrom sqlalchemy.orm import relation\n\nfrom flexget import db_schema, plugin\nfrom flexget.event import event\nfrom flexget.manager import Session\nfrom flexget.plugin import get_plugin_by_name\nfrom flexget.utils import requests\nfrom flexget.utils.database import text_date_synonym, year_property, with_session\nfrom flexget.utils.sqlalchemy_utils import table_add_column, table_schema\n\ntry:\n import tmdb3\nexcept ImportError:\n raise plugin.DependencyError(issued_by='api_tmdb', missing='tmdb3',\n message='TMDB requires https://github.com/wagnerrp/pytmdb3')\n\nlog = logging.getLogger('api_tmdb')\nBase = db_schema.versioned_base('api_tmdb', 0)\n\n# This is a FlexGet API key\ntmdb3.tmdb_api.set_key('bdfc018dbdb7c243dc7cb1454ff74b95')\ntmdb3.locales.set_locale(\"en\", \"us\", True)\n# There is a bug in tmdb3 library, where it uses the system encoding for query parameters, tmdb expects utf-8 #2392\ntmdb3.locales.syslocale.encoding = 'utf-8'\ntmdb3.set_cache('null')\n\n\n@db_schema.upgrade('api_tmdb')\ndef upgrade(ver, session):\n if ver is None:\n log.info('Adding columns to tmdb cache table, marking current cache as expired.')\n table_add_column('tmdb_movies', 'runtime', Integer, session)\n table_add_column('tmdb_movies', 'tagline', Unicode, session)\n table_add_column('tmdb_movies', 'budget', Integer, session)\n table_add_column('tmdb_movies', 'revenue', Integer, session)\n table_add_column('tmdb_movies', 'homepage', String, session)\n table_add_column('tmdb_movies', 'trailer', String, session)\n # Mark all cached movies as expired, so new fields get populated next lookup\n movie_table = table_schema('tmdb_movies', session)\n session.execute(movie_table.update(values={'updated': datetime(1970, 1, 1)}))\n ver = 0\n return ver\n\n\n# association tables\ngenres_table = Table('tmdb_movie_genres', Base.metadata,\n Column('movie_id', Integer, ForeignKey('tmdb_movies.id')),\n Column('genre_id', Integer, ForeignKey('tmdb_genres.id')))\nBase.register_table(genres_table)\n\n\nclass TMDBContainer(object):\n \"\"\"Base class for TMDb objects\"\"\"\n\n def __init__(self, init_object=None):\n if isinstance(init_object, dict):\n self.update_from_dict(init_object)\n elif init_object:\n self.update_from_object(init_object)\n\n def update_from_dict(self, update_dict):\n \"\"\"Populates any simple (string or number) attributes from a dict\"\"\"\n for col in self.__table__.columns:\n if isinstance(update_dict.get(col.name), (basestring, int, float)):\n setattr(self, col.name, update_dict[col.name])\n\n def update_from_object(self, update_object):\n \"\"\"Populates any simple (string or number) attributes from object attributes\"\"\"\n for col in self.__table__.columns:\n if (hasattr(update_object, col.name) and\n isinstance(getattr(update_object, col.name), (basestring, int, float))):\n setattr(self, col.name, getattr(update_object, col.name))\n\n\nclass TMDBMovie(TMDBContainer, Base):\n __tablename__ = 'tmdb_movies'\n\n id = Column(Integer, primary_key=True, autoincrement=False, nullable=False)\n updated = Column(DateTime, default=datetime.now, nullable=False)\n popularity = Column(Integer)\n translated = Column(Boolean)\n adult = Column(Boolean)\n language = Column(String)\n original_name = Column(Unicode)\n name = Column(Unicode)\n alternative_name = Column(Unicode)\n movie_type = Column(String)\n imdb_id = Column(String)\n url = Column(String)\n votes = Column(Integer)\n rating = Column(Float)\n certification = Column(String)\n overview = Column(Unicode)\n runtime = Column(Integer)\n tagline = Column(Unicode)\n budget = Column(Integer)\n revenue = Column(Integer)\n homepage = Column(String)\n trailer = Column(String)\n _released = Column('released', DateTime)\n released = text_date_synonym('_released')\n year = year_property('released')\n posters = relation('TMDBPoster', backref='movie', cascade='all, delete, delete-orphan')\n genres = relation('TMDBGenre', secondary=genres_table, backref='movies')\n\n def update_from_object(self, update_object):\n try:\n TMDBContainer.update_from_object(self, update_object)\n self.translated = len(update_object.translations) > 0\n if len(update_object.languages) > 0:\n self.language = update_object.languages[0].code # .code or .name ?\n self.original_name = update_object.originaltitle\n self.name = update_object.title\n try:\n if len(update_object.alternate_titles) > 0:\n # maybe we could choose alternate title from movie country only\n self.alternative_name = update_object.alternate_titles[0].title\n except UnicodeEncodeError:\n # Bug in tmdb3 library, see #2437. Just don't set alternate_name when it fails\n pass\n self.imdb_id = update_object.imdb\n self.url = update_object.homepage\n self.rating = update_object.userrating\n if len(update_object.youtube_trailers) > 0:\n self.trailer = update_object.youtube_trailers[0].source # unicode: ooNSm6Uug3g\n elif len(update_object.apple_trailers) > 0:\n self.trailer = update_object.apple_trailers[0].source\n self.released = update_object.releasedate\n except tmdb3.TMDBError as e:\n raise LookupError('Error updating data from tmdb: %s' % e)\n\n\nclass TMDBGenre(TMDBContainer, Base):\n\n __tablename__ = 'tmdb_genres'\n\n id = Column(Integer, primary_key=True, autoincrement=False)\n name = Column(String, nullable=False)\n\n\nclass TMDBPoster(TMDBContainer, Base):\n\n __tablename__ = 'tmdb_posters'\n\n db_id = Column(Integer, primary_key=True)\n movie_id = Column(Integer, ForeignKey('tmdb_movies.id'))\n size = Column(String)\n url = Column(String)\n file = Column(Unicode)\n\n def get_file(self, only_cached=False):\n \"\"\"Makes sure the poster is downloaded to the local cache (in userstatic folder) and\n returns the path split into a list of directory and file components\"\"\"\n from flexget.manager import manager\n base_dir = os.path.join(manager.config_base, 'userstatic')\n if self.file and os.path.isfile(os.path.join(base_dir, self.file)):\n return self.file.split(os.sep)\n elif only_cached:\n return\n # If we don't already have a local copy, download one.\n log.debug('Downloading poster %s' % self.url)\n dirname = os.path.join('tmdb', 'posters', str(self.movie_id))\n # Create folders if they don't exist\n fullpath = os.path.join(base_dir, dirname)\n if not os.path.isdir(fullpath):\n os.makedirs(fullpath)\n filename = os.path.join(dirname, posixpath.basename(self.url))\n thefile = file(os.path.join(base_dir, filename), 'wb')\n thefile.write(requests.get(self.url).content)\n self.file = filename\n # If we are detached from a session, update the db\n if not Session.object_session(self):\n session = Session()\n try:\n poster = session.query(TMDBPoster).filter(TMDBPoster.db_id == self.db_id).first()\n if poster:\n poster.file = filename\n finally:\n session.close()\n return filename.split(os.sep)\n\n\nclass TMDBSearchResult(Base):\n\n __tablename__ = 'tmdb_search_results'\n\n id = Column(Integer, primary_key=True)\n search = Column(Unicode, nullable=False)\n movie_id = Column(Integer, ForeignKey('tmdb_movies.id'), nullable=True)\n movie = relation(TMDBMovie, backref='search_strings')\n\n\nclass ApiTmdb(object):\n \"\"\"Does lookups to TMDb and provides movie information. Caches lookups.\"\"\"\n\n @staticmethod\n @with_session(expire_on_commit=False)\n def lookup(title=None, year=None, tmdb_id=None, imdb_id=None, smart_match=None, only_cached=False, session=None):\n \"\"\"\n Do a lookup from TMDb for the movie matching the passed arguments.\n\n Any combination of criteria can be passed, the most specific criteria specified will be used.\n\n :param int tmdb_id: tmdb_id of desired movie\n :param unicode imdb_id: imdb_id of desired movie\n :param unicode title: title of desired movie\n :param int year: release year of desired movie\n :param unicode smart_match: attempt to clean and parse title and year from a string\n :param bool only_cached: if this is specified, an online lookup will not occur if the movie is not in the cache\n session: optionally specify a session to use, if specified, returned Movie will be live in that session\n :param session: sqlalchemy Session in which to do cache lookups/storage. commit may be called on a passed in\n session. If not supplied, a session will be created automatically.\n\n :return: The :class:`TMDBMovie` object populated with data from tmdb\n\n :raises: :class:`LookupError` if a match cannot be found or there are other problems with the lookup\n \"\"\"\n\n if not (tmdb_id or imdb_id or title) and smart_match:\n # If smart_match was specified, and we don't have more specific criteria, parse it into a title and year\n title_parser = get_plugin_by_name('parsing').instance.parse_movie(smart_match)\n title = title_parser.name\n year = title_parser.year\n\n if title:\n search_string = title.lower()\n if year:\n search_string = '%s (%s)' % (search_string, year)\n elif not (tmdb_id or imdb_id):\n raise LookupError('No criteria specified for TMDb lookup')\n log.debug('Looking up TMDb information for %r' % {'title': title, 'tmdb_id': tmdb_id, 'imdb_id': imdb_id})\n\n movie = None\n\n def id_str():\n return '' % (title, tmdb_id, imdb_id)\n if tmdb_id:\n movie = session.query(TMDBMovie).filter(TMDBMovie.id == tmdb_id).first()\n if not movie and imdb_id:\n movie = session.query(TMDBMovie).filter(TMDBMovie.imdb_id == imdb_id).first()\n if not movie and title:\n movie_filter = session.query(TMDBMovie).filter(func.lower(TMDBMovie.name) == title.lower())\n if year:\n movie_filter = movie_filter.filter(TMDBMovie.year == year)\n movie = movie_filter.first()\n if not movie:\n found = session.query(TMDBSearchResult). \\\n filter(func.lower(TMDBSearchResult.search) == search_string).first()\n if found and found.movie:\n movie = found.movie\n if movie:\n # Movie found in cache, check if cache has expired.\n refresh_time = timedelta(days=2)\n if movie.released:\n if movie.released > datetime.now() - timedelta(days=7):\n # Movie is less than a week old, expire after 1 day\n refresh_time = timedelta(days=1)\n else:\n age_in_years = (datetime.now() - movie.released).days / 365\n refresh_time += timedelta(days=age_in_years * 5)\n if movie.updated < datetime.now() - refresh_time and not only_cached:\n log.debug('Cache has expired for %s, attempting to refresh from TMDb.' % id_str())\n try:\n ApiTmdb.get_movie_details(movie, session)\n except URLError:\n log.error('Error refreshing movie details from TMDb, cached info being used.')\n else:\n log.debug('Movie %s information restored from cache.' % id_str())\n else:\n if only_cached:\n raise LookupError('Movie %s not found from cache' % id_str())\n # There was no movie found in the cache, do a lookup from tmdb\n log.verbose('Searching from TMDb %s' % id_str())\n try:\n if imdb_id and not tmdb_id:\n result = tmdb3.Movie.fromIMDB(imdb_id)\n if result:\n movie = session.query(TMDBMovie).filter(TMDBMovie.id == result.id).first()\n if movie:\n # Movie was in database, but did not have the imdb_id stored, force an update\n ApiTmdb.get_movie_details(movie, session, result)\n else:\n tmdb_id = result.id\n if tmdb_id:\n movie = TMDBMovie()\n movie.id = tmdb_id\n ApiTmdb.get_movie_details(movie, session)\n if movie.name:\n session.merge(movie)\n else:\n movie = None\n elif title:\n try:\n result = _first_result(tmdb3.tmdb_api.searchMovie(title.lower(), adult=True, year=year))\n except (socket.timeout, URLError):\n raise LookupError('Error contacting TMDb')\n if not result and year:\n result = _first_result(tmdb3.tmdb_api.searchMovie(title.lower(), adult=True))\n if result:\n movie = session.query(TMDBMovie).filter(TMDBMovie.id == result.id).first()\n if not movie:\n movie = TMDBMovie(result)\n ApiTmdb.get_movie_details(movie, session, result)\n session.merge(movie)\n if title.lower() != movie.name.lower():\n session.merge(TMDBSearchResult(search=search_string, movie=movie))\n except tmdb3.TMDBError as e:\n raise LookupError('Error looking up movie from TMDb (%s)' % e)\n if movie:\n log.verbose(\"Movie found from TMDb: %s (%s)\" % (movie.name, movie.year))\n\n if not movie:\n raise LookupError('No results found from tmdb for %s' % id_str())\n else:\n session.commit()\n return movie\n\n @staticmethod\n def get_movie_details(movie, session, result=None):\n \"\"\"Populate details for this :movie: from TMDb\"\"\"\n\n if not result and not movie.id:\n raise LookupError('Cannot get tmdb details without tmdb id')\n if not result:\n try:\n result = tmdb3.Movie(movie.id)\n except tmdb3.TMDBError:\n raise LookupError('No results for tmdb_id: %s (%s)' % (movie.id, sys.exc_info()[1]))\n try:\n movie.update_from_object(result)\n except tmdb3.TMDBRequestInvalid as e:\n log.debug('Error updating tmdb info: %s' % e)\n raise LookupError('Error getting tmdb info')\n posters = result.posters\n if posters:\n # Add any posters we don't already have\n # TODO: There are quite a few posters per movie, do we need to cache them all?\n poster_urls = [p.url for p in movie.posters]\n for item in posters:\n for size in item.sizes():\n url = item.geturl(size)\n if url not in poster_urls:\n poster_data = {\"movie_id\": movie.id, \"size\": size, \"url\": url, \"file\": item.filename}\n movie.posters.append(TMDBPoster(poster_data))\n genres = result.genres\n if genres:\n for genre in genres:\n if not genre.id:\n continue\n db_genre = session.query(TMDBGenre).filter(TMDBGenre.id == genre.id).first()\n if not db_genre:\n db_genre = TMDBGenre(genre)\n if db_genre not in movie.genres:\n movie.genres.append(db_genre)\n movie.updated = datetime.now()\n\n\ndef _first_result(results):\n if results and len(results) >= 1:\n return results[0]\n\n\n@event('plugin.register')\ndef register_plugin():\n plugin.register(ApiTmdb, 'api_tmdb', api_ver=2)\n","sub_path":"flexget/plugins/api_tmdb.py","file_name":"api_tmdb.py","file_ext":"py","file_size_in_byte":16620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"284414151","text":"# -*- coding: utf-8 -*-\n#/usr/bin/python2\n'''\nJune 2017 by kyubyong park. \nkbpark.linguist@gmail.com.\nhttps://www.github.com/kyubyong/transformer\n'''\n\nfrom __future__ import print_function\nimport codecs\nimport os\n\nimport tensorflow as tf\nimport numpy as np\n\nfrom hyperparams import Hyperparams as hp\nfrom data_load_cploc_mask import load_test_data_cloze, load_dev_data,\\\n load_src_vocab, load_des_vocab\nfrom train_cploc_mask_v61 import Graph\nfrom nltk.translate.bleu_score import corpus_bleu\nfrom tqdm import tqdm\n\nhp.logdir = 'logdir_cploc_mask_v6'\nresult_dir = 'results_cploc_mask_v6'\nclue_level = 5\n\ndef remove_dup(x):\n if len(x) == 1:\n return x\n y = [x[0]]\n for w in x[1:]:\n if w == y[-1]:\n continue\n else:\n y.append(w)\n return y\n\ndef eval(stage='test', checkpoint_file=None, is_dedup=False, clue_level=1): \n # Load graph\n g = Graph(is_training=False, clue_level=clue_level)\n print(\"Graph loaded\")\n \n # Load data\n if stage == 'test':\n X, Y, XLoc, M, Sources, Targets = load_test_data_cloze()\n else: \n X, XLoc, M, Sources, Targets = load_dev_data()\n\n src2idx, idx2src = load_src_vocab()\n des2idx, idx2des = load_des_vocab()\n \n # X, Sources, Targets = X[:33], Sources[:33], Targets[:33]\n\n config = tf.ConfigProto() \n config.gpu_options.allow_growth=True \n config.allow_soft_placement=True\n\n num_gen = 0\n num_copy = 0 \n num_unk_copy = 0\n max_batch = 10\n\n # Start session \n with g.graph.as_default(): \n sv = tf.train.Supervisor()\n with sv.managed_session(config=config) as sess:\n if not checkpoint_file:\n checkpoint_file = tf.train.latest_checkpoint(hp.logdir)\n\n ## Restore parameters\n sv.saver.restore(sess, checkpoint_file)\n print(\"Restored! {}\".format(checkpoint_file))\n \n ## Get model name\n #mname = open(hp.logdir + '/checkpoint', 'r').read().split('\"')[1] # model name\n mname = checkpoint_file.split('/')[1]\n \n ## Inference\n if not os.path.exists(result_dir): os.mkdir(result_dir)\n with codecs.open(result_dir + \"/\" + mname + '.level{}'.format(clue_level) + '.' + stage, \"w\", \"utf-8\") as fout:\n list_of_refs, hypotheses = [], []\n for i in tqdm(range(min(max_batch, len(X) // hp.batch_size))):\n \n ### Get mini-batches\n x = X[i*hp.batch_size: (i+1)*hp.batch_size]\n y = Y[i*hp.batch_size: (i+1)*hp.batch_size]\n xloc = XLoc[i*hp.batch_size: (i+1)*hp.batch_size]\n m = M[i*hp.batch_size: (i+1)*hp.batch_size]\n sources = Sources[i*hp.batch_size: (i+1)*hp.batch_size]\n targets = Targets[i*hp.batch_size: (i+1)*hp.batch_size]\n \n ### Autoregressive inference\n preds = np.zeros((hp.batch_size, hp.y_maxlen), np.int32)\n preds_unk = np.zeros((hp.batch_size, hp.y_maxlen), np.int32)\n preds_xloc = np.zeros((hp.batch_size, hp.x_maxlen), np.int32) - 1\n preds_yloc = np.zeros((hp.batch_size, hp.y_maxlen), np.int32) - 1\n for j in range(hp.y_maxlen):\n # y_mask = y.copy()\n # y_mask[:,j] = 12\n # _preds, loc_logits = sess.run([g.preds, g.loc_logits], {g.x: x, g.y: y_mask, g.m: m, g.xloc: preds_xloc, g.yloc: preds_yloc})\n _preds, loc_logits = sess.run([g.preds, g.loc_logits], {g.x: x, g.y: preds_unk, g.m: m, g.xloc: preds_xloc, g.yloc: preds_yloc})\n #sess.run(tf.get_collection('save_op'), {g.x: x, g.y: y_mask, g.m: m, g.xloc: preds_xloc, g.yloc: preds_yloc})\n\n # print(_preds[0])\n # input()\n preds[:, j] = _preds[:, j]\n \n preds_unk[:, j] = _preds[:, j]\n preds_unk[preds_unk>=len(idx2des)] = 1\n\n for i in range(hp.batch_size):\n xloc = np.zeros(hp.x_maxlen, dtype=np.int32) - 1\n yloc = np.zeros(hp.y_maxlen, dtype=np.int32) - 1\n\n source_words = sources[i].split()\n target_words = []\n for idx in preds[i]:\n if idx in idx2des:\n target_words.append(idx2des[idx])\n elif idx - len(idx2des) == len(source_words):\n target_words.append('')\n else:\n cp_word_idx = idx - len(idx2des)\n cp_word = source_words[cp_word_idx]\n target_words.append(cp_word)\n source_sent_np = np.array(source_words)\n target_sent_np = np.array(target_words)\n source_wset = set(source_words)\n target_wset = set(target_words)\n for loc_id, w in enumerate(target_wset & source_wset):\n xloc[np.where(source_sent_np==w)] = loc_id\n yloc[np.where(target_sent_np==w)] = loc_id\n preds_xloc[i] = xloc \n preds_yloc[i] = yloc\n #print(loc_logits.shape)\n #print(loc_logits[0][j][:20])\n #input()\n\n ### Write to file\n for source, target, m_, pred in zip(sources, targets, m, preds): # sentence-wise\n got_display = []\n got = []\n source_words = np.array(source.split())\n for idx in pred:\n if idx in idx2des:\n num_gen += 1\n got.append(idx2des[idx])\n got_display.append(idx2des[idx]+'[{}]'.format(idx))\n else:\n num_copy += 1\n cp_word_idx = idx - len(idx2des)\n cp_word = source_words[cp_word_idx]\n got.append(cp_word)\n got_display.append(cp_word+'[{},{}]'.format(cp_word_idx, m_[cp_word_idx]))\n if cp_word not in des2idx:\n num_unk_copy += 1\n \n if is_dedup:\n got = remove_dup(got)\n got_display = remove_dup(got_display)\n\n got = \" \".join(got).split(\"\")[0].strip()\n got_display = \" \".join(got_display).split(\"\")[0].strip()\n #if got.count(''):\n # last_char = got.index('')\n #else:\n # last_char = len(got)\n #got = \" \".join(got[:last_char+1])\n #got_display = \" \".join(got_display)\n fout.write(\"- source: \" + source +\"\\n\")\n fout.write(\"- expected: \" + target + \"\\n\")\n fout.write(\"- got: \" + got + \"\\n\")\n fout.write(\"- analyse: \" + got_display + \"\\n\\n\")\n fout.flush()\n \n # bleu score\n ref = target.split()\n hypothesis = got.split()\n if len(ref) > 3 and len(hypothesis) > 3:\n list_of_refs.append([ref])\n hypotheses.append(hypothesis)\n\n ## Calculate bleu score\n score = corpus_bleu(list_of_refs, hypotheses)\n fout.write(\"Bleu Score = \" + str(100*score) + \"\\n\")\n score = corpus_bleu(list_of_refs, hypotheses, weights=(1, 0, 0, 0))\n fout.write(\"Bleu@1 Score = \" + str(100*score) + \"\\n\")\n score = corpus_bleu(list_of_refs, hypotheses, weights=(0, 1, 0, 0))\n fout.write(\"Bleu@2 Score = \" + str(100*score) + \"\\n\")\n score = corpus_bleu(list_of_refs, hypotheses, weights=(0, 0, 1, 0))\n fout.write(\"Bleu@3 Score = \" + str(100*score) + \"\\n\")\n score = corpus_bleu(list_of_refs, hypotheses, weights=(0, 0, 0, 1))\n fout.write(\"Bleu@4 Score = \" + str(100*score) + \"\\n\")\n fout.write(\"Generate / Copy / UNK Copy = {} / {} / {}\".format(num_gen, num_copy, num_unk_copy))\n \nif __name__ == '__main__':\n all_models = open(hp.logdir + '/checkpoint', 'r').readlines()\n all_models = [hp.logdir + '/' + all_models[i].split('\"')[1] for i in range(len(all_models))]\n\n for f in all_models[-1:]:\n for clue_level in [1, 2, 3, 5]:\n eval('test', f, True, clue_level)\n eval('dev', f, True, clue_level)\n \n print(\"Done\")\n \n \n","sub_path":"eval_cploc_mask_v6.py","file_name":"eval_cploc_mask_v6.py","file_ext":"py","file_size_in_byte":9438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"446455392","text":"def Binsearch(data, key):\n awal = 1\n akhir = len(data) + 1\n ketemu = False\n while (awal <= akhir) and not ketemu:\n tengah = int((awal + akhir)/2)\n if key == data[tengah]:\n ketemu = True\n print('data', key, 'ditemukan di posisi', tengah,'dari data setelah di urutkan')\n elif (key < data[tengah]):\n akhir = tengah - 1\n else:\n awal = tengah + 1\n if ketemu == False:\n print('data tidak ditemukan')\n\na = 'rafsanjani rahadi'\nb = 'a'\nBinsearch(a,b)\n\n","sub_path":"Alpro 1/P6-b.py","file_name":"P6-b.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"64993900","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom scipy.integrate import odeint\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nplt.style.use('ggplot')\n\n# System Parameters\np1, p2, p3, fd1, fd2 = 3.473, 0.196, 0.242, 5.3, 1.1\n\n# Define NN\n'''\nclass Net(nn.Module):\n def __init__(self):\n super(Net,self).__init__()\n self.fc1 = nn.Linear(2,10)\n self.fc2 = nn.Linear(10,1)\n \n def forward(self,x):\n x1 = torch.sigmoid(self.fc1(x))\n return torch.sigmoid(self.fc2(x1))\n'''\n\nclass Net():\n def __init__(self):\n self.w1 = torch.rand(2,10,requires_grad=True)\n self.w2 = torch.rand(10,2,requires_grad=True)\n \n def forward(self,x):\n x1 = torch.sigmoid(torch.matmul(x,self.w1))\n return torch.sigmoid(torch.matmul(x1,self.w2))\n\ndef policy(x):\n if np.abs(x[0]+x[1])>=.1:\n u = [[-3],[-2]]\n else:\n u=[[0],[0]]\n return u\n\ndef distrubance(t):\n return [[0.5*np.cos(0.5*t)],[np.sin(t)]]\n\ndef model(x,t,policy,disturbance):\n c1=np.cos(x[0])\n c2=np.cos(x[1])\n s1=np.sin(x[0])\n s2=np.sin(x[1])\n \n fs1=1\n fs2 =1\n u=policy(x)\n M=np.array([[p1+2*p2*c2,p2+p3*c2],\n [p2+p3*c2,p2]])\n C=np.array([[-p3*s2*x[3],-p3*s2*(x[2]+x[3])],\n [p3*s2*x[2],0]])\n D=np.array([[fd1,0],\n [0,fd2]])\n S = np.array([[fs1,0],\n [0,fs2]])\n \n x3x4dot = np.linalg.inv(M)@(-(C+D)@[[x[2]],[x[3]]]-S@distrubance(t)+u)\n \n return [x[2],x[3],x3x4dot[0][0],x3x4dot[1][0]]\n\ndef Q_approximation(net_x,u):\n \n \n return torch.norm(u) + torch.dot(u,net_x) \n\ndef Temperal_difference(x,k,Q_net):\n # Define desired trajectory\n x_d = torch.tensor([math.cos(0.5*k),2*math.cos(k)])\n \n # Cost function\n c = x - x_d\n \n # Pass x through the net\n x_net = Q_net.forward(x)\n print(x_net)\n \n # Define loss function for nn\n Loss = 0.5*Q_approximation(x_net,-x_net)\n print(Loss)\n \n Loss.backward()\n print(Q_net.w1.grad)\n return Q_net.w1.grad\n\n'''\nxinit=[0,0,0,0]\nt=np.linspace(0,100,1000)\n\n\nx = odeint(model,xinit,t,args=(policy,distrubance,))\n\nfig, axs =plt.subplots(2,1)\naxs[0].plot(t,x[:,0],t,x[:,1])\naxs[0].legend(['$q_1$','$q_2$'])\naxs[1].plot(t,x[:,2],t,x[:,3])\naxs[1].set_xlabel('$t$')\naxs[1].legend(['$\\dot{q}_1$','$\\dot{q}_2$'])\n'''\n\n# random seed\ntorch.manual_seed(200)\nnet = Net()\nx = torch.tensor([1.0,2.0])\nTemperal_difference(x,1.0,net)\n\n","sub_path":"TD_lambda.py","file_name":"TD_lambda.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"271248092","text":"from django.shortcuts import render,HttpResponse\nfrom django.core.paginator import Paginator\nimport requests\nimport json\n# Create your views here.\n\ndef carga_info(request,cluster):\n\tdatos = request.session['datos_api']\n\tclusters = datos[1]\n\tclusters = list( filter( lambda ins: int(ins['instancia'][0]) == cluster , clusters) )\n\tprint(clusters , \"\\n\")\n\tdatos = [datos[0],clusters]\n\treturn render(request,\"core/info-cluster.html\",{'datos':datos,'cluster':cluster,'clusters':clusters})\n\n\ndef algoritmo(request):\n\turl = 'https://cloudxapi.herokuapp.com/cluster/EM';\n\tdatos = True\n\tparams = {}\n\tpagina_actual = 0\n\tpaginas = 0\n\tposts = []\n\tif request.POST.get('query'):\n\t\t\n\t\tbody = request.POST\n\t\tparams = {\n\t\t\t\t\"queryBD\": body.get('query').strip(),\n\t\t\t\t\"numFolds\": body.get('numFolds'),\n\t\t\t\t\"numKMeansRuns\": body.get('numKMeansRuns'),\n\t\t\t\t\"maximumNumberOfClusters\": body.get('maximumNumberOfClusters'),\n\t\t\t\t\"numClusters\": body.get('numClusters'),\n\t\t\t\t\"maxIterations\": body.get('maxIterations')\n\t\t\t};\n\n\t\tresponse = generate_request(url,params)\n\t\t# if response != False:\n\t\t# \t(response['valsInstances']).sort(key=lambda ins: int(ins['instancia'][0]))\n\t\t# \tpaginator = Paginator(response['valsInstances'],5)\n\t\t# \tpagina = request.GET.get(\"page\") or 1\n\t\t# \tposts = paginator.get_page(pagina)\n\t\t# \tpagina_actual = int(pagina)\n\t\t# \tpaginas = range(1,posts.paginator.num_pages + 1)\n\t\t# \tdatos = [response['attributes'],posts,response['infoCluster'],response['graph']]\n\t\t# \trequest.session['datos_api'] = datos\n\t\tif response != False:\n\n\t\t\t(response['valsInstances']).sort(key=lambda ins: int(ins['instancia'][0]))\n\t\t\t(response['AttSummaryPanel']).sort( key=lambda ins: int(ins[2]) ,reverse=True )\n\t\t\trequest.session['datos_api'] = [ response['attributes'] ,response['valsInstances'] ]\n\t\t\tdatos = [response['attributes'],response['valsInstances'],response['infoCluster'],response['graph'],response['AttSummaryPanel']]\n\n\t\t\t# datos_figura = list()\n\n\t\t\t# for i in response['AttSummaryPanel']:\n\t\t\t# \tprint(i)\n\n\n\t\t\t# print(response['AttSummaryPanel'])\n\t\telse:\n\t\t\tdatos = None\n\n\t# elif request.session['query_instancias'] is not None:\n\t# \tpaginator = Paginator(request.session['query_instancias'],5)\n\t# \tpagina = request.GET.get(\"page\") or 1\n\t# \tposts = paginator.get_page(pagina)\n\t# \tpagina_actual = int(pagina)\n\t# \tpaginas = range(1,posts.paginator.num_pages + 1)\n\t# \tdatos = request.session['datos_api']\n\n\t\t\n\t#return render(request,\"core/algoritmo.html\",{'datos':datos,'datos_Form':params,\"pagina_actual\":pagina_actual,\"paginas\":paginas,\"posts\":posts})\n\treturn render(request,\"core/algoritmo.html\",{'datos':datos,'datos_Form':params})\n\n\ndef generate_request(url, params={}):\n\tdataJson = False\n\t_headers = {\"Content-Type\":\"application/json\"}\n\tresponse = requests.post(url,data=json.dumps(params),headers = _headers)\n\tif response.status_code == 200:\n\t\tdataJson = response.json()\n\n\treturn dataJson\n\n","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"303329793","text":"\"\"\"Fichier d'installation du script Yam.py.\"\"\"\n\nfrom cx_Freeze import setup, Executable\nimport os\nimport sys\n\nos.environ['TCL_LIBRARY'] = r'C:\\\\Python37\\\\tcl\\\\tcl8.6'\nos.environ['TK_LIBRARY'] = r'C:\\\\Python37\\\\tcl\\\\tk8.6'\n\n\nif sys.platform == \"win32\":\n\tbase = \"Win32GUI\"\n\nsetup(\n name = \"Yam\",\n version = \"1.0\",\n description = \"Yam game\",\n author = \"Rémi Caulier\",\n options = {\"build_exe\": {\"packages\": [\"pygame\", \"tkinter\"],\n \t\t\t\t\t\t\"include_files\": ['Files/']}},\n executables = [Executable(\"Yam.py\", base = base)],\n)","sub_path":"Client/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"582319563","text":"\"\"\"\nA registration profile model and associated manager.\n\nThe RegistrationProfile model and especially its custom manager\nimplement nearly all the logic needed to handle user registration and\naccount activation, so before implementing something in a view or\nform, check here to see if they can take care of it for you.\n\nAlso, be sure to see the note on RegistrationProfile about use of the\n``AUTH_PROFILE_MODULE`` setting.\n\n\"\"\"\nfrom django.http import *\nimport datetime, random, re, sha\nfrom django.db import models\nfrom django.template import Context, loader\nfrom django.contrib.auth.models import User\nfrom django.contrib.sites.models import Site\nfrom django.conf import settings\nfrom django.template import RequestContext\nfrom django.utils.timezone import utc\nfrom django.core.mail import EmailMessage\nclass RegistrationManager(models.Manager):\n\t\"\"\"\n\tCustom manager for the RegistrationProfile model.\n\n\tThe methods defined here provide shortcuts for account creation\n\tand activation (including generation and emailing of activation\n\tkeys), and for cleaning out expired inactive accounts.\n\n\t\"\"\"\n\tdef activate_user(self, activation_key):\n\t\t\"\"\"\n\t\tGiven the activation key, makes a User's account active if the\n\t\tactivation key is valid and has not expired.\n\t\t\n\t\tReturns the User if successful, or False if the account was\n\t\tnot found or the key had expired.\n\t\t\n\t\t\"\"\"\n\t\t# Make sure the key we're trying conforms to the pattern of a\n\t\t# SHA1 hash; if it doesn't, no point even trying to look it up\n\t\t# in the DB.\n\t\tif re.match('[a-f0-9]{40}', activation_key):\n\t\t\ttry:\n\t\t\t\tuser_profile = self.get(activation_key=activation_key)\n\t\t\texcept self.model.DoesNotExist:\n\t\t\t\treturn False\n\t\t\tif not user_profile.activation_key_expired():\n\t\t\t\t# Account exists and has a non-expired key. Activate it.\n\t\t\t\tuser = user_profile.user\n\t\t\t\tuser.is_active = True\n\t\t\t\tuser.save()\n\t\t\t\treturn user\n\t\treturn False\n\n\tdef create_inactive_user(self, username, password, fname, lname, email, send_email=True):\n\t\t\"\"\"\n\t\tCreates a new User and a new RegistrationProfile for that\n\t\tUser, generates an activation key, and mails it.\n\t\t\n\t\tPass ``send_email=False`` to disable sending the email.\n\t\t\n\t\t\"\"\"\n\t\t# Create the user.\n\t\tnew_user = User.objects.create_user(username, email, password)\n\t\tnew_user.is_active = False\n\t\tnew_user.first_name = fname\n\t\tnew_user.last_name = lname\n\t\tnew_user.save()\n\t\t\n\t\t# Generate a salted SHA1 hash to use as a key.\n\t\tsalt = sha.new(str(random.random())).hexdigest()[:5]\n\t\tactivation_key = sha.new(salt+new_user.username).hexdigest()\n\t\t\n\t\t# And finally create the profile.\n\t\tnew_profile = self.create(user=new_user,\n\t\t\t\t\t\t\t\t\tactivation_key=activation_key)\n\t\t\n\t\tif send_email:\n\t\t\tfrom django.core.mail import send_mail\n\t\t\tcurrent_domain = Site.objects.get_current().domain\n\t\t\tsubject = \"Activate your new account at %s\" % current_domain\n\t\t\tmessage_template = loader.get_template('registration/activation_email.txt')\n\t\t\tmessage_context = Context({ 'site_url': 'http://%s/' % current_domain,\n\t\t\t\t\t\t\t\t\t\t'activation_key': activation_key,\n\t\t\t\t\t\t\t\t\t\t'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS })\n\t\t\tmessage = message_template.render(message_context)\n\t\t\tEmailMessage(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email])\n\t\treturn new_user\n\n\tdef delete_expired_users(self):\n\t\t\"\"\"\n\t\tRemoves unused profiles and their associated accounts.\n\n\t\tThis is provided largely as a convenience for maintenance\n\t\tpurposes; if a RegistrationProfile's key expires without the\n\t\taccount being activated, then both the RegistrationProfile and\n\t\tthe associated User become clutter in the database, and (more\n\t\timportantly) it won't be possible for anyone to ever come back\n\t\tand claim the username. For best results, set this up to run\n\t\tregularly as a cron job.\n\t\t\n\t\tIf you have a User whose account you want to keep in the\n\t\tdatabase even though it's inactive (say, to prevent a\n\t\ttroublemaker from accessing or re-creating his account), just\n\t\tdelete that User's RegistrationProfile and this method will\n\t\tleave it alone.\n\t\t\n\t\t\"\"\"\n\t\tfor profile in self.all():\n\t\t\tif profile.activation_key_expired():\n\t\t\t\tuser = profile.user\n\t\t\t\tif not user.is_active:\n\t\t\t\t\tuser.delete() # Removing the User will remove the RegistrationProfile, too.\n\n\nclass RegistrationProfile(models.Model):\n\t\"\"\"\n\tSimple profile model for a User, storing a registration date and\n\tan activation key for the account.\n\t\n\tWhile it is possible to use this model as the value of the\n\t``AUTH_PROFILE_MODULE`` setting, it's not recommended that you do\n\tso. This model is intended solely to store some data needed for\n\tuser registration, and can do that regardless of what you set in\n\t``AUTH_PROFILE_MODULE``, so if you want to use user profiles in a\n\tproject, it's far better to develop a customized model for that\n\tpurpose and just let this one handle registration.\n\t\n\t\"\"\"\n\tuser = models.ForeignKey(User, unique=True)\n\tactivation_key = models.CharField(max_length=40)\n\tkey_generated = models.DateTimeField()\n\t\n\tobjects = RegistrationManager()\n\t\n\tclass Admin:\n\t\tpass\n\t\n\tdef save(self,*args, **kwargs):\n\t\tif not self.id:\n\t\t\tself.key_generated = datetime.datetime.now()\n\t\tsuper(RegistrationProfile, self).save(*args, **kwargs)\n\t\n\tdef __str__(self):\n\t\treturn \"User profile for %s\" % self.user.username\n\t\n\tdef activation_key_expired(self):\n\t\t\"\"\"\n\t\tDetermines whether this Profile's activation key has expired,\n\t\tbased on the value of the setting ``ACCOUNT_ACTIVATION_DAYS``.\n\t\t\n\t\t\"\"\"\n\t\texpiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)\n\t\treturn self.key_generated + expiration_date <= datetime.datetime.utcnow().replace(tzinfo=utc)\n\n","sub_path":"registration/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"615799723","text":"import sys\nimport logging\nimport traceback\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as ec\n\nimport json\nimport time\nimport re\n \n\n\ntry:\n \n #Log Vars\n log_file = \"instagrambot.log\"\n \n logger = logging.getLogger(__name__)\n logger.setLevel(logging.INFO)\n\n handler = logging.FileHandler(log_file)\n handler.setLevel(logging.INFO)\n\n formatter = logging.Formatter(\"%(asctime)s - %(levelname)s - %(message)s\")\n handler.setFormatter(formatter)\n\n logger.addHandler(handler)\n \n \n \n #General Vars\n debug = False\n error_trace = False\n \n base_url = \"\"\n sub_url = \"\"\n\n \n \n #Objects\n browser = None\n \n\n\n #Fonctions \n def write_log(l, s):#l => 1: info, 2:warning, 3:error\n global debug\n \n logger.info('%s', str(s))\n \n if debug:\n print(\"LOG -> level:\" + str(l) + \" - \" + str(s))\n \n def args_control():\n if len(sys.argv) != 2:\n write_log(2, \"Args invalid\" + str(sys.argv))\n sys.exit(1)\n \n write_log(1, \"Args OK\")\n \n def fill_vars():\n global browser, sub_url\n sub_url = sys.argv[1] \n browser = get_browser()\n \n write_log(1, \"Vars filled\")\n\n def get_browser():\n global debug\n \n if debug:\n temp = webdriver.Chrome(\"./chromedriver\") \n else:\n options = webdriver.ChromeOptions()\n options.add_argument('--headless')\n options.add_argument('--no-sandbox')\n options.add_argument('--disable-dev-shm-usage')\n options.add_argument('--disable-gpu') \n options.add_argument('--user-data-dir=/var/www/html/insta/data') \n temp = webdriver.Chrome(\"./chromedriver\", options=options)\n \n write_log(1, \"Browser created\") \n return temp\n \n def go_to_page(url):\n global browser\n browser.get(url)\n write_log(1, \"Go url: \" + url)\n \n def go_to_media_file():\n global base_url, sub_url\n go_to_page(base_url+sub_url)\n \n def account_login():\n global browser\n username=\"\"\n password=\"\"\n browser.get(\"https://www.instagram.com/accounts/login\")\n time.sleep(5)\n user_uls = browser.find_element_by_xpath('.//input[@name=\"username\"]')\n time.sleep(5)\n user_uls.send_keys(username)\n password = browser.find_element_by_xpath('.//input[@name=\"password\"]').send_keys(password)\n login_button=browser.find_element_by_xpath('//*[@id=\"react-root\"]/section/main/div/article/div/div[1]/div/form/div[4]/button/div').click()\n time.sleep(5) \n def new_tab_chrome():\n browser.execute_script(\"window.open('https://www.instagram.com');\")\n \n def fill_all_comments_on_page():\n global browser\n \n try:\n while True:\n WebDriverWait(browser, 1).until(ec.element_to_be_clickable((By.CLASS_NAME, \"dCJp8\")))\n more = browser.find_element_by_class_name(\"dCJp8\")\n more.click()\n except Exception as e:\n temp = True\n def strip_emoji(text):\n a = re.compile('[\\U00010000-\\U0010ffff]', flags=re.UNICODE)\n return a.sub(r'', text)\n def get_data_from_page():\n data = []\n user_uls = browser.find_elements_by_xpath('//ul[contains(@class,\"Mr508\")]')\n for user_ul in user_uls:\n username = user_ul.find_element_by_xpath('.//h3//a').text\n comment = user_ul.find_element_by_xpath('.//div[@class=\"C4VMK\"]//span').text\n comment=strip_emoji(comment)\n photo = user_ul.find_element_by_xpath('.//div[@class=\"P9YgZ\"]//div//div//a//img').get_attribute(\"src\")\n temp = {\"username\": username, \"comment\": comment, \"photo\": photo}\n data.append(temp)\n \n return data\n def get_data():\n #account_login()\n go_to_media_file()\n fill_all_comments_on_page()\n data = get_data_from_page()\n \n close_browser()\n \n return data\n \n def print_data(data):\n for i in data:\n print(json.dumps(i))\n\n def close_browser():\n global browser \n browser.quit()\n \n write_log(1, \"Browser closed\")\n \n def main():\n args_control()\n fill_vars()\n \n data = get_data()\n \n print_data(data)\n\n #Main\n if __name__ == \"__main__\":\n write_log(1, \"Started\") \n main()\n\n\n \nexcept SystemExit as e:\n sys.exit(e)\n \nexcept Exception as e:\n try:\n write_log(3, \"Error handled\")\n except Exception as ee:\n def write_log(l, s):\n m = \"Level: \" + str(l) + \" - \" + str(s)\n print(m)\n with open(log_file, \"a\") as f:\n f.write(m)\n \n write_log(3, \"Error handled\")\n \n exc_type, exc_obj, exc_tb = sys.exc_info() \n write_log(3, \"General error! \" + str(e) + \" (line: \" + str(exc_tb.tb_lineno) + \")\")\n \n if error_trace:\n print(traceback.print_exc())\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"8553759","text":"import pytest\n\nfrom app.modules.projects.application.archivization_service import ArchivizationService\nfrom app.modules.projects.application.testing.fake_project_repository import FakeProjectRepository\nfrom app.modules.projects.application.testing.fake_unit_of_work import FakeUnitOfWork\nfrom app.modules.projects.domain.project_builder import ProjectBuilder\nfrom app.utc_datetime import utc_now\n\n\nclass TestArchiveService:\n @pytest.fixture()\n def fake_project_repository(self):\n return FakeProjectRepository()\n\n @pytest.fixture()\n def fake_unit_of_work(self, fake_project_repository):\n return FakeUnitOfWork(repository=fake_project_repository)\n\n @pytest.fixture()\n def service(self, fake_unit_of_work):\n return ArchivizationService(uow=fake_unit_of_work)\n\n def test_archive(\n self,\n fake_project_repository: FakeProjectRepository,\n service: ArchivizationService,\n fake_unit_of_work: FakeUnitOfWork,\n ):\n # Given\n project = fake_project_repository.create(ProjectBuilder().build())\n\n # When\n service.archive(project.id)\n\n # Then\n assert fake_unit_of_work.committed is True\n assert project.archived is True\n\n def test_unarchive(\n self,\n fake_project_repository: FakeProjectRepository,\n service: ArchivizationService,\n fake_unit_of_work: FakeUnitOfWork,\n ):\n # Given\n project = fake_project_repository.create(ProjectBuilder().build())\n project.archive(now=utc_now())\n\n # When\n service.unarchive(project.id)\n\n # Then\n assert fake_unit_of_work.committed is True\n assert project.archived is False\n","sub_path":"app/modules/projects/application/archivization_service_test.py","file_name":"archivization_service_test.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"19143229","text":"# model script to load to main.py g\n\nimport numpy as np\nimport pandas as pd\nfrom joblib import load\nfrom sklearn.preprocessing import StandardScaler\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\n\n\n# formater for single input\ndef format_features(brewery_name: int, review_aroma: int, review_appearance: int, review_palate: int, review_taste: int):\n \n return {\n 'brewery_name': [brewery_name],\n 'review_aroma': [review_aroma],\n 'review_appearance': [review_appearance],\n 'review_palate': [review_palate],\n 'review_taste': [review_taste]\n }\n\n# formater for multi input\ndef format_features_multi(brewery_name: list, review_aroma: list, review_appearance: list, review_palate: list,\n review_taste: list):\n return {\n 'brewery_name': brewery_name,\n 'review_aroma': review_aroma,\n 'review_appearance': review_appearance,\n 'review_palate': review_palate,\n 'review_taste': review_taste\n }\n\n# load scaler\ndef apply_scaler(obs):\n '''Applies scaler to num_cols'''\n \n num_cols = ['review_aroma','review_appearance','review_palate','review_taste']\n scaler = load('../models/scaler.joblib')\n obs[num_cols] = scaler.fit_transform(obs[num_cols])\n \n return obs\n\n# load label encoder\ndef apply_name_encoder(obs):\n '''Applies label encoder to cat_cols'''\n\n cat_cols = ['brewery_name']\n name_encoder = load('../models/name_encoder.joblib')\n obs[cat_cols] = name_encoder.fit_transform(obs[cat_cols])\n\n return obs\n\n# create tensors for single input\ndef single_tensor(obs):\n \"\"\"Converts single row to tensor \"\"\"\n data_cat = []\n data_cont = []\n num_cols = ['review_aroma','review_appearance','review_palate','review_taste']\n data_cat = torch.tensor(obs['brewery_name'].to_numpy())\n data_cont = torch.tensor(obs[num_cols].to_numpy())\n \n data = [data_cat, data_cont]\n result = {'data': data}\n \n return result\n\n# Dataset creator for embedding for multi input\nclass EmbeddingDataset(Dataset):\n def __init__(self, data, targets=None,\n is_train=True, cat_cols_idx=None,\n cont_cols_idx=None):\n self.data = data\n self.targets = targets\n self.is_train = is_train\n self.cat_cols_idx = cat_cols_idx\n self.cont_cols_idx = cont_cols_idx\n \n def __getitem__(self, idx):\n row = self.data[idx].astype('float32')\n \n data_cat = []\n data_cont = []\n \n result = None\n \n if self.cat_cols_idx:\n data_cat = torch.tensor(row[self.cat_cols_idx])\n \n if self.cont_cols_idx:\n data_cont = torch.tensor(row[self.cont_cols_idx])\n \n data = [data_cat, data_cont]\n \n if self.is_train:\n result = {'data': data,\n 'target': torch.tensor(self.targets[idx])}\n else:\n result = {'data': data}\n \n return result\n \n \n def __len__(self):\n return(len(self.data))\n \n# embedding class - need to load model\nclass ClassificationEmbdNN(torch.nn.Module):\n \n def __init__(self, emb_dims, no_of_cont=None):\n super(ClassificationEmbdNN, self).__init__()\n \n self.emb_layers = torch.nn.ModuleList([torch.nn.Embedding(x, y)\n for x, y in emb_dims])\n \n no_of_embs = sum([y for x, y in emb_dims])\n self.no_of_embs = no_of_embs\n self.emb_dropout = torch.nn.Dropout(0.2)\n \n self.no_of_cont = 0\n if no_of_cont:\n self.no_of_cont = no_of_cont\n self.bn_cont = torch.nn.BatchNorm1d(no_of_cont)\n \n self.fc1 = torch.nn.Linear(in_features=self.no_of_embs + self.no_of_cont, \n out_features=208)\n self.dropout1 = torch.nn.Dropout(0.2)\n self.bn1 = torch.nn.BatchNorm1d(208)\n self.act1 = torch.nn.ReLU()\n \n self.fc2 = torch.nn.Linear(in_features=208, \n out_features=208)\n self.dropout2 = torch.nn.Dropout(0.2)\n self.bn2 = torch.nn.BatchNorm1d(208)\n self.act2 = torch.nn.ReLU()\n \n# self.fc3 = torch.nn.Linear(in_features=256, \n# out_features=64)\n# self.dropout3 = torch.nn.Dropout(0.2)\n# self.bn3 = torch.nn.BatchNorm1d(64)\n# self.act3 = torch.nn.ReLU()\n \n self.fc3 = torch.nn.Linear(in_features=208, \n out_features=104)\n self.act3 = torch.nn.Softmax()\n \n def forward(self, x_cat, x_cont=None):\n if self.no_of_embs != 0:\n x = [emb_layer(x_cat[:, i])\n for i, emb_layer in enumerate(self.emb_layers)]\n \n x = torch.cat(x, 1)\n x = self.emb_dropout(x)\n \n if self.no_of_cont != 0:\n x_cont = self.bn_cont(x_cont)\n \n if self.no_of_embs != 0:\n x = torch.cat([x, x_cont], 1)\n else:\n x = x_cont\n \n x = self.fc1(x)\n x = self.dropout1(x)\n x = self.bn1(x)\n x = self.act1(x)\n \n x = self.fc2(x)\n x = self.dropout2(x)\n x = self.bn2(x)\n x = self.act2(x)\n \n# x = self.fc3(x)\n# x = self.dropout3(x)\n# x = self.bn3(x)\n# x = self.act3(x)\n \n x = self.fc3(x)\n x = self.act3(x)\n \n return x\n \n# get model and load\ndef get_model():\n \n # load model obj\n model = ClassificationEmbdNN(emb_dims=[[5742,252]],no_of_cont=4)\n #model = torch.load('../models/model.pt')\n #set to trained dict of weights\n model.load_state_dict(torch.load('../models/embed_3layers.pt'))\n\n return model\n \n# function to predict from obs\ndef predict(obs, model, single=False):\n \"\"\"obs = dataset as tensor embed obj\n model = model state_dict loaded\n single = set to true if single input\"\"\"\n \n # set to eval\n model.eval()\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n \n model.to(device)\n \n with torch.no_grad():\n predictions = None\n \n if single:\n output = model(obs['data'][0].unsqueeze(dim=0).to(device, \n dtype=torch.long), \n obs['data'][1].to(device,\n dtype=torch.float)).cpu().numpy()\n else:\n\n obs_loader = DataLoader(obs, batch_size=len(obs))\n\n for i, batch in enumerate(obs_loader):\n \n output = model(batch['data'][0].to(device, \n dtype=torch.long), \n batch['data'][1].to(device, \n dtype=torch.float)).cpu().numpy()\n \n if i == 0:\n predictions = output\n \n else: \n \n predictions = np.vstack((predictions, output)) \n\n predictions = output\n \n from joblib import load\n label_encoders = load('../models/label_encoders.joblib')\n label = label_encoders['beer_style'].inverse_transform(predictions.argmax(1))\n\n return label\n \n\n","sub_path":"app/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":7437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"615161128","text":"#coding: utf-8\r\n# +-------------------------------------------------------------------\r\n# | 宝塔Windows面板\r\n# +-------------------------------------------------------------------\r\n# | Copyright (c) 2015-2099 宝塔软件(http://www.bt.cn) All rights reserved.\r\n# +-------------------------------------------------------------------\r\n# | Author: 曹觉心 <314866873@qq.com> \r\n# +-------------------------------------------------------------------\r\nimport os ,public ,json ,sys #line:9\r\nfrom flask import request ,redirect ,g #line:11\r\nfrom BTPanel import session ,cache #line:12\r\nfrom datetime import datetime #line:13\r\nclass dict_obj :#line:15\r\n def __contains__ (O0O00OOOO00000O0O ,OOO000O0O0O0OO0O0 ):#line:16\r\n return getattr (O0O00OOOO00000O0O ,OOO000O0O0O0OO0O0 ,None )#line:17\r\n def __setitem__ (OOO0O00O0O000O0OO ,OO0O00OO0OO0O0OO0 ,O0O0O0O000OOOOO00 ):setattr (OOO0O00O0O000O0OO ,OO0O00OO0OO0O0OO0 ,O0O0O0O000OOOOO00 )#line:18\r\n def __getitem__ (OOOOO0O00O00O0O0O ,OO0O00OOOOO0O00O0 ):return getattr (OOOOO0O00O00O0O0O ,OO0O00OOOOO0O00O0 ,None )#line:19\r\n def __delitem__ (OOO00O0O00OO0OO0O ,OOO0O0OO0O0O00OO0 ):delattr (OOO00O0O00OO0OO0O ,OOO0O0OO0O0O00OO0 )#line:20\r\n def __delattr__ (O0OO00OOO0O0O0000 ,OO0OOO0OOO000O00O ):delattr (O0OO00OOO0O0O0000 ,OO0OOO0OOO000O00O )#line:21\r\n def get_items (OOOO00O00O000OOOO ):return OOOO00O00O000OOOO #line:22\r\nclass panelSetup :#line:25\r\n def init (O00O0O00OO0OOO0O0 ):#line:26\r\n O0O0O00OOOO0O0OOO =request .headers .get ('User-Agent')#line:27\r\n if O0O0O00OOOO0O0OOO :#line:28\r\n O0O0O00OOOO0O0OOO =O0O0O00OOOO0O0OOO .lower ();#line:29\r\n if O0O0O00OOOO0O0OOO .find ('spider')!=-1 or O0O0O00OOOO0O0OOO .find ('bot')!=-1 :return redirect ('https://www.baidu.com');#line:30\r\n g .version ='6.5.0'#line:32\r\n g .title =public .GetConfigValue ('title')#line:33\r\n g .uri =request .path #line:34\r\n g .setup_path =public .GetConfigValue ('setup_path')#line:35\r\n g .recycle_bin_open =0 #line:36\r\n if os .path .exists (\"data/recycle_bin.pl\"):g .recycle_bin_open =1 #line:37\r\n public .writeFile (\"data/panel.version\",g .version )#line:39\r\n session ['version']=g .version ;#line:41\r\n session ['title']=g .title #line:42\r\n return None #line:43\r\nclass panelAdmin (panelSetup ):#line:46\r\n setupPath =os .getenv (\"BT_SETUP\")#line:47\r\n def local (OOOO000O00000O0OO ):#line:50\r\n OOOOO00O0O0O0O0OO =panelSetup ().init ()#line:51\r\n if OOOOO00O0O0O0O0OO :return OOOOO00O0O0O0O0OO #line:52\r\n OOOOO00O0O0O0O0OO =OOOO000O00000O0OO .checkLimitIp ()#line:53\r\n if OOOOO00O0O0O0O0OO :return OOOOO00O0O0O0O0OO #line:54\r\n OOOOO00O0O0O0O0OO =OOOO000O00000O0OO .setSession ();#line:55\r\n if OOOOO00O0O0O0O0OO :return OOOOO00O0O0O0O0OO #line:56\r\n OOOOO00O0O0O0O0OO =OOOO000O00000O0OO .checkClose ();#line:57\r\n if OOOOO00O0O0O0O0OO :return OOOOO00O0O0O0O0OO #line:58\r\n OOOOO00O0O0O0O0OO =OOOO000O00000O0OO .checkWebType ();#line:59\r\n if OOOOO00O0O0O0O0OO :return OOOOO00O0O0O0O0OO #line:60\r\n OOOOO00O0O0O0O0OO =OOOO000O00000O0OO .checkDomain ();#line:61\r\n if OOOOO00O0O0O0O0OO :return OOOOO00O0O0O0O0OO #line:62\r\n OOOOO00O0O0O0O0OO =OOOO000O00000O0OO .checkConfig ();#line:63\r\n OOOO000O00000O0OO .GetOS ();#line:65\r\n def checkAddressWhite (O00O0OOOO00O00000 ):#line:69\r\n OOOOO0OOOOOO0OO00 =O00O0OOOO00O00000 .GetToken ();#line:70\r\n if not OOOOO0OOOOOO0OO00 :return redirect ('/login');#line:71\r\n if not request .remote_addr in OOOOO0OOOOOO0OO00 ['address']:return redirect ('/login');#line:72\r\n def checkLimitIp (OOO0O0O0O0OO0OO0O ):#line:76\r\n if os .path .exists ('data/limitip.conf'):#line:77\r\n O0OOO000000000OOO =public .ReadFile ('data/limitip.conf')#line:78\r\n if O0OOO000000000OOO :#line:79\r\n O0OOO000000000OOO =O0OOO000000000OOO .strip ();#line:80\r\n if not public .GetClientIp ()in O0OOO000000000OOO .split (','):return redirect ('/login')#line:81\r\n def setSession (OOO0OOO0000O0O00O ):#line:85\r\n session ['menus']=sorted (json .loads (public .ReadFile ('config/menu.json')),key =lambda OOOO0OO0OO00OOO00 :OOOO0OO0OO00OOO00 ['sort'])#line:86\r\n session ['yaer']=datetime .now ().year #line:87\r\n session ['download_url']='http://download.bt.cn';#line:88\r\n if not 'brand'in session :#line:89\r\n session ['brand']=public .GetConfigValue ('brand');#line:90\r\n session ['product']=public .GetConfigValue ('product');#line:91\r\n session ['rootPath']='/www'#line:92\r\n session ['download_url']='http://download.bt.cn';#line:93\r\n session ['setupPath']=public .GetConfigValue ('setup_path');#line:94\r\n session ['logsPath']=public .GetConfigValue ('setup_path')+'/wwwlogs';#line:95\r\n session ['yaer']=datetime .now ().year #line:96\r\n print (session )#line:97\r\n if not 'menu'in session :#line:98\r\n session ['menu']=public .GetLan ('menu');#line:99\r\n if not 'lan'in session :#line:100\r\n session ['lan']=public .GetLanguage ();#line:101\r\n if not 'home'in session :#line:102\r\n session ['home']='http://www.bt.cn';#line:103\r\n def checkWebType (O00O000O00O00O000 ):#line:107\r\n session ['webserver']='iis';#line:109\r\n if public .get_server_status ('nginx')>=0 :#line:110\r\n session ['webserver']='nginx'#line:111\r\n elif public .get_server_status ('apache')>=0 :#line:112\r\n session ['webserver']='apache';#line:113\r\n if os .path .exists (O00O000O00O00O000 .setupPath +'/'+session ['webserver']+'/version.pl'):#line:115\r\n session ['webversion']=public .ReadFile (O00O000O00O00O000 .setupPath +'/'+session ['webserver']+'/version.pl').strip ()#line:116\r\n OOOO0OO00O0O00000 =O00O000O00O00O000 .setupPath +'/data/phpmyadminDirName.pl'#line:117\r\n if os .path .exists (OOOO0OO00O0O00000 ):#line:118\r\n session ['phpmyadminDir']=public .ReadFile (OOOO0OO00O0O00000 ).strip ()#line:119\r\n def checkClose (OO0O0OO000O0O000O ):#line:122\r\n if os .path .exists ('data/close.pl'):#line:123\r\n return redirect ('/close');#line:124\r\n def checkDomain (O00OOO00000O00OO0 ):#line:127\r\n try :#line:128\r\n O00O00O00O000OOOO =True #line:129\r\n if not 'login'in session :#line:130\r\n O00O00O00O000OOOO =O00OOO00000O00OO0 .get_sk ()#line:131\r\n if O00O00O00O000OOOO :return O00O00O00O000OOOO #line:132\r\n else :#line:133\r\n if session ['login']==False :return redirect ('/login')#line:134\r\n OO0OOOOOO0O00O0OO =public .GetHost ()#line:135\r\n O0O0OOO000000O000 =public .ReadFile ('data/domain.conf')#line:136\r\n if O0O0OOO000000O000 :#line:137\r\n if (OO0OOOOOO0O00O0OO .strip ().lower ()!=O0O0OOO000000O000 .strip ().lower ()):return redirect ('/login')#line:138\r\n OO0O00OO0O00O00O0 ='data/login_token.pl'#line:140\r\n if os .path .exists (OO0O00OO0O00O00O0 ):#line:141\r\n OO000O0O000000OOO =public .readFile (OO0O00OO0O00O00O0 ).strip ()#line:142\r\n if 'login_token'in session :#line:143\r\n if session ['login_token']!=OO000O0O000000OOO :#line:144\r\n return redirect ('/login?dologin=True')#line:145\r\n except :#line:146\r\n return redirect ('/login')#line:147\r\n def get_sk (OOOOO0O000O0OO00O ,):#line:150\r\n OOO00O00O00OOO0OO =OOOOO0O000O0OO00O .setupPath +'/panel/config/api.json'#line:151\r\n if not os .path .exists (OOO00O00O00OOO0OO ):return redirect ('/login')#line:152\r\n O0OOO0O00O0O00O00 =json .loads (public .ReadFile (OOO00O00O00OOO0OO ))#line:153\r\n if not O0OOO0O00O0O00O00 ['open']:return redirect ('/login')#line:154\r\n from BTPanel import get_input #line:155\r\n OOOO0O00O000O0O0O =get_input ()#line:156\r\n if not 'request_token'in OOOO0O00O000O0O0O or not 'request_time'in OOOO0O00O000O0O0O :return redirect ('/login')#line:157\r\n O0OOO0OOOO00OO000 =public .GetClientIp ()#line:158\r\n if not O0OOO0OOOO00OO000 in O0OOO0O00O0O00O00 ['limit_addr']:return public .returnJson (False ,'IP校验失败,您的访问IP为['+O0OOO0OOOO00OO000 +']')#line:159\r\n OO00000O0OO0OOO00 =public .md5 (OOOO0O00O000O0O0O .request_time +O0OOO0O00O0O00O00 ['token'])#line:160\r\n if OOOO0O00O000O0O0O .request_token ==OO00000O0OO0OOO00 :return False #line:161\r\n return public .returnJson (False ,'密钥校验失败')#line:162\r\n def checkConfig (O00O00O000O0O0O00 ):#line:165\r\n if not 'config'in session :#line:166\r\n session ['config']=public .M ('config').where (\"id=?\",('1',)).field ('webserver,sites_path,backup_path,status,mysql_root').find ();#line:167\r\n O0OOOOO0O0OO000O0 ='data/sa.pl'#line:168\r\n if os .path .exists (O0OOOOO0O0OO000O0 ):#line:169\r\n session ['config']['mssql_sa']=public .readFile (O0OOOOO0O0OO000O0 )#line:170\r\n print (session ['config'])#line:171\r\n if not 'email'in session ['config']:#line:172\r\n session ['config']['email']=public .M ('users').where (\"id=?\",('1',)).getField ('email');#line:173\r\n if not 'address'in session :#line:174\r\n session ['address']=public .GetLocalIp ()#line:175\r\n def checkSafe (OO0000O000OO0OOO0 ):#line:177\r\n O0OOOOOO000O000OO =['/','/site','/ftp','/database','/plugin','/soft','/public'];#line:178\r\n if not os .path .exists (os .getenv (\"BT_SETUP\")+'/data/userInfo.json'):#line:179\r\n if 'vip'in session :del (session .vip );#line:180\r\n if not request .path in O0OOOOOO000O000OO :return True #line:181\r\n if 'vip'in session :return True #line:182\r\n import panelAuth #line:184\r\n O000O000OOOOO00O0 =panelAuth .panelAuth ().get_order_status (None );#line:185\r\n try :#line:186\r\n if O000O000OOOOO00O0 ['status']==True :#line:187\r\n session .vip =O000O000OOOOO00O0 #line:188\r\n return True #line:189\r\n return redirect ('/vpro');#line:190\r\n except :pass #line:191\r\n return False #line:192\r\n def GetOS (OO0OO0OO000OO0OO0 ):#line:195\r\n if not 'server_os'in session :#line:196\r\n OOO0OOOOOOO0OO000 ={}#line:197\r\n OOO0OOOOOOO0OO000 ['x']='Windows';#line:198\r\n OOO0OOOOOOO0OO000 ['osname']=''#line:199\r\n session ['server_os']=OOO0OOOOOOO0OO000 ","sub_path":"mtVIvqMhycn4w0r5/1bb755838066ca634a8c0d4c2494d8b3ddc3a4e5.py","file_name":"1bb755838066ca634a8c0d4c2494d8b3ddc3a4e5.py","file_ext":"py","file_size_in_byte":10668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"597157772","text":"# coding: utf-8\ndesc={\"ref\": {\"NGPH\": \"https://vitroid.github.io/@NGPH\"},\n \"brief\": \"Undirected graph of HBs.\",\n \"usage\": \"No options available.\"\n }\n\n\n\nimport numpy as np\n\n\ndef hook2(lattice):\n lattice.logger.info(\"Hook2: Output the undirected network.\")\n\n s = \"\"\n s += \"@NGPH\\n\"\n s += \"{0}\\n\".format(len(lattice.reppositions))\n for i,j,k in lattice.graph.edges(data=True):\n s += \"{0} {1}\\n\".format(i,j)\n s += \"-1 -1\\n\"\n s = \"\\n\".join(lattice.doc) + \"\\n\" + s\n print(s,end=\"\")\n lattice.logger.info(\"Hook2: end.\")\n\nhooks = {2:hook2}\n","sub_path":"genice/formats/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"24673935","text":"import transaction\nfrom Products.CMFCore.utils import getToolByName\n\nPRODUCT_DEPENDENCIES = ('collective.keywordwidgetreplacer',\n 'PloneKeywordManager',\n 'Faq',\n 'PlonePopoll',\n 'UploadReferenceWidget',\n 'weka.content',\n 'weka.portlet.adtech',\n 'weka.portlet.netnews',\n 'weka.portlet.adsense',\n 'weka.mptheme')\n \nEXTENSION_PROFILES = ('weka.mppolicy:default',)\n\ndef install(self, reinstall=False):\n \"\"\"custom install method for the extension profile\"\"\"\n portal_quickinstaller = getToolByName(self, 'portal_quickinstaller')\n portal_setup =getToolByName(self, 'portal_setup')\n \n for product in PRODUCT_DEPENDENCIES:\n if reinstall and portal_quickinstaller.isProductInstalled(product):\n portal_quickinstaller.reinstallProducts([product])\n transaction.savepoint()\n elif not portal_quickinstaller.isProductInstalled(product):\n portal_quickinstaller.installProduct(product)\n transaction.savepoint()\n \n for extension_id in EXTENSION_PROFILES:\n portal_setup.runAllImportStepsFromProfile('profile-%s' % extension_id, purge_old=False)\n product_name = extension_id.split(':')[0]\n portal_quickinstaller.notifyInstalled(product_name)\n transaction.savepoint()\n\n","sub_path":"src/weka.mppolicy/weka/mppolicy/Extensions/Install.py","file_name":"Install.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"611034162","text":"#face detection\nimport cv2\n\nface_cascade = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\n\ngray_img = cv2.imread(\"face.jpg\")\n\nfaces = face_cascade.detectMultiScale(gray_img, scaleFactor = 1.05, minNeighbors = 5)\n\nprint(type(faces))\nprint(faces)\n\nfor x,y,w,h in faces:\n img = cv2.rectangle(img, (x,y), (x+w, y+h), (0,255,0), 3)\n","sub_path":"opencv/face.py","file_name":"face.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"266365217","text":"\"\"\"\nThe example shows the usage of the KentMixtureModel.\n\nIt shows the performance of the Kent mixture model in comparison\nto a Gaussian mixture model on synthetic data.\n\"\"\"\n\nimport numpy as np\n\nimport matplotlib.pylab as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfrom matplotlib.patches import FancyArrowPatch\nfrom mpl_toolkits.mplot3d import proj3d\n\nfrom sklearn.mixture import GMM, KentMixtureModel\nfrom sklearn.mixture.kmm import to_spherical_coords, to_cartesian_coords\n\nclass Arrow3D(FancyArrowPatch):\n def __init__(self, xs, ys, zs, *args, **kwargs):\n FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)\n self._verts3d = xs, ys, zs\n\n def draw(self, renderer):\n xs3d, ys3d, zs3d = self._verts3d\n xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)\n self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))\n FancyArrowPatch.draw(self, renderer)\n\n\nif __name__ == \"__main__\":\n np.random.seed(123456)\n\n colors=['r','b', 'y', 'k', 'c', 'g', 'white', 'm', 'turquoise', 'darkgreen', ]\n\n # ------------------------------------\n # ground truth centers\n \n centers = np.array([[1.0,0,0], [0.,1.,0.], [-1,0,0.]])\n n_components = centers.shape[0]\n \n # no samples per center\n samples = 60\n # standard deviation in angle per center\n stds = np.array([[0.3, 0.75], [0.1,0.5], [0.7,0.3]])\n \n responsibilities_true = np.zeros( (samples*centers.shape[0], centers.shape[0]) )\n clustering_true = np.zeros( (samples*centers.shape[0], ) )\n \n # generate data\n X = np.zeros( (samples*centers.shape[0], centers.shape[1]) )\n row = 0\n for i in range(centers.shape[0]):\n # normalize center\n centers[i,:] /= np.linalg.norm(centers[i,:])\n # convert to spherical coordinates\n gamma_raw = to_spherical_coords(centers[i, :])\n \n for _ in range(samples):\n gamma = gamma_raw + np.random.randn(2)*stds[i]\n X[row,:] = to_cartesian_coords(gamma)\n responsibilities_true[row, :] = [ 1. if i==j else 0. for j in range(centers.shape[0]) ]\n clustering_true[row] = i\n row += 1\n\n iterations = 500\n initializations = 10\n\n # ------------------------------------\n # fit Kent mixture model\n klf = KentMixtureModel(n_components=n_components, n_iter=iterations, n_init=initializations)\n klf.fit(X)\n kmm_lpr, kmm_responsibilities = klf.score_samples(X)\n\n # ------------------------------------\n # fit GMM\n glf = GMM(n_components=n_components, n_iter=iterations, n_init=initializations, covariance_type='full')\n glf.fit(X)\n gmm_lpr, gmm_responsibilities = glf.score_samples(X)\n\n # ------------------------------------\n # Print some info\n np.set_printoptions(precision=3)\n np.set_printoptions(suppress=True)\n\n print (\"CENTERS\")\n print ([centers[i,:] / np.linalg.norm(centers[i,:]) for i in range(centers.shape[0])])\n\n print ( \"KMM: responsibilities\" )\n print ( kmm_responsibilities.T )\n print ( \"kappa: %s,\\nbeta: %s,\\nG:\\n %s\\nS:\\n%s\" % tuple(map(str,(klf.kappa_, klf.beta_, klf.G_, klf.S_))) )\n print ( \"weights: %s\" % str(klf.weights_) )\n\n print ( \"GMM: responsibilities\" )\n print ( gmm_responsibilities.T )\n print ( \"Mean: %s,\\nCov:\\n%s\" % tuple(map(str, (glf.means_, glf.covars_))) )\n\n # ------------------------------------\n # visualize\n for name, clf, lpr, responsibilities, means in [ \n (\"Truth\", None, np.ones(X.shape[0]), responsibilities_true, centers),\n (\"Kent\", klf, kmm_lpr, kmm_responsibilities, klf.G_[:, :, 0]),\n (\"Gaussian\", glf, gmm_lpr, gmm_responsibilities, glf.means_) ]:\n\n print ( \"===============================\" )\n print ( name )\n\n fig = plt.figure(figsize=(10,10))\n ax = fig.add_subplot(1,1,1, projection='3d')\n plt.title(name)\n\n print ( \"Log-likelihood\" )\n print ( np.sum(lpr) )\n\n X_lik = np.exp(lpr)\n X_lik /= np.max(X_lik)\n print ( \"Likelihoods (normalized): \" )\n print ( X_lik )\n\n cluster_mapping = {}\n for k in range(n_components):\n G = means[k]\n\n print ( \"Mean vectors\" )\n print ( G )\n \n # find matching real cluster\n k_true = np.argmin(1 - np.dot(centers, G))\n cluster_mapping[k] = k_true\n \n # cluster mean\n ax.scatter(G[0], G[1], G[2], c=\"k\", s = 100.0, alpha=1.0)\n a = Arrow3D([0, G[0]], [0, G[1]], [0, G[2]], mutation_scale=20, lw=1, arrowstyle=\"-|>\", color=\"k\")\n ax.text(G[0], G[1], G[2]+0.1, \"C%d\" % k, color=\"black\")\n ax.add_artist(a)\n\n # true mean\n ax.scatter(centers[k,0], centers[k,1], centers[k,2], c=\"w\", s = 100.0, alpha=1.0)\n a = Arrow3D([0, centers[k,0]], [0, centers[k,1]], [0, centers[k,2]], mutation_scale=20, lw=0.5, arrowstyle=\"-|>\", color=\"k\")\n ax.add_artist(a)\n\n misclassified = 0\n for i in range(X.shape[0]):\n j = np.argmax(responsibilities[i,:])\n lik = np.max([0.4, np.min([1.0, X_lik[i]])])\n \n if cluster_mapping[j] != clustering_true[i]:\n misclassified += 1\n \n ax.scatter(X[i:i+1,0], X[i:i+1,1], X[i:i+1,2], c=colors[cluster_mapping[j] ], s = 50.0, alpha=lik)\n a = Arrow3D([0, X[i:i+1,0]], [0, X[i:i+1,1]], [0, X[i:i+1,2]], mutation_scale=20, lw=1, arrowstyle=\"-|>\", color=\"gray\")\n ax.add_artist(a)\n ax.text(X[i:i+1,0], X[i:i+1,1], X[i:i+1,2]+0.1, \"%d\" % i, color=\"gray\")\n print ( \"Misclassified: %d \" % misclassified )\n\n ax.set_xlim3d(-1,1)\n ax.set_ylim3d(-1,1)\n ax.set_zlim3d(-1,1)\n\n ax.set_xlabel(\"x\")\n ax.set_ylabel(\"y\")\n ax.set_zlabel(\"z\")\n\n plt.show()\n","sub_path":"examples/mixture/plot_kmm.py","file_name":"plot_kmm.py","file_ext":"py","file_size_in_byte":5681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"566020528","text":"#-*-coding:utf-8 -*-\nimport time\nfrom selenium import webdriver\ndriver = webdriver.Chrome()\ndriver.maximize_window()\n'''获取对话框输入2,并且点击【确认】,文本框内提示<左哥是真笨啊>,点击【取消】文本框内提示<您没有按要求输入,请重新输入>'''\ndriver.get('file:///C:/Users/Administrator/Desktop/alert.html')\n'''获取prompt对话框的按钮,点击按钮,弹出confirm对话框'''\ndriver.find_element_by_xpath('/html/body/div/input[1]').click()\n'''获取prompt对话框'''\ndialog_box = driver.switch_to_alert()\n'''添加等待时间'''\ntime.sleep(2)\n'''获取对话框的内容'''\nprint (dialog_box.text) #打印警告对话框内容\ndialog_box.send_keys(\"2\") #弹出框内输入2\ndialog_box.accept() #接受\nprint (driver.find_element_by_xpath('//*[@id=\"textSpan\"]/font').text) #获取关闭弹窗结果 #获取确认弹窗结果\n'''这里等待几秒在测试取消'''\ntime.sleep(2)\n#************************点击【取消】,并且获取显示结果**********************\ndriver.find_element_by_xpath('/html/body/div/input[1]').click()\n'''获取prompt对话框'''\ndialog_box = driver.switch_to_alert()\n'''添加等待时间'''\ntime.sleep(2)\ndialog_box.dismiss() #关闭对话框\nprint (driver.find_element_by_xpath('//*[@id=\"textSpan\"]/font').text) #获取关闭弹窗结果\ntime.sleep(2)\n#driver.quit()","sub_path":"prompt_1.py","file_name":"prompt_1.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"461293735","text":"import bs4 as bs4\nimport requests, random\n\n\nclass VkBot:\n def __init__(self, user_id):\n print(\"\\nСоздан объект бота!\")\n self._USER_ID = user_id\n self._USERNAME = self._get_user_name_from_vk_id(user_id)\n self._COMMANDS = [\"ПРИВЕТ\", \"!ПОГОДА\", \"!ВРЕМЯ\", \"ПОКА\", \"!КОМАНДЫ\", \"!ЧИСЛО\", '!МОНЕТКА', 'ИГРА КИЛЛЕР',\n '!ЦИТАТА', \"ИГРА ПРИКЛЮЧЕНИЕ\", \"АУФ\", '!ШАР', '!ВЫБЕРИ', \"ПОМОЩЬ\"]\n\n def _get_user_name_from_vk_id(self, user_id):\n request = requests.get(\"https://vk.com/id\" + str(user_id))\n bs = bs4.BeautifulSoup(request.text, \"html.parser\")\n user_name = self._clean_all_tag_from_str(bs.findAll(\"title\")[0])\n return user_name.split()[0]\n\n def new_message(self, message):\n # Привет\n if message.upper() == self._COMMANDS[0]:\n return f\"Привет-привет, {self._USERNAME}! \" + str(\n random.choice(['😉', '😌', '✋ 😇']))\n # Погода\n elif message.upper().split(' ')[0] == self._COMMANDS[1]:\n pass\n #return self._get_weather()\n # Время\n elif message.upper() == self._COMMANDS[2]:\n return self._get_time()\n # Пока\n elif message.upper() == self._COMMANDS[3]:\n return f\"Пока-пока, {self._USERNAME}!\"\n elif message.upper() == self._COMMANDS[4] or message.upper() == self._COMMANDS[13]:\n return f\"Список команд:\\n\" \\\n f\"\\n\" \\\n f\"Развлечения 🎮:\\n\" \\\n f\"Игра киллер - регистрация на игру. 🔫\\n\" \\\n f\"Игра приключение - начать приключение в фентезийном мире. 🗡🛡\\n\" \\\n f\"Анонимный чат - анонимный чат с другими пользователями ✉\\n\" \\\n f\"!Монетка - подбросить монетку (орел/решка). 🎲\\n\" \\\n f\"!Цитата - мудрая цитата. ☝\\n\" \\\n f\"!Шар [текст] - шар предсказаний. 🔮\\n\" \\\n f\"!Выбери [фраза 1] или [фраза 2] - шар предсказаний. ⚖\\n\" \\\n f\"написать шутку: [ваша шутка] - записать шутку в список шуток\\n\" \\\n f\"шутка - рандомная шутка других пользователей\\n\" \\\n f\"\\n\" \\\n f\"Полезное 🎓:\\n\" \\\n f\"!Погода - для просмотра погоды в Москве. ☀\\n\" \\\n f\"!Время - для просмотра вр��мени в Москве. 🌓\\n\" \\\n f\"!Число [от] [до] - генерация рандомного числа. 🔢\\n\" \\\n f\"переводчик - переводчик 🔤\\n\" \\\n f\"почтовый индекс [адрес] - почтовый индекс по заданному адресу 📪\"\n elif message.upper()[0:6] == self._COMMANDS[5]:\n if len(message.split(' ')) != 3:\n return f\"Неверный синтаксис, надо вводить так:\\n\" \\\n f\"!Число [от] [до]\"\n else:\n if int(message.split(' ')[1]) > int(message.split(' ')[2]):\n return f\"Первое число больше второго 😒\"\n else:\n return f\"Ваше число: \" + str(random.randint(int(message.split(' ')[1]), int(message.split(' ')[2])))\n elif message.upper() == self._COMMANDS[6]:\n return f\"Иии выпадает! \" + random.choice(['Орёл', 'Решка']) + ' ' + str(\n random.choice(['🌝', '😄', '😏', '😅']))\n elif message.upper() == self._COMMANDS[7]:\n return \"Отлично, для регитрации на игру отправьте свою фотографию 👤, чтобы другие игроки смогли вас\" \\\n \" найти ⌚\"\n elif message.upper() == self._COMMANDS[8]:\n with open('citata.txt', 'r') as file:\n line = file.readlines()\n return line[random.randint(0, 12)].encode(\"utf-8\")\n elif message.upper() == self._COMMANDS[9]:\n return \"Вы начали игру {название еще не придкмал}.\\n для выхода из игры напишите: выход игра приключение.\" \\\n \"\\n для сохранения игры напишите: сохранить игра приключение.\\n для загрузки сохранения напишите:\" \\\n \" загрузить игра приключение.\\n чтобы начать напишите: начать приключение.\"\n elif message.upper() == self._COMMANDS[10]:\n return \"Выкатывает со дворов!\"\n elif message.upper().split(' ')[0] == self._COMMANDS[11]:\n if len(message.split(' ')) < 2:\n return \"Неправильный синтаксис:\\n\" \\\n \"!Шар [текст] - верный синтаксис.\"\n else:\n return random.choice(\n ['Хорошие перспективы.', 'Даже не думай.', 'Скорее да, чем нет.', 'Скорее нет, чем да.',\n 'Никаких сомнений.', 'Спроси позже.', 'Бесспорно.', 'Определённо да.',\n 'Сконцентрируйся и спроси опять.', 'Лучше не рассказывать.'])\n elif message.upper().split(' ')[0] == self._COMMANDS[12]:\n if 'или' not in message:\n return \"Неправильный синтаксис:\\n\" \\\n \"!Выбери [фраза 1] или [фраза 2] - верный синтаксис.\"\n elif message[-3:] == 'или':\n return \"Неправильный синтаксис:\\n\" \\\n \"!Выбери [фраза 1] или [фраза 2] - верный синтаксис.\"\n else:\n message = message[8:]\n message = message.split(' или ')\n if len(message) > 2:\n return 'Слишком много \"или\".'\n else:\n return 'Мой выбор: ' + str(random.choice(message))\n else:\n return \"Не понимаю о чем вы... 😒\\n Для списка команд напишите:\\n\" \\\n \"!команды\"\n\n def _get_time(self):\n request = requests.get(\"https://my-calend.ru/date-and-time-today\")\n b = bs4.BeautifulSoup(request.text, \"html.parser\")\n return self._clean_all_tag_from_str(str(b.select(\".page\")[0].findAll(\"h2\")[1])).split()[1]\n\n @staticmethod\n def _clean_all_tag_from_str(string_line):\n \"\"\"\n Очистка строки stringLine от тэгов и их содержимых\n :param string_line: Очищаемая строка\n :return: очищенная строка\n \"\"\"\n result = \"\"\n not_skip = True\n for i in list(string_line):\n if not_skip:\n if i == \"<\":\n not_skip = False\n else:\n result += i\n else:\n if i == \">\":\n not_skip = True\n return result\n\n ''''@staticmethod\n def _get_weather(city=str(\"Москва\")) -> list:\n owm = pyowm.OWM('6d00d1d4e704068d70191bad2673e0cc', language='ru')\n place = city\n observation = owm.weather_at_place(place)\n w = observation.get_weather()\n return 'В городе ' + city + ' сейчас ' + w.get_detailed_status() + ' и ' + str(\n w.get_temperature('celsius')['temp']) + ' градусов по Цельсию.'''\n","sub_path":"bot VK version 5/vk_bot.py","file_name":"vk_bot.py","file_ext":"py","file_size_in_byte":8510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"555694698","text":"width, height = int(input()), int(input())\n\ngrid = [input() for _ in range(height)]\n\nfor y1 in range(height):\n for x1 in range(width):\n if grid[y1][x1].isdigit():\n x2, y2 = -1, -1\n x3, y3 = -1, -1\n\n for i in range(x1 + 1, width):\n if grid[y1][i].isdigit():\n x2, y2 = i, y1\n break\n\n for i in range(y1 + 1, height):\n if grid[i][x1].isdigit():\n x3, y3 = x1, i\n break\n\n print(x1, y1, x2, y2, x3, y3)\n","sub_path":"Medium/There_is_no_Spoon_Episode_1.py","file_name":"There_is_no_Spoon_Episode_1.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"304954491","text":"\"\"\"\n This file contains the class need for the entire simulation\n\"\"\"\n\nfrom Player import Player\nfrom PlayerActions import PlayerActionSignContract\nfrom Environment import Economy\n\n\nclass Scenario:\n # A scenario contains a player and its action and an economical environment\n year = 0\n eco = Economy()\n player = Player(1000, 600)\n\n def __init__(self, y=1, e=Economy(), p=Player()):\n self.year = y\n self.eco = e\n self.player = p\n self.player_action = PlayerActionSignContract()\n\n def update(self):\n self.eco.update() # Update economical status with growth rate and variance\n self.player.update(self.eco) # Player's financial status update via environment\n self.player_action.impact(self.player) # Player's financial status is affected by the action they take\n if self.player_action.action_period_cd > 0:\n # Update the counter\n self.player_action.action_period_cd -= 1\n else:\n self.player_action = PlayerActionSignContract() # If the action period is finished, ask for new action\n self.player_action.impact(self.player)\n self.player_action.action_period_cd -= 1\n self.year += 1\n","sub_path":"WarGamePython/src/Simulator.py","file_name":"Simulator.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"131219157","text":"import glob\nimport json\nimport pickle\nimport os\nimport re\nfrom functools import reduce\nfrom operator import mul\n\n\nfrom astropy import units as u, constants as const\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport scipy as sp\nfrom scipy.stats import gaussian_kde\nfrom scipy.integrate import quad\n\nimport bilby\n\nplt.style.use('publication.mplstyle')\n\n# luminosity distance integral\nomega_m = 0.3\nomega_lambda = 0.7\nintegrand = lambda z: 1./np.sqrt(omega_m * (1 + z)**3 + omega_lambda)\n\ndef add_hubble(result):\n hubble_vals = np.array(\n [quad(integrand, 0, z_vals)[0] for z_vals in result.posterior.z.values]\n )\n hubble_vals /= result.posterior.luminosity_distance.values\n hubble_vals *= (1 + result.posterior.z.values)\n hubble_vals *= (const.c.to('km/s')/u.Mpc).value\n result.posterior['h0'] = hubble_vals\n\n\ndef add_reweighted_hubble(row, num_prior_points=10000,\n bin_start=-10, bin_step=20,\n num_bins=15, plot=False):\n result = row.bilby_result\n hubble_posterior = result.posterior.h0.values\n try:\n hubble_prior = result.priors['h0'].sample(num_prior_points)\n except KeyError:\n z_prior = result.priors['z'].sample(num_prior_points)\n distance_prior = result.priors['luminosity_distance'].sample(num_prior_points)\n hubble_prior = np.array([quad(integrand, 0, z_vals)[0] for z_vals in z_prior])\n hubble_prior /= distance_prior\n hubble_prior *= (1 + z_prior)\n hubble_prior *= (const.c.to('km/s')/u.Mpc).value\n\n # cut the prior at max value of the bin\n bins = [bin_start + n*bin_step for n in range(num_bins)]\n accept_mask = hubble_prior < (max(bins) - bin_step)\n\n #distance_prior = distance_prior[accept_mask]\n hubble_prior = hubble_prior[accept_mask]\n # cut posterior values at 99 percentile\n hubble_posterior = hubble_posterior[\n hubble_posterior < np.percentile(\n hubble_posterior, 99\n )\n ]\n\n counts, bb = np.histogram(hubble_prior, bins=bins, density=True)\n bin_centers = 0.5*(bb[1:] + bb[:-1])\n\n weights_interpolant = sp.interpolate.interp1d(\n bin_centers, counts, kind='cubic',\n fill_value=(0., 0.), bounds_error=False\n )\n\n wts = 1./weights_interpolant(hubble_prior)\n wts /= np.sum(wts)\n\n #print(hubble_prior[np.where(np.isnan(wts))])\n #print(hubble_prior[np.where(np.isinf(wts))])\n\n posterior_wts = 1./weights_interpolant(hubble_posterior)\n posterior_wts /= np.sum(posterior_wts)\n\n #print(\"Bad posterior values\")\n #print(hubble_posterior[np.where(np.isnan(posterior_wts))])\n #print(hubble_posterior[np.where(np.isinf(posterior_wts))])\n\n if plot:\n _, _b, _p = plt.hist(hubble_posterior, weights=posterior_wts,\n bins=20, density=True, alpha=0.5, label='reweighted')\n _, _b, _p = plt.hist(hubble_posterior,\n bins=_b, density=True, alpha=0.5, label='original')\n reweighted_kde = sp.stats.gaussian_kde(\n hubble_posterior, weights=posterior_wts\n )\n\n fiducial_hubble_vals = np.linspace(0, 200, 100)\n reweighted_kde_hubble_vals = reweighted_kde(fiducial_hubble_vals)\n plt.plot(fiducial_hubble_vals, reweighted_kde_hubble_vals, label='KDE')\n plt.title(f\"Inclination: {row.inclination:.1f}, Distance: {row.distance}\")\n plt.legend()\n plt.show()\n return hubble_posterior, posterior_wts\n\n\nfilenames = glob.glob(\n '/home/deep/work/campus-cluster-runs/pbilby-runs/redshift-injections/O5/'\n 'outdir_gw_tidal_cosmo_dl_[1234567]00_CE_incl_[13467][0|5]/result/*.json'\n)\nfilenames = sorted(filenames)\n\npattern = re.compile('.*_dl_([0-9]+)_.*_incl_([0-9]+).*')\n\nresults_master = pd.DataFrame(\n data=[(*re.match(pattern, os.path.basename(f)).groups(), bilby.result.read_in_result(filename=f))\n for f in filenames],\n columns=('distance', 'inclination', 'bilby_result')\n)\nresults_master.distance = results_master.distance.astype(float)\nresults_master.inclination = results_master.inclination.astype(float)\n\nfor idx, r in results_master.iterrows():\n if hasattr(r.bilby_result.posterior, 'z'):\n add_hubble(r.bilby_result)\n\n# attach posterior for hubble\nresults_master['hubble_kde'] = [\n gaussian_kde(r.bilby_result.posterior.h0.values)\n for idx, r in results_master.iterrows()\n]\n# attach re-weighted hubble\nposteriors = []\nweights = []\nfor idx, row in results_master.iterrows():\n posterior, weight = add_reweighted_hubble(\n row, bin_start=-10, bin_step=20,\n num_bins=16, plot=False\n )\n posteriors.append(posterior)\n weights.append(weight)\nresults_master['hubble_reweighting'] = posteriors\nresults_master['weights'] = weights\nresults_master['reweighted_hubble_kde'] = [\n gaussian_kde(\n r.hubble_reweighting,\n weights=r.weights\n )\n for idx, r in results_master.iterrows()\n]\n# load population weights\nwith open('/home/deep/github/gw-tidal-cosmology-docs/data/O5/dl-iota-kde.pickle-O5', 'rb') as f:\n kde = pickle.load(f)\n\ndist_vals = np.linspace(50, 800, 100)\nincl_vals = np.linspace(0, np.pi, 20)\n\nX, Y = np.meshgrid(dist_vals, incl_vals)\npositions = np.vstack([X.ravel(), Y.ravel()])\nZ = np.reshape(kde(positions).T, X.shape)\n\nplt.figure()\nplt.contourf(X, Y, Z, cmap='bone')\nplt.colorbar()\nplt.xlabel(r'Distance (Mpc)')\nplt.ylabel(r'Inclination (Rad.)')\nplt.ylim((0, 1.57))\nplt.scatter(\n results_master.distance, results_master.inclination/180*np.pi,\n s=50,\n c='r',\n\n)\nplt.savefig('../figures/p-det-heatmap-O5.pdf')\nplt.close()\n\npop_wts = [kde([r.distance, r.inclination/180*np.pi])[0] for idx, r in results_master.iterrows()]\n\nresults_master['pop_wt'] = np.array(pop_wts)\n\nprior_wts_incl = np.array(\n [np.sin(r.inclination/180*np.pi) for idx, r in results_master.iterrows()]\n)\nprior_wts_incl /= prior_wts_incl.sum()\n\nresults_master['prior_wt_incl'] = prior_wts_incl\n\nprior_wts_dist = np.array([r.distance**2 for idx, r in results_master.iterrows()])\nprior_wts_dist /= prior_wts_dist.sum()\n\nresults_master['prior_wt_dist'] = prior_wts_dist\n\n# net-prior weighting\nprior_wt = prior_wts_dist*prior_wts_incl\nprior_wt /= prior_wt.sum()\nresults_master['prior_wt'] = prior_wt\n\nrelative_pop_wts = 10*(results_master.pop_wt/np.sum(results_master.pop_wt))\n\n# Stacked H0\nstacked_h0 = lambda x: reduce(\n mul, [\n (prior_wt * k(x))**pop_wt\n for k, prior_wt, pop_wt in zip(results_master.reweighted_hubble_kde.values,\n results_master.prior_wt.values,\n relative_pop_wts)\n ]\n)\n\nnorm = quad(stacked_h0, 20, 150)[0]\nnorm_stacked_h0 = lambda x: stacked_h0(x)/norm\n\nh0_vals = np.linspace(10, 150, num=1000)\np_h0_vals = norm_stacked_h0(h0_vals)\nh0_cdf = sp.integrate.cumtrapz(p_h0_vals, h0_vals)\nh0_vals = 0.5*(h0_vals[1:] + h0_vals[:-1])\nplt.plot(h0_vals, h0_cdf)\nplt.show()\nfive, ninety_five = h0_vals[np.argmax(h0_cdf > 0.05)], h0_vals[np.argmax(h0_cdf > 0.95)]\nprint(\"5 percent/ 95 percent/ confidence interval = {:.2f}/{:.2f}/{:.2f}\".format(\n five, ninety_five, ninety_five - five\n))\n\nplt.figure()\nh0_vals = np.linspace(20, 150, 150)\n\nfor idx, r in results_master.iterrows():\n plt.plot(h0_vals, r.reweighted_hubble_kde(h0_vals),\n label=f'DL = {r.distance:.1e}; iota = {r.inclination:.1e}',\n color='black',\n linestyle='dotted')\n\n\nplt.plot(h0_vals, norm_stacked_h0(h0_vals), linewidth=3)\nplt.xlim((20, 150))\nplt.axvline(x=70, c='r')\nplt.xlabel('$H_0$ (km s$^{-1}/$Mpc)')\nplt.ylabel('$p(H_0)$')\n#plt.show()\nplt.savefig('../figures/stacked-h0-O5.pdf')\n","sub_path":"scripts/stacked-h0-O5.py","file_name":"stacked-h0-O5.py","file_ext":"py","file_size_in_byte":7657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"348595262","text":"\nfrom __future__ import absolute_import, division, print_function, \\\n unicode_literals\n\nfrom ..shared import AnalysisTask\n\nfrom ..shared.plot.plotting import timeseries_analysis_plot\n\nfrom ..shared.generalized_reader import open_multifile_dataset\nfrom ..shared.io import open_mpas_dataset\n\nfrom ..shared.timekeeping.utility import date_to_days, days_to_datetime\n\nfrom ..shared.io.utility import build_config_full_path, make_directories, \\\n check_path_exists\nfrom ..shared.html import write_image_xml\n\n\nclass TimeSeriesSST(AnalysisTask):\n \"\"\"\n Performs analysis of the time-series output of sea-surface temperature\n (SST).\n\n Attributes\n ----------\n\n mpasTimeSeriesTask : ``MpasTimeSeriesTask``\n The task that extracts the time series from MPAS monthly output\n\n refConfig : ``MpasAnalysisConfigParser``\n Configuration options for a reference run (if any)\n\n Authors\n -------\n Xylar Asay-Davis, Milena Veneziani\n \"\"\"\n\n def __init__(self, config, mpasTimeSeriesTask, refConfig=None):\n # {{{\n \"\"\"\n Construct the analysis task.\n\n Parameters\n ----------\n config : ``MpasAnalysisConfigParser``\n Configuration options\n\n mpasTimeSeriesTask : ``MpasTimeSeriesTask``\n The task that extracts the time series from MPAS monthly output\n\n refConfig : ``MpasAnalysisConfigParser``, optional\n Configuration options for a reference run (if any)\n\n Authors\n -------\n Xylar Asay-Davis\n \"\"\"\n # first, call the constructor from the base class (AnalysisTask)\n super(TimeSeriesSST, self).__init__(\n config=config,\n taskName='timeSeriesSST',\n componentName='ocean',\n tags=['timeSeries', 'sst'])\n\n self.mpasTimeSeriesTask = mpasTimeSeriesTask\n self.refConfig = refConfig\n\n self.run_after(mpasTimeSeriesTask)\n\n # }}}\n\n def setup_and_check(self): # {{{\n \"\"\"\n Perform steps to set up the analysis and check for errors in the setup.\n\n Raises\n ------\n OSError\n If files are not present\n\n Authors\n -------\n Xylar Asay-Davis\n \"\"\"\n # first, call setup_and_check from the base class (AnalysisTask),\n # which will perform some common setup, including storing:\n # self.inDirectory, self.plotsDirectory, self.namelist, self.streams\n # self.calendar\n super(TimeSeriesSST, self).setup_and_check()\n\n config = self.config\n\n self.startDate = self.config.get('timeSeries', 'startDate')\n self.endDate = self.config.get('timeSeries', 'endDate')\n\n self.variableList = \\\n ['timeMonthly_avg_avgValueWithinOceanRegion_avgSurfaceTemperature']\n self.mpasTimeSeriesTask.add_variables(variableList=self.variableList)\n\n if config.get('runs', 'preprocessedReferenceRunName') != 'None':\n check_path_exists(config.get('oceanPreprocessedReference',\n 'baseDirectory'))\n\n self.inputFile = self.mpasTimeSeriesTask.outputFile\n\n mainRunName = config.get('runs', 'mainRunName')\n regions = config.getExpression('timeSeriesSST', 'regions')\n\n self.xmlFileNames = []\n self.filePrefixes = {}\n\n for region in regions:\n filePrefix = 'sst_{}_{}'.format(region, mainRunName)\n self.xmlFileNames.append('{}/{}.xml'.format(self.plotsDirectory,\n filePrefix))\n self.filePrefixes[region] = filePrefix\n\n return # }}}\n\n def run_task(self): # {{{\n \"\"\"\n Performs analysis of the time-series output of sea-surface temperature\n (SST).\n\n Authors\n -------\n Xylar Asay-Davis, Milena Veneziani\n \"\"\"\n\n self.logger.info(\"\\nPlotting SST time series...\")\n\n self.logger.info(' Load SST data...')\n\n config = self.config\n calendar = self.calendar\n\n mainRunName = config.get('runs', 'mainRunName')\n preprocessedReferenceRunName = \\\n config.get('runs', 'preprocessedReferenceRunName')\n preprocessedInputDirectory = config.get('oceanPreprocessedReference',\n 'baseDirectory')\n\n movingAveragePoints = config.getint('timeSeriesSST',\n 'movingAveragePoints')\n\n regions = config.getExpression('regions', 'regions')\n plotTitles = config.getExpression('regions', 'plotTitles')\n regionsToPlot = config.getExpression('timeSeriesSST', 'regions')\n\n regionIndicesToPlot = [regions.index(region) for region in\n regionsToPlot]\n\n outputDirectory = build_config_full_path(config, 'output',\n 'timeseriesSubdirectory')\n\n make_directories(outputDirectory)\n\n dsSST = open_mpas_dataset(fileName=self.inputFile,\n calendar=calendar,\n variableList=self.variableList,\n startDate=self.startDate,\n endDate=self.endDate)\n\n yearStart = days_to_datetime(dsSST.Time.min(), calendar=calendar).year\n yearEnd = days_to_datetime(dsSST.Time.max(), calendar=calendar).year\n timeStart = date_to_days(year=yearStart, month=1, day=1,\n calendar=calendar)\n timeEnd = date_to_days(year=yearEnd, month=12, day=31,\n calendar=calendar)\n\n if self.refConfig is not None:\n baseDirectory = build_config_full_path(\n self.refConfig, 'output', 'timeSeriesSubdirectory')\n\n refFileName = '{}/{}.nc'.format(\n baseDirectory, self.mpasTimeSeriesTask.fullTaskName)\n\n refStartYear = self.refConfig.getint('timeSeries', 'startYear')\n refEndYear = self.refConfig.getint('timeSeries', 'endYear')\n refStartDate = '{:04d}-01-01_00:00:00'.format(refStartYear)\n refEndDate = '{:04d}-12-31_23:59:59'.format(refEndYear)\n\n dsRefSST = open_mpas_dataset(\n fileName=refFileName,\n calendar=calendar,\n variableList=self.variableList,\n startDate=refStartDate,\n endDate=refEndDate)\n else:\n dsRefSST = None\n\n if preprocessedReferenceRunName != 'None':\n self.logger.info(' Load in SST for a preprocesses reference '\n 'run...')\n inFilesPreprocessed = '{}/SST.{}.year*.nc'.format(\n preprocessedInputDirectory, preprocessedReferenceRunName)\n dsPreprocessed = open_multifile_dataset(\n fileNames=inFilesPreprocessed,\n calendar=calendar,\n config=config,\n timeVariableName='xtime')\n yearEndPreprocessed = days_to_datetime(dsPreprocessed.Time.max(),\n calendar=calendar).year\n if yearStart <= yearEndPreprocessed:\n dsPreprocessedTimeSlice = \\\n dsPreprocessed.sel(Time=slice(timeStart, timeEnd))\n else:\n self.logger.warning('Preprocessed time series ends before the '\n 'timeSeries startYear and will not be '\n 'plotted.')\n preprocessedReferenceRunName = 'None'\n\n self.logger.info(' Make plots...')\n for regionIndex in regionIndicesToPlot:\n region = regions[regionIndex]\n\n title = '{} SST'.format(plotTitles[regionIndex])\n xLabel = 'Time [years]'\n yLabel = '[$^\\circ$C]'\n\n varName = self.variableList[0]\n SST = dsSST[varName].isel(nOceanRegions=regionIndex)\n\n filePrefix = self.filePrefixes[region]\n\n figureName = '{}/{}.png'.format(self.plotsDirectory, filePrefix)\n\n lineStyles = ['k-']\n lineWidths = [3]\n\n fields = [SST]\n legendText = [mainRunName]\n\n if dsRefSST is not None:\n refSST = dsRefSST[varName].isel(nOceanRegions=regionIndex)\n fields.append(refSST)\n lineStyles.append('b-')\n lineWidths.append(1.5)\n refRunName = self.refConfig.get('runs', 'mainRunName')\n legendText.append(refRunName)\n\n if preprocessedReferenceRunName != 'None':\n SST_v0 = dsPreprocessedTimeSlice.SST\n fields.append(SST_v0)\n lineStyles.append('r-')\n lineWidths.append(1.5)\n legendText.append(preprocessedReferenceRunName)\n\n timeseries_analysis_plot(config, fields, movingAveragePoints,\n title, xLabel, yLabel, figureName,\n lineStyles=lineStyles,\n lineWidths=lineWidths,\n legendText=legendText, calendar=calendar)\n\n caption = 'Running Mean of {} Sea Surface Temperature'.format(\n region)\n write_image_xml(\n config=config,\n filePrefix=filePrefix,\n componentName='Ocean',\n componentSubdirectory='ocean',\n galleryGroup='Time Series',\n groupLink='timeseries',\n thumbnailDescription='{} SST'.format(region),\n imageDescription=caption,\n imageCaption=caption)\n\n # }}}\n\n# }}}\n\n# vim: foldmethod=marker ai ts=4 sts=4 et sw=4 ft=python\n","sub_path":"mpas_analysis/ocean/time_series_sst.py","file_name":"time_series_sst.py","file_ext":"py","file_size_in_byte":9862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"162617670","text":"# -*- coding: utf-8 -*-\n'''\nCreated on Aug 31, 2016\n\n@author: songbo\n'''\n\nimport os\nimport time\nfrom subprocess import Popen, PIPE\n\nfrom com.qa.automation.appium.configs.driver_configs import appPackage_ffan\n\n\nclass Performance(object):\n def __init__(self, reportPath):\n '''\n 初始化性能测试信息\n :param reportPath: 日志文件保存路径\n '''\n self.reportPath = reportPath\n self.now = time.strftime(\"%Y_%m_%d_%H_%M_%S\")\n\n def getPid(self):\n '''\n 获取应用PID\n :return: 应用PID\n '''\n cmdPid = \"adb shell ps | grep ' %s\\r' | awk '{print $2}'\" % (appPackage_ffan)\n ret = Popen(cmdPid, shell=True, stdout=PIPE, stderr=PIPE)\n\n pid, err = ret.communicate()\n\n return pid.decode('utf-8').split('\\n')[0]\n\n def getCpu(self):\n '''\n 获取应用cpu使用状态, 并保存至日志文件中\n :return: 无\n '''\n pid = self.getPid()\n if pid:\n cpu = \"dumpsys cpuinfo | grep \" + pid\n cmdCpu = \"adb shell \\\"%s\\\"\" % (cpu)\n ret = Popen(cmdCpu, shell=True, stdout=PIPE, stderr=PIPE)\n\n cpuInfo, err = ret.communicate()\n\n if err or not cpuInfo:\n return\n cpuRate = cpuInfo.decode('utf-8').split(\"/\" + appPackage_ffan + \":\")[0].split(\"%\")[0]\n logName = \"Cpu_performance.txt\"\n logPath = os.path.join(self.reportPath, logName)\n f = open(logPath, \"a\")\n f.write(\"%s:%s\" % (time.strftime(\"%Y/%m/%d %H_%M_%S\"), cpuRate) + \"\\n\")\n f.close()\n\n def getMemory(self):\n '''\n 获取应用内存使用状态, 并保存至日志文件中\n :return: 无\n '''\n pss = \"dumpsys meminfo \" + appPackage_ffan + \" | grep TOTAL\"\n cmdPss = \"adb shell \\\"%s\\\"\" % (pss)\n ret = Popen(cmdPss, shell=True, stdout=PIPE, stderr=PIPE)\n\n memInfo, err = ret.communicate()\n\n if err or not memInfo:\n return\n mem = int(memInfo.decode('utf-8').split(\" \")[3])/1024\n logName = \"Mem_peformance.txt\"\n logPath = os.path.join(self.reportPath, logName)\n f = open(logPath, \"a\")\n f.write(\"%s:%s\" % (time.strftime(\"%Y/%m/%d %H_%M_%S\"), mem) + \"\\n\")\n f.close()\n\n def getTraffic(self):\n cmdTraffic = \"adb shell cat /proc/net/xt_qtaguid/stats | grep rmnet0\"\n ret = Popen(cmdTraffic, shell=True, stdout=PIPE, stderr=PIPE)\n trafficInfo, err = ret.communicate()\n if err or not trafficInfo:\n cmdTraffic = \"adb shell cat /proc/net/xt_qtaguid/stats | grep wlan0\"\n ret = Popen(cmdTraffic, shell=True, stdout=PIPE, stderr=PIPE)\n trafficInfo, err = ret.communicate()\n if err or not trafficInfo:\n return\n rateLines = trafficInfo.decode('utf-8').split('\\n')\n totalTraffic = 0\n for rateLine in rateLines:\n try:\n upTraffic = float(rateLine.split(' ')[7])\n downTraffic = float(rateLine.split(' ')[5])\n except:\n break\n totalTraffic = upTraffic + downTraffic + totalTraffic\n\n getTime = time.time()\n\n return totalTraffic, getTime\n\n def parseTraffic(self, startTraffic, endTraffic, duration):\n traffic = round((endTraffic - startTraffic) / 1024 / 1024, 2)\n\n logName = \"Traffic_performance.txt\"\n logPath = os.path.join(self.reportPath, logName)\n f = open(logPath, \"a\")\n f.write(\"%s:%s\" % (duration, traffic) + \"\\n\")\n f.close()\n\n def getRx(self):\n '''\n 获取应用下行速率\n :return: 无\n '''\n currentRx = self._getRate('down')\n if currentRx is None:\n return\n\n logName = \"Rx_performance.txt\"\n logPath = os.path.join(self.reportPath, logName)\n f = open(logPath, \"a\")\n f.write(\"%s:%s\" % (time.strftime(\"%Y/%m/%d %H_%M_%S\"), currentRx) + \"\\n\")\n f.close()\n\n def getTx(self):\n '''\n 获取应用上行速率\n :return: 无\n '''\n currentTx = self._getRate('up')\n if currentTx is None:\n return\n\n logName = \"Tx_performance.txt\"\n logPath = os.path.join(self.reportPath, logName)\n f = open(logPath, \"a\")\n f.write(\"%s:%s\" % (time.strftime(\"%Y/%m/%d %H_%M_%S\"), currentTx) + \"\\n\")\n f.close()\n\n def _getRate(self, sort):\n '''\n 获取上下行速率\n :return: 速率\n '''\n pid = self.getPid()\n uid = self._getUid(pid)\n currentRateList = []\n for _ in range(2):\n cmdRate = \"adb shell cat /proc/net/xt_qtaguid/stats | grep %s\" % uid\n ret = Popen(cmdRate, shell=True, stdout=PIPE, stderr=PIPE)\n\n rateInfo, err = ret.communicate()\n if err or not rateInfo:\n return\n rateLines = rateInfo.decode('utf-8').split('\\n')\n totlaRate = 0\n for rateLine in rateLines:\n try:\n if sort == 'up':\n rate = float(rateLine.split(' ')[7])\n elif sort == 'down':\n rate = float(rateLine.split(' ')[5])\n else:\n return None\n except:\n break\n totlaRate = rate + totlaRate\n currentRateList.append(totlaRate)\n time.sleep(1)\n\n currentRate = round((currentRateList[1] - currentRateList[0]) / 1024, 2)\n if currentRate < 0:\n return 0\n else:\n return currentRate\n\n def _getUid(self, pid):\n '''\n 获取进程UID\n :param pid: 进程PID\n :return: 进程UID\n '''\n cmdUid = \"adb shell cat /proc/%s/status | grep Uid:\" % pid\n ret = Popen(cmdUid, shell=True, stdout=PIPE, stderr=PIPE)\n\n uidInfo, err = ret.communicate()\n if err or not uidInfo:\n return\n\n uid = uidInfo.decode('utf-8').split('\\t')[1]\n return uid\n\n","sub_path":"AutoFrameworkForAppiumPy/com/qa/automation/appium/cases/android/ffan/common/performance.py","file_name":"performance.py","file_ext":"py","file_size_in_byte":6102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"299623563","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\ntorch.manual_seed(3)\n\ndef l21_reg(data):\n m = data.shape[0]\n n = data.shape[1]\n\n outer_sum = 0\n for i in range(m):\n inner_sum = 0\n for j in range(n):\n inner_sum += data[i][j] ** 2\n outer_sum += inner_sum ** 0.5\n return outer_sum\n\n\ndef find_latent(l):\n m = l.size()[0]\n n = l.size()[1]\n # subtract the column mean\n for i in range(0, n):\n col_sum = 0\n for j in range(0, m):\n col_sum += l[j][i]\n mean = col_sum / m\n for j in range(0, m):\n l[j][i] = l[j][i] - mean\n # l = torch.mm(l, torch.transpose(l, 0, 1))\n return l\n\n\narr = torch.randint(0, 10, (4, 4))\narr = arr.float()\narr = find_latent(arr)\nprint(torch.sum(arr, dim=0))\n\n\n# class ElasticNetRegularizer(_Regularizer):\n# \"\"\"\n# Elastic Net Regularizer\n# \"\"\"\n# def __init__(self, model, lambda_reg=0.01, alpha_reg=0.01):\n# super(ElasticNetRegularizer, self).__init__(model=model)\n# self.lambda_reg = lambda_reg\n# self.alpha_reg = alpha_reg\n#\n# def regularized_param(self, param_weights, reg_loss_function):\n# reg_loss_function += self.lambda_reg * \\\n# (((1 - self.alpha_reg) * ElasticNetRegularizer.__add_l2(var=param_weights)) +\n# (self.alpha_reg * ElasticNetRegularizer.__add_l1(var=param_weights)))\n# return reg_loss_function\n#\n# def regularized_all_param(self, reg_loss_function):\n# for model_param_name, model_param_value in self.model.named_parameters():\n# if model_param_name.endswith('weight'):\n# reg_loss_function += self.lambda_reg * \\\n# (((1 - self.alpha_reg) * ElasticNetRegularizer.__add_l2(var=model_param_value)) +\n# (self.alpha_reg * ElasticNetRegularizer.__add_l1(var=model_param_value)))\n# return reg_loss_function\n#\n# @staticmethod\n# def __add_l1(var):\n# return var.abs().sum()\n#\n# @staticmethod\n# def __add_l2(var):\n# return var.pow(2).sum()\n#\n# self.lambda_reg * (((1 - self.alpha_reg) * ElasticNetRegularizer.__add_l2(var=param_weights)) + (self.alpha_reg * ElasticNetRegularizer.__add_l1(var=param_weights)))\n","sub_path":"Playground.py","file_name":"Playground.py","file_ext":"py","file_size_in_byte":2364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"345631639","text":"#!/usr/bin/env python3.2\n\nimport praw\nimport sys\nimport random\n\nclass MarkovModel:\n def __init__(self):\n self._computed = False\n self._database = dict()\n\n def set_text(self, text):\n self._text = text\n\n def set_order(self, order):\n self._order = order\n\n def analyze_text(self):\n length = len(self._text)\n all_substrings = [self._text[i:i + self._order + 1] for i in range(length - self._order)]\n for string in all_substrings:\n key = string[:len(string) - 1]\n val = string[len(string) - 1]\n if key not in self._database:\n self._database[key] = list(val)\n else:\n self._database[key].append(val)\n self._computed = True\n\n def get_first_ngram(self):\n return self._text[:self._order]\n\n def get_next_character(self, ngram):\n if not self._computed:\n self.analyze_text()\n\n if len(ngram) != self._order:\n raise Exception(\"ngram length is incorrect\")\n else:\n if ngram not in self._database:\n return None\n else:\n vals = self._database[ngram]\n length = len(vals)\n random_index = random.randint(0, length - 1)\n return vals[random_index]\n\n def generate_text(self, num_characters):\n ngram = self.get_first_ngram()\n i = 0\n text = ngram\n\n while (i < num_characters):\n next_char = self.get_next_character(ngram)\n if next_char is None:\n ngram = self.get_first_ngram()\n else:\n text += next_char\n ngram = ngram[1:] + next_char\n i += 1\n\n return text.encode('utf-8')\n\n\n\ndef main():\n # get username and password from the command line arguments\n user = sys.argv[1]\n pwd = sys.argv[2]\n\n # r = praw.Reddit(user_agent='jrb by /u/infinitus_')\n # r.login(user, pwd)\n\n text = \"\"\"Mr. And Mrs. Dursley, of Number four, Privet Drive, were proud to say that they were perfectly normal, thank you very much. They were the last people you'd expect to be involved with anything strange or mysterious, because they just didn't hold with such nonsense. Mr. Dursley was the director of a firm called Grunnings, which made drills. He was a big, beefy man with hardly any neck, although he did have a very large mustache. Mrs. Dursley was thin and blonde and had nearly twice the usual amount of neck, which came in very useful as she spent much of her time craning over garden fences, spying on the neighbors. The Dursleys had a small son called Dudley and in their opinion there was no finer boy anywhere.\"\"\"\n\n mm = MarkovModel()\n mm.set_text(text)\n mm.set_order(6)\n print(mm.generate_text(500))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"typical-post-bot.py","file_name":"typical-post-bot.py","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"571420856","text":"\"\"\"\nCreated by: Mohit Sharma\n\"\"\"\nimport re\nimport random\nimport xlsxwriter\nimport nltk\nfrom collections import OrderedDict\n\nnoun_words = []\nlist_of_tags = [\"VB\", \"VBD\", \"VBG\", \"VBP\", \"VBN\", \"VBZ\", \"NN\", \"NNS\", \"NNP\", \"JJ\", \"RB\"]\n# get list of nouns from the file\nwith open('nouns.txt', 'r') as f:\n for line in f:\n line = line.replace(\" \", \"\")\n line = line.replace(\"\\n\", \"\")\n noun_words.append(line)\n noun_words = [item for item in noun_words if item != '']\n # print(noun_words)\n len_noun_words = len(noun_words)\n\n# get list of sentences from the essay\nwith open('original.txt', 'r+') as f:\n original_sentence = OrderedDict()\n count = 0\n # getting the input in the right format\n for line in f:\n splitted = re.split(\"[.]\", line)\n splitted = [item for item in splitted if len(item.split()) > 9]\n\n for l in splitted:\n if not l == \"\":\n original_sentence[count] = l\n count += 1\n # print(original_sentence)\n\n original_sentence = {i: j for i, j in original_sentence.items() if len(j) > 1}\n copy_original_sent = original_sentence\n changed_sentence = OrderedDict()\n nouns_used = OrderedDict()\n original_word = OrderedDict()\n\n # print(copy_original_sent)\n\n count = 0\n# replace a noun in the sentence with a random noun\n for key, value in copy_original_sent.items():\n if len(value) > 4:\n value = value.lstrip(\" \")\n value = ([value])\n value = value[0].split()\n # print(value)\n length = len(value)\n\n bow = []\n\n # find index of noun in the sentence -\"value\"\n # tokenize line\n value = ' '.join(value)\n tokens = [nltk.word_tokenize(value)]\n # tagging tokens\n tagged_tokens = [nltk.pos_tag(token) for token in tokens]\n # getting BOW\n for each_token in tagged_tokens:\n for token, tag in each_token:\n if tag in list_of_tags and len(token) > 2:\n bow.append(token)\n bow = list(set(bow))\n\n # print(len(bow))\n value = value.replace(\",\", \"\")\n value = value.split()\n # finding index of noun in bow of the sentence - \"value\"\n try:\n random_bow_index = random.randrange(0, len(bow)-1)\n # print(value)\n # print(bow[random_bow_index])\n # print(value.index(bow[random_bow_index]))\n noun_index = value.index(bow[random_bow_index])\n while len(value[noun_index]) <= 3:\n random_bow_index = random.randrange(0, len(bow) - 1)\n noun_index = value.index(bow[random_bow_index])\n # print(noun_index)\n #\n # print(value[noun_index])\n random_noun = random.randrange(0, len_noun_words)\n original_word[count] = value[noun_index]\n value[noun_index] = noun_words[random_noun]\n changed_sentence[key] = ' '.join(value)\n nouns_used[key] = noun_words[random_noun]\n count += 1\n except:\n print(\"\")\n pass\n\n\nprint(original_sentence)\nprint(changed_sentence)\nprint(nouns_used)\n\n\n# writing to excel sheet.\nworkbook = xlsxwriter.Workbook('Database.xlsx')\nworksheet = workbook.add_worksheet()\n\n# Widen the first column to make the text clearer.\nworksheet.set_column('A:A', 20)\nworksheet.set_column('B:B', 20)\nworksheet.set_column('C:C', 20)\n\n\n# Add a bold format to use to highlight cells.\nbold = workbook.add_format({'bold': True})\n\n# Write some simple text.\nworksheet.write('A1', 'Normal Text', bold)\nworksheet.write('B1', 'Obfuscated Text', bold)\nworksheet.write('C1', 'Original Word', bold)\nworksheet.write('D1', 'Obfuscated Word', bold)\n\nnum_of_items_in_dic = max(changed_sentence, key=int)\n\n\nfor i in range(0, num_of_items_in_dic):\n try:\n worksheet.write(i, 0, original_sentence[i])\n worksheet.write(i, 1, changed_sentence[i])\n worksheet.write(i, 2, original_word[i])\n worksheet.write(i, 3, nouns_used[i])\n except:\n pass\n\nworkbook.close()\n","sub_path":"Project/Database/making_database.py","file_name":"making_database.py","file_ext":"py","file_size_in_byte":4149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"98520871","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n \n def convertLLtoList(self, L):\n tmp = []\n while(L.next != None):\n tmp.append(L.val)\n L = L.next\n return tmp\n \n def creatLLfromList(self, l):\n if len(l) == 1:\n return ListNode(l[0])\n else:\n node = ListNode(l[-1])\n node.next = self.creatLLfromList(l[:-1])\n return node\n \n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n \n l1 = self.convertLLtoList(l1)\n l2 = self.convertLLtoList(l2)\n \n if len(l1) < len(l2):\n A = l1\n B = l2\n else:\n A = l2\n B = l1\n i = e = 0 \n c = []\n for a in A:\n b = B[i]\n i = i+1\n if a + b + e < 10:\n c.append(a + b + e)\n e = 0\n else:\n c.append(a + b + e - 10)\n e = 1\n \n for b in B[i:]:\n i = i + 1\n if b + e < 10:\n c.append(b)\n else:\n c.append(b+e-10)\n e = 1\n \n if e == 1:\n c.append(e)\n \n result = self.creatLLfromList(c)\n \n return result\n \n \n\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution_2(object):\n \n def convertLLtoList(self, L):\n tmp = []\n while(L.val != None):\n tmp.append(L.val)\n if L.next != None:\n L = L.next\n else:\n break\n return tmp\n \n def convertListtoNum(self, nums):\n count = 0\n result = 0\n for num in nums:\n result = result + num * 10**count\n count = count + 1\n return result\n \n def creatLLfromList(self, l):\n if len(l) == 1:\n return ListNode(l[0])\n else:\n node = ListNode(l[-1])\n node.next = self.creatLLfromList(l[:-1])\n return node\n\n def addTwoNumbers(self, l1, l2):\n l1_num = self.convertListtoNum(self.convertLLtoList(l1))\n l2_num = self.convertListtoNum(self.convertLLtoList(l2))\n result = l1_num + l2_num \n result_list = [int(i) for i in list(str(result))]\n return self.creatLLfromList(result_list)\n \n\nclass Solution_3(object):\n\n def addTwoNumbers(self, l1, l2):\n result = carry = 0\n l_result_cpy = l_result = ListNode(0)\n while(l1 != None or l2 != None):\n if l1 == None:\n l1 = ListNode(0)\n if l2 == None:\n l2 = ListNode(0)\n \n result = carry + l1.val + l2.val\n carryflag = result - 10 >= 0\n if carryflag:\n carry = 1\n l_result.val = result - 10\n l_result.next = ListNode(carry)\n l_result = l_result.next\n else:\n carry = 0\n l_result.val = result\n \n if l1.next != None or l2.next != None:\n l_result.next = ListNode(0)\n l_result = l_result.next\n if l1.next!=None:\n l1 = l1.next\n else:\n l1 = None\n if l2.next != None:\n l2 = l2.next\n else:\n l2 = None\n \n return l_result_cpy\n","sub_path":"2 Add Two Numbers.py","file_name":"2 Add Two Numbers.py","file_ext":"py","file_size_in_byte":3756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"178900942","text":"#This is a Nipype generator. Warning, here be dragons.\nimport sys\nimport nipype\nimport nipype.pipeline as pe\nimport nipype.interfaces.io as io\nimport nipype.interfaces.ants as ants\nimport nipype.interfaces.afni as afni\nimport nipype.interfaces.fsl as fsl\n\nWorkingDirectory = \"~/Porcupipelines/ThisStudy\"\n\n#Generic datagrabber module that wraps around glob in an\nNodeHash_30bb950 = pe.Node(io.S3DataGrabber(outfields=['outfiles']), name = 'NodeName_30bb950')\nNodeHash_30bb950.inputs.anon = True\nNodeHash_30bb950.inputs.bucket = 'openneuro'\nNodeHash_30bb950.inputs.bucket_path = 'ds000101/ds000101_R2.0.0/uncompressed/'\nNodeHash_30bb950.inputs.local_directory = '/tmp'\nNodeHash_30bb950.inputs.sort_filelist = True\nNodeHash_30bb950.inputs.template = 'sub-01/anat/sub-01_T1w.nii.gz'\n\n#Wraps command **N4BiasFieldCorrection**\nNodeHash_1ea4b50 = pe.Node(interface = ants.N4BiasFieldCorrection(), name = 'NodeName_1ea4b50')\nNodeHash_1ea4b50.inputs.copy_header = False\nNodeHash_1ea4b50.inputs.dimension = 3\nNodeHash_1ea4b50.inputs.num_threads = 4\nNodeHash_1ea4b50.inputs.save_bias = True\n\n#Wraps command **3dUnifize**\nNodeHash_291d6d0 = pe.Node(interface = afni.Unifize(), name = 'NodeName_291d6d0')\nNodeHash_291d6d0.inputs.outputtype = 'NIFTI_GZ'\n\n#Wraps command **3dSkullStrip**\nNodeHash_1ddfa30 = pe.Node(interface = afni.SkullStrip(), name = 'NodeName_1ddfa30')\nNodeHash_1ddfa30.inputs.outputtype = 'NIFTI_GZ'\n\n#Wraps command **3dcalc**\nNodeHash_3bd6370 = pe.Node(interface = afni.Calc(), name = 'NodeName_3bd6370')\nNodeHash_3bd6370.inputs.expr = 'a*step(b)'\nNodeHash_3bd6370.inputs.outputtype = 'NIFTI_GZ'\n\n#Wraps command **fslmaths**\nNodeHash_49ddb10 = pe.Node(interface = fsl.Threshold(), name = 'NodeName_49ddb10')\nNodeHash_49ddb10.inputs.args = '-bin'\nNodeHash_49ddb10.inputs.thresh = 1.e-3\n\n#Wraps command **3dUnifize**\nNodeHash_229c200 = pe.Node(interface = afni.Unifize(), name = 'NodeName_229c200')\nNodeHash_229c200.inputs.gm = True\nNodeHash_229c200.inputs.outputtype = 'NIFTI_GZ'\n\n#Generic datasink module to store structured outputs\nNodeHash_3207070 = pe.Node(interface = io.DataSink(), name = 'NodeName_3207070')\nNodeHash_3207070.inputs.base_directory = '/tmp'\n\n#Create a workflow to connect all those nodes\nanalysisflow = nipype.Workflow('MyWorkflow')\nanalysisflow.connect(NodeHash_30bb950, 'outfiles', NodeHash_1ea4b50, 'input_image')\nanalysisflow.connect(NodeHash_1ea4b50, 'output_image', NodeHash_291d6d0, 'in_file')\nanalysisflow.connect(NodeHash_291d6d0, 'out_file', NodeHash_1ddfa30, 'in_file')\nanalysisflow.connect(NodeHash_1ea4b50, 'bias_image', NodeHash_3207070, 'bias_image')\nanalysisflow.connect(NodeHash_291d6d0, 'out_file', NodeHash_3bd6370, 'in_file_a')\nanalysisflow.connect(NodeHash_1ddfa30, 'out_file', NodeHash_3bd6370, 'in_file_b')\nanalysisflow.connect(NodeHash_3bd6370, 'out_file', NodeHash_49ddb10, 'in_file')\nanalysisflow.connect(NodeHash_3bd6370, 'out_file', NodeHash_229c200, 'in_file')\nanalysisflow.connect(NodeHash_49ddb10, 'out_file', NodeHash_3207070, 'out_mask')\nanalysisflow.connect(NodeHash_229c200, 'out_file', NodeHash_3207070, 'out_file')\n\n#Run the workflow\nplugin = 'MultiProc' #adjust your desired plugin here\nplugin_args = {'n_procs': 1} #adjust to your number of cores\nanalysisflow.write_graph(graph2use='flat', format='png', simple_form=False)\nanalysisflow.run(plugin=plugin, plugin_args=plugin_args)\n","sub_path":"_examples/example_pipelines/skullstrip_afni_ants_example/porcupine_generated_pipeline.py","file_name":"porcupine_generated_pipeline.py","file_ext":"py","file_size_in_byte":3347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"128992693","text":"from django.test import TestCase\nfrom django.urls import reverse\nfrom django.http import HttpResponseRedirect\nfrom django.conf import settings\nfrom django.contrib.auth import get_user_model\n\nUser = get_user_model()\n\n\nTEST_CREDENTIALS = {\n 'username': 'testuser',\n 'password': 'password123456'\n}\nLOGIN_URL = getattr(settings, 'LOGIN_URL', '/accounts/login/')\n\n\nclass UnauthorizedViewTestCase(TestCase):\n pattern = ''\n view_url = ''\n\n def setUp(self):\n self.view_url = reverse(self.pattern)\n\n\nclass AuthorizedViewTestCase(TestCase):\n pattern = ''\n view_url = ''\n\n def setUp(self):\n User.objects.create_user(**TEST_CREDENTIALS)\n self.client.login(**TEST_CREDENTIALS)\n self.view_url = reverse(self.pattern)\n\n\nclass IndexTest(TestCase):\n def test_redirect(self):\n \"\"\"Unauthorized client should redirect to login url\"\"\"\n response = self.client.get('/')\n self.assertIsInstance(response, HttpResponseRedirect)\n self.assertEqual(response.url, LOGIN_URL)\n\n\nclass PodcastsListUnauthorizedTest(UnauthorizedViewTestCase):\n pattern = 'podcasts:podcasts-list'\n\n def test_unauthorized(self):\n \"\"\"Unauthorized client should redirect to login url\"\"\"\n response = self.client.get(self.view_url)\n self.assertIsInstance(response, HttpResponseRedirect)\n self.assertEqual(response.url, LOGIN_URL)\n\n\nclass PodcastsListTest(AuthorizedViewTestCase):\n pattern = 'podcasts:podcasts-list'\n\n def test_logged_in(self):\n \"\"\"Log in client to get *actual* url\"\"\"\n response = self.client.get(self.view_url)\n self.assertEqual(response.status_code, 200)\n\n def test_logged_in_from_index(self):\n \"\"\"Test the redirect from index to podcasts-list\"\"\"\n response = self.client.get('/')\n self.assertIsInstance(response, HttpResponseRedirect)\n self.assertEqual(response.url, self.view_url)\n\n def test_empty_page_request(self):\n \"\"\"404 for request of empty/nonexistent pagination page\"\"\"\n response = self.client.get(self.view_url + '?page=9999')\n self.assertEqual(response.status_code, 404)\n","sub_path":"podcasts/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":2142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"259544845","text":"import torch.nn as nn\n\nclass TSResNetBlock(nn.Module):\n def __init__(self, in_features, n_featuremaps):\n super(TSResNetBlock, self).__init__()\n self.in_features = in_features\n self.n_featuremaps = n_featuremaps\n self.conv1 = nn.Conv1d(in_channels=in_features, out_channels=n_featuremaps,\n kernel_size=9, padding=4)\n self.bn1 = nn.BatchNorm1d(num_features=n_featuremaps)\n self.conv2 = nn.Conv1d(in_channels=n_featuremaps, out_channels=n_featuremaps,\n kernel_size=5, padding=2)\n self.bn2 = nn.BatchNorm1d(num_features=n_featuremaps)\n\n self.conv3 = nn.Conv1d(in_channels=n_featuremaps, out_channels=n_featuremaps,\n kernel_size=3, padding=2)\n self.bn3 = nn.BatchNorm1d(num_features=n_featuremaps)\n self.relu = nn.ReLU()\n self.sc = nn.Conv1d(in_channels=in_features, out_channels=n_featuremaps,\n kernel_size=1, padding=1)\n self.bnsc = nn.BatchNorm1d(num_features=n_featuremaps)\n\n def forward(self, x):\n out = self.relu(self.bn1(self.conv1(x)))\n out = self.relu(self.bn2(self.conv2(out)))\n out = self.relu(self.bn3(self.conv3(out)))\n shortcut = self.bnsc(self.sc(x))\n out = self.relu(shortcut+out)\n return out\n\n\nclass TSResNet(nn.Module):\n def __init__(self, args, loader):\n super(TSResNet, self).__init__()\n dataset = loader.dataset\n self.block1 = TSResNetBlock(in_features=dataset.n_variates, n_featuremaps=64)\n self.block2 = TSResNetBlock(in_features=64, n_featuremaps=128)\n self.block3 = TSResNetBlock(in_features=128, n_featuremaps=128)\n self.avgpool = nn.AvgPool1d(kernel_size=dataset.input_size-2)\n self.final = nn.Linear(in_features=128, out_features=dataset.output_size)\n self.features = nn.Sequential(self.block1, self.block2, self.block3)\n\n def forward(self, x):\n out = x\n out = out.view(out.shape[0], out.shape[2], out.shape[1])\n out = self.block1(out)\n out = self.block2(out)\n out = self.block3(out)\n out = self.avgpool(out).squeeze(dim=2)\n return self.final(out)\n","sub_path":"Towards_Advance_Adversarial_Attacks_Against_TSC/TimeSeriesAdversarialAttacks/models/resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"119620484","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Fix abbreviation, hesitation based on GLM provided Switchboard corpus.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport re\n\n\nclass GLM(object):\n \"\"\"docstring for GLM.\"\"\"\n\n def __init__(self, glm_path, space_mark='_'):\n super(GLM, self).__init__()\n\n self.space_mark = space_mark\n\n self.map_dict = {}\n with open(glm_path, 'r')as f:\n for line in f:\n line = line.strip()\n if len(line) == 0 or line[0] in [';', '*', '\\'']:\n continue\n before, after = line.split('=>')\n before = re.sub(r'[\\[\\]\\s]+', '', before).lower()\n after = after.split('/')[0]\n # NOTE: use the first word from candidates\n after = after.split(';')[0]\n after = re.sub(r'[\\[\\]{}]+', '', after).lower()\n\n # Remove consecutive spaces\n after = re.sub(r'[\\s]+', ' ', after)\n\n # Remove the first and last space\n if after[0] == ' ':\n after = after[1:]\n if after[-1] == ' ':\n after = after[:-1]\n\n self.map_dict[before] = after\n\n # For debug\n # print(before + ' => ' + after)\n\n def fix_trans(self, transcript):\n \"\"\"\n Args:\n transcript (string):\n Returns:\n transcript_fixed (string):\n \"\"\"\n # Fix abbreviation, hesitation based on GLM\n word_list = transcript.split(self.space_mark)\n word_list_mapped = []\n for word in word_list:\n if word in self.map_dict.keys():\n word_fixed = self.map_dict[word]\n word_list_mapped.extend(word_fixed.split(' '))\n\n # For debug\n # print('fixed: %s => %s' % (word, word_fixed))\n else:\n word_list_mapped.append(word)\n transcript_fixed = self.space_mark.join(word_list_mapped)\n\n return transcript_fixed\n","sub_path":"examples/swbd/s5c/exp/metrics/glm.py","file_name":"glm.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"311027457","text":"from scipy import signal\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n\n#----------------------------------------------------------------------\nfs =100\t\t# FRECUENCIA DE LA SEÑAL\nN =10\t\t\t# NUMERO DE MUESTRAS\nfase =0\namp =1\t\t\t# ESPECIFICA LA AMPLITUD DE LA SEÑAL\n\nciclos =4\t\t# NUMERO DE CICLOS\n\n#-----------------------------------------------------------------------\n\n# VALOR DEL EJE X\nX = []\nY = []\nXs = []\nYs = []\n\n\niG =0\n\n# VALOR DEL EJE Y\n\n\nfig, ax = plt.subplots(1,1)\nax.grid(True)\n\n# AMPLITUD EN X - GRAFICADOR\nax.set_xlim([0, ciclos*1/fs])\n\n# AMPLITUD EN Y - GRAFICADOR\nax.set_ylim([-amp-1, amp+1])\n\n\n#SEÑAL\ndef mysignal(f,n):\n return np.sin(2*np.pi*n/f*fs/N)\n\ndef my_square_signal(f,n):\n return signal.square(2*np.pi*n/f*fs/N)\n\ndef my_triangle_signal(f,n):\n return signal.sawtooth(2*np.pi*n/f*fs/N, 0.5)\n\n\n# SIMIL ARRAYLIST PARA ALMACENAMIENTO DE DATOS DE Fx1\nsinegraph, = ax.plot([], [],'b')\ndot, = ax.plot([], [], 'o', color='blue')\n\n# SIMIL ARRAYLIST PARA ALMACENAMIENTO DE DATOS DE Fx2\nsinegraph2, = ax.plot([], [],'r')\n\ndot2, = ax.plot([], [], 'o', color='red')\n\ndef senoidal(fs,f0,amp,muestras,fase):\n global X,Y,Xs,Ys,iG\n X.append(1/fs*(iG*1/muestras))\n Xs.append(1/fs*(iG-fase)*1/muestras)\n Y.append(mysignal(fs,iG))\t\t\t\t# CALCULO DE Y PARA FS\n Ys.append(mysignal(f0,iG))\t\t\t\t# CALCULO DE Y PARA F0\n# sinegraph.set_data(X,Y)\n dot.set_data(X[iG],Y[iG])\n sinegraph2.set_data(Xs,Ys)\n dot2.set_data(Xs[iG],Ys[iG])\n if iG == ciclos*N-1:\n X=[]\n Y=[]\n Xs=[]\n Ys=[]\n \ndef cuadrada(fs,f0,amp,muestras):\n global X,Y,Ys,iG\n\n X.append(1/fs*(iG*1/muestras))\n Y.append(mysignal(fs,iG))\n Ys.append(my_square_signal(fs,iG))\n sinegraph.set_data(X,Y)\n dot.set_data(X[iG],Y[iG])\n sinegraph2.set_data(X,Ys)\n dot2.set_data(X[iG],Ys[iG])\n if iG == ciclos*N-1:\n X=[]\n Y=[]\n Ys=[]\n\ndef triangular(fs,f0,amp,muestras):\n global X,Y,Ys,iG\n\n X.append(1/fs*(iG*1/muestras))\n Y.append(mysignal(fs,iG))\n Ys.append(my_triangle_signal(fs,iG))\n sinegraph.set_data(X,Y)\n dot.set_data(X[iG],Y[iG])\n sinegraph2.set_data(X,Ys)\n dot2.set_data(X[iG],Ys[iG])\n if iG == ciclos*N-1:\n X=[]\n Y=[]\n Ys=[]\n\n\n\n\ndef update(i):\n global iG\n iG = i\n senoidal(fs,fs*0.51,1,N,0)\n #cuadrada(fs,fs,1,N)\n #triangular(fs,fs,1,N)\n\n\n\n\nanim = animation.FuncAnimation(fig,update, ciclos*N, interval=10)\nplt.show()\n","sub_path":"entrega_tps/edgardo_torrelli/tp1/tp1_a.py","file_name":"tp1_a.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"73446248","text":"class RungeKutta:\n @staticmethod\n def map_point(system, x, num_steps, step_size):\n x1 = list(x)\n for i in range(num_steps):\n fx1 = system.get_derivative(x1)\n x2 = RungeKutta.move_point(x1, fx1, step_size / 2)\n fx2 = system.get_derivative(x2)\n x3 = RungeKutta.move_point(x1, fx2, step_size / 2)\n fx3 = system.get_derivative(x3)\n x4 = RungeKutta.move_point(x1, fx3, step_size)\n fx4 = system.get_derivative(x4)\n\n for j in range(len(x1)):\n x1[j] += step_size / 6 * (fx1[j] + 2 * fx2[j] + 2 * fx3[j] + fx4[j])\n\n if system.is_outside_bounds(x1):\n return x1\n\n return x1\n\n @staticmethod\n def move_point(x, fx, step_size):\n ret = list(x)\n for i in range(len(ret)):\n ret[i] += step_size * fx[i]\n\n return ret\n","sub_path":"Python/iMath/RungeKutta.py","file_name":"RungeKutta.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"31467127","text":"class Solution:\n def findShortestSubArray(self, nums: 'List[int]') -> 'int':\n left, right, count = {}, {}, {}\n\n for i, x in enumerate(nums):\n if x not in left:\n left[x] = i\n\n right[x] = i\n count[x] = count.get(x, 0) + 1\n\n max_degree = max(count.values())\n\n ret = len(nums) # start from the length of nums\n\n for x in count:\n if count[x] == max_degree:\n ret = min(ret, right[x] - left[x] + 1)\n\n return ret\n\n\n\n\n","sub_path":"697_degreeOfAnArray.py","file_name":"697_degreeOfAnArray.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"333841758","text":"import numpy as np\nimport numpy.random as rand\nimport itertools\n\n# non-diagonal elements int hte matrix have already divided into 2\ndef matrix_gen(dimension):\n matrix = rand.randint(-13, 15, (dimension, dimension))\n return matrix * matrix.transpose() # simetric matrix\n\ndef vector_get(dimension):\n vector = rand.randint(-13, 23, dimension + 1)\n return vector\n\ndef func_value(matrix, vector, point, dimension):\n return np.dot(np.dot(point, matrix), point) + np.dot(point, vector[: dimension]) + vector[dimension]\n\ndef find_global_optimum(dimension, perm, matrix, vector):\n perm_tupels = itertools.permutations(tuple(perm))\n opt = 0.0\n curr_val = 0.0\n opt_point = perm\n\n for point in perm_tupels:\n curr_val = func_value(matrix, vector, point, dimension)\n if curr_val <= opt:\n opt = curr_val\n opt_point = point\n\n return np.array(opt_point)\n\ndef limits_vector_new_free_member_gen(matrix, vector, point, dimension, step):\n f_val = func_value(matrix, vector, point, dimension)\n if f_val <= 0:\n vector\n\n new_free_member = -(f_val + step)\n vector[dimension] += new_free_member\n return vector\n\ndef available_points(dimension):\n perm = np.loadtxt(\"./Data/Permutation.txt\")\n perm_tupels = itertools.permutations(tuple(perm))\n matrix1 = np.loadtxt(\"./Data/LimitMatrix1.txt\", delimiter=\" \")\n vector1 = np.loadtxt(\"./Data/LimitVector1.txt\",)\n matrix2 = np.loadtxt(\"./Data/LimitMatrix2.txt\", delimiter=\" \")\n vector2 = np.loadtxt(\"./Data/LimitVector2.txt\", )\n\n count = 0\n\n for point in perm_tupels:\n curr_val1 = func_value(matrix1, vector1, point, dimension)\n curr_val2 = func_value(matrix2, vector2, point, dimension)\n if (curr_val1 <= 0) and (curr_val2 <= 0):\n count += 1\n\n return count\n\ndef task_gen():\n dimension = 50\n\n matrix = matrix_gen(dimension)\n vector = vector_get(dimension)\n perm = rand.permutation(dimension)\n\n np.savetxt('./Data/Permutation.txt', perm, '%d')\n np.savetxt('./Data/Vector.txt', vector, '%d')\n np.savetxt('./Data/Matrix.txt', matrix, '%d')\n\n # global_opt = find_global_optimum(dimension, perm, matrix, vector)\n # print(global_opt)\n # print(func_value(matrix, vector, global_opt, dimension))\n\n rand.shuffle(perm)\n\n matrix = matrix_gen(dimension)\n vector = vector_get(dimension)\n #vector = limits_vector_new_free_member_gen(matrix, vector, perm, dimension, 2)\n print(func_value(matrix, vector, perm, dimension))\n\n np.savetxt('./Data/LimitVector1.txt', vector, '%d')\n np.savetxt('./Data/LimitMatrix1.txt', matrix, '%d')\n\n matrix = matrix_gen(dimension)\n vector = vector_get(dimension)\n #vector = limits_vector_new_free_member_gen(matrix, vector, perm, dimension, 7)\n print(func_value(matrix, vector, perm, dimension))\n\n np.savetxt('./Data/LimitVector2.txt', vector, '%d')\n np.savetxt('./Data/LimitMatrix2.txt', matrix, '%d')\n\n #print(available_points(dimension))\n\n\ntask_gen()","sub_path":"MatrixAndVectorGen.py","file_name":"MatrixAndVectorGen.py","file_ext":"py","file_size_in_byte":3007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"611879724","text":"import socket\nimport sys\nimport argparse\nimport threading\nimport http.client\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"Host_Name\")\nparser.add_argument(\"PortNumber\", nargs = '?' , type = int, default = 8080)\nparser.add_argument(\"filename\" , nargs = '?', default = \"index.html\")\nargs = parser.parse_args()\n\nhost = args.Host_Name\nport = args.PortNumber\n\ndef receive(socket, signal):\n while signal:\n try:\n data = socket.recv(4096)\n print('Hostname\\t\\t: ', socket.getpeername())\n print('Socket family\\t\\t: ', serverSocket.family) \n print('Socket protocol\\t\\t: ', serverSocket.proto)\n print('Socket timeout\\t\\t: ', serverSocket.gettimeout())\n print('Socket type\\t\\t: ', serverSocket.type)\n print(data)\n serverSocket.close() \n signal = False \n except:\n print(\"You have been disconnected from the server\")\n socket.close()\n signal = False\n break\n\ntry:\n serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n serverSocket.connect((host,port))\n try:\n send_file = \"GET /\" + args.filename + \" HTTP/1.1\\r\\n\\r\\n\" \n serverSocket.send(str.encode(send_file))\n \n except IOError:\n print(\"could not send filename\")\n serverSocket.close()\n \nexcept:\n print(\"Sorry could not connect\")\n input(\"Press enter to quit\")\n sys.exit(0)\n \n\nreceive_thread = threading.Thread(target = receive, args = (serverSocket, True))\nreceive_thread.start()\n\n ","sub_path":"client3.py","file_name":"client3.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"203994121","text":"\"\"\"\nWrite a Python program somewhat similar to http://www.pythonlearn.com/code/geoxml.py. The program will prompt for\na URL, read the XML data from that URL using urllib and then parse and extract the comment counts from the XML data,\ncompute the sum of the numbers in the file.\n\nWe provide two files for this assignment. One is a sample file where we give you the sum for your testing and the\nother is the actual data you need to process for the assignment.\nSample data:\nhttp://python-data.dr-chuck.net/comments_42.xml (Sum=2553)\nActual data:\nhttp://python-data.dr-chuck.net/comments_353536.xml (Sum ends with 90)\n\"\"\"\n\nimport urllib.request as ur\nimport xml.etree.ElementTree as et\n\nurl = input(\"Enter location: \")\n\ntotal_number = 0\nsum = 0\n\nprint(\"Receiving\", url)\nxml = ur.urlopen(url).read()\nprint(\"Received:\", len(xml), \"characters\")\n\ntree = et.fromstring(xml)\ncounts = tree.findall(\".//count\")\nfor count in counts:\n sum += int(count.text)\n total_number += 1\n\nprint(\"Count:\", total_number)\nprint(\"Sum:\", sum)\n","sub_path":"Access Web Data/ExtractingFromXML.py","file_name":"ExtractingFromXML.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"504498639","text":"\"\"\"You have x no. of 5 rupee coins and y no. of 1 rupee coins. You want to purchase an item for amount z. \r\nThe shopkeeper wants you to provide exact change. You want to pay using minimum number of coins. How many 5\r\nrupee coins and 1 rupee coins will you use? If exact change is not possible then display -1.\"\"\"\r\n\r\ndef make_amount(rupees_to_make, no_of_five, no_of_one):\r\n have_five_money = 5 * no_of_five\r\n have_one_money = 1 * no_of_one\r\n total_avl_money = have_five_money + have_one_money\r\n rupees_to_make = int(rupees_to_make) \r\n if rupees_to_make <= total_avl_money:\r\n if rupees_to_make < 5:\r\n req_five_coins = 0\r\n more_req_ones = rupees_to_make\r\n print(\"No. of Five needed :\",req_five_coins)\r\n print(\"No. of One needed :\",more_req_ones)\r\n else:\r\n req_five_coins = int(rupees_to_make / 5)\r\n more_req_ones = rupees_to_make - (req_five_coins * 5)\r\n if req_five_coins <= no_of_five:\r\n five = no_of_five - req_five_coins\r\n req_five_coins = -five + no_of_five\r\n more_req_ones = more_req_ones\r\n if no_of_one >= more_req_ones:\r\n print(\"No. of Five needed :\",req_five_coins)\r\n print(\"No. of One needed :\",more_req_ones)\r\n else:\r\n print(-1)\r\n else:\r\n five = req_five_coins - no_of_five\r\n req_five_coins = req_five_coins - five\r\n more_req_ones = more_req_ones +(five * 5)\r\n if no_of_one >= more_req_ones:\r\n print(\"No. of Five needed :\",req_five_coins)\r\n print(\"No. of One needed :\",more_req_ones)\r\n else:\r\n print(-1)\r\n else:\r\n print(-1)\r\n \r\n \r\n \r\nmake_amount(93,19,2)","sub_path":"change_pridector.py","file_name":"change_pridector.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"210649125","text":"import os\nimport json\nimport argparse\n\nfrom config import config\nimport parser\nimport network_objects\n\ndef do_parse():\n net_conf = parser.parse_conf()\n lease_conf = parser.parse_leases()\n nets = network_objects.build_networks(net_conf)\n network_objects.build_leases(lease_conf)\n return nets\n \ndef log_all(nets=None):\n if nets is None:\n nets = do_parse()\n d = {}\n for n in nets:\n d[n.name] = n.serialize()\n s = json.dumps(d)\n now = config.now\n fn = now.strftime(config.log_file_format)\n p = os.path.expanduser(config.log_file_path)\n if not os.path.exists(p):\n os.makedirs(p)\n with open(os.path.join(p, fn), 'w') as f:\n f.write(s)\n return nets\n \ndef log_stats(nets=None):\n if nets is None:\n nets = do_parse()\n d = {}\n for n in nets:\n d[n.name] = n.serialize(include_leases=False)\n now = config.now\n fn = 'stats.json'\n p = os.path.expanduser(config.log_file_path)\n if not os.path.exists(p):\n os.makedirs(p)\n fn = os.path.join(p, fn)\n if os.path.exists(fn):\n with open(fn, 'r') as f:\n s = f.read()\n _d = json.loads(s)\n else:\n _d = {}\n _d[str(now)] = d\n s = json.dumps(_d)\n with open(os.path.join(p, fn), 'w') as f:\n f.write(s)\n return nets\n \nif __name__ == '__main__':\n p = argparse.ArgumentParser()\n p.add_argument('--stats-only', dest='stats_only', action='store_true')\n args, remaining = p.parse_known_args()\n o = vars(args)\n nets = log_stats()\n if not o.get('stats_only'):\n log_all()\n","sub_path":"web/dhcpd_stats/log_stats.py","file_name":"log_stats.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"419256175","text":"# uncompyle6 version 3.6.7\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build\\bdist.win32\\egg\\source\\Tools\\LogError.py\n# Compiled at: 2019-02-21 18:44:24\n# Size of source mod 2**32: 775 bytes\nimport logging, sys\nfrom Tools.BasePara import error_log_path\nhandler = logging.FileHandler(error_log_path)\nhandler.setLevel(logging.WARNING)\nlogging.basicConfig(level=(logging.WARNING), format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nformatter = logging.Formatter('%(asctime)s - %(filename)s - %(funcName)s - %(message)s')\nhandler.setFormatter(formatter)\nlogger = logging.getLogger(__name__)\nlogger.addHandler(handler)","sub_path":"pycfiles/pyguppyclient-0.0.6.tar/LogError.cpython-36.py","file_name":"LogError.cpython-36.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"313258708","text":"from django.shortcuts import render, redirect\nfrom django.views import generic\nfrom .models import Event\nfrom .models import EventTranslation\nfrom .forms import LanguageForm, EventSubscriptionForm\n\nclass EventList(generic.ListView):\n model = Event \n context_object_name = \"filteredList\" # name of the list as a template variable\n template_name = 'eventlist.html' # template location\n\n def get_queryset(self):\n \tfilteredLanguage = self.request.GET.get('language', 'en_uk')\n \treturn Event.objects.filter(published_state__name__contains = 'Published', eventtranslation__language__code__contains=filteredLanguage)\n\n def get_context_data(self, **kwargs):\n context = super(EventList, self).get_context_data(**kwargs)\n filteredLanguage = self.request.GET.get('language', 'en_uk')\n eventList = Event.objects.filter(published_state__name__contains = 'Published', eventtranslation__language__code__contains=filteredLanguage)\n\n events = []\n\n for event in eventList:\n \ttrans = EventTranslation.objects.filter(eventOriginal__id__contains=event.id, language__code__contains=filteredLanguage).first()\n\n \tevents.append({\n \t\t'id': event.id,\n \t\t'date': event.date,\n \t\t'name': trans.eventName,\n \t\t})\n\n context['events'] = events\n context['form'] = LanguageForm()\n context['language'] = filteredLanguage\n return context\n\n\nclass EventDetail(generic.ListView):\n model = Event \n context_object_name = \"eventDetail\" # name of the list as a template variable\n template_name = 'eventdetail.html' # template location\n\n def get_context_data(self, **kwargs):\n context = super(EventDetail, self).get_context_data(**kwargs)\n eventId = self.request.GET.get('event', 0)\n filteredLanguage = self.request.GET.get('language', 'en_uk')\n\n if(eventId!=None):\n \tevent = Event.objects.filter(published_state__name__contains = 'Published', eventtranslation__language__code__contains=filteredLanguage, id = eventId).first()\n \tif(event!=None): \n\t \ttrans = EventTranslation.objects.filter(eventOriginal__id__contains=eventId, language__code__contains=filteredLanguage).first()\n\n\t \teventInfo = {\n\t \t\t'id': event.id,\n\t \t\t'date': event.date,\n\t \t\t'name': trans.eventName,\n\t \t\t'description': trans.description\n\t \t}\n\n\t \tcontext['eventInfo'] = eventInfo\n\t \tcontext['form'] = EventSubscriptionForm()\n\t else:\n\t \t# If the event could not be found, send an error message on screen\n \t\tcontext['eventInfo'] = { 'name': \"Event not found\" }\n return context\n\n# POST Request Handlers\ndef changeLanguage(request):\n if request.method == \"POST\":\n form = EventSubscriptionForm(request.POST)\n language = request.POST.get('language', 'en_uk')\n return redirect('/?language='+language)\n else:\n return render(request, '/', {'form': form})\n\ndef postSubscription(request):\n if request.method == \"POST\":\n form = EventSubscriptionForm(request.POST)\n eventId = request.POST.get('event', '')\n if form.is_valid():\n bbb = form.save(commit=False)\n bbb.event_id = Event.objects.get(pk=eventId)\n bbb.save()\n return redirect('events')\n else:\n return render(request, '/', {'form': form})\n\n\n\n\n\n","sub_path":"eventsapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"428419687","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Nov 19 19:07:22 2017\n\n@author: zhouying\n\"\"\"\n\nfrom datetime import datetime\nimport matplotlib.dates as mdates\nimport matplotlib.pyplot as plt\nimport pandas as pd\n \ndata = pd.read_csv('.\\\\data\\\\train.csv')\n\nxs = [datetime.strptime(d, '%Y-%m-%d').date() for d in data['date']]\nquestions = data['questions']\nanswers = data['answers']\nmyid = data['id']\n\n# 配置横坐标\nplt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))\nplt.gca().xaxis.set_major_locator(mdates.DayLocator())\n# Plot\nplt.scatter(xs, questions,c='r')\nplt.scatter(xs,answers,c='b')\nplt.show()\n\nys = [d.weekday() for d in xs]\nworkys = [i for i in range(len(ys)) if ys[i] not in [5,6]]\nrestys = [i for i in range(len(ys)) if ys[i] in [5,6]]\nfrom sklearn.linear_model import LinearRegression\nimport numpy as np\n# 创建并拟合模型\n\nworkid = [myid[i] for i in workys]#工作日的ID号\nworkques=[questions[i] for i in workys] #工作日的问题数\nworkanws=[answers[i] for i in workys]\nmodel1 = LinearRegression()\nmodel1.fit(np.array(workid).reshape(len(workys),1),np.array(workques).reshape(len(workys),1))\nmodel11 = LinearRegression()\nmodel11.fit(np.array(workques).reshape(len(workys),1),np.array(workanws).reshape(len(workys),1))\n\nprint(model1.coef_)\nprint(model1.intercept_)\nprint(model11.coef_)\nprint(model11.intercept_)\nrestid = [myid[i] for i in restys]#周末的ID号\nrestques=[questions[i] for i in restys] #周末的问题数\nrestans = [answers[i] for i in restys]\n\nmodel2 = LinearRegression()\nmodel2.fit(np.array(restid).reshape(len(restys),1),np.array(restques).reshape(len(restys),1))\nmodel22 = LinearRegression()\nmodel22.fit(np.array(restques).reshape(len(restys),1),np.array(restans).reshape(len(restys),1))\n\n\nprint(model2.coef_)\nprint(model2.intercept_)\nprint(model22.coef_)\nprint(model22.intercept_)\n\n\ntest = pd.read_csv('.\\\\data\\\\test.csv')\ntestid = test['id']\ntestdate= [datetime.strptime(d, '%Y-%m-%d').date() for d in test['date']]\ntestques = []\ntestans = []\nfor i in range(len(testid)):\n if testdate[i].weekday() not in [5,6]:\n q = model1.predict(np.array(int(testid[i])).reshape(-1,1))\n testques.append(q[0][0])\n q = model11.predict(q)\n testans.append(q[0][0])\n else:\n q = model2.predict(np.array(int(testid[i])).reshape(-1,1))\n testques.append(q[0][0])\n q = model22.predict(np.array(q))\n testans.append(q[0][0])\ndataframe = pd.DataFrame({'id':testid,'questions':testques,'answers':testans})\ncolumns = ['id','questions','answers']\ndataframe.to_csv('.\\\\data\\\\sample_submit3.csv',index=False,sep=',',columns=columns)\n","sub_path":"try/plot2.py","file_name":"plot2.py","file_ext":"py","file_size_in_byte":2628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"141169988","text":"#!/usr/bin/env python\nfrom __future__ import division\n\nimport time\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import linalg as linalg\nfrom numpy import random as random\n\nimport se2\n\nfrom .NearestNeighborsDubins import NearestNeighborsDubins\nfrom .PushObject import PushObject\nfrom .RRTNode import RRTNode\n\n\nclass RRTPushing:\n def __init__(self):\n self.sim_ = None\n self.nn_ = None\n self.ss_ = None\n self.root_ = None\n self.k_ = 5\n self.goalbias_ = 1.00\n self.eta_ = 20\n self.maxiters_ = 100\n self.max_goalsamples_ = 50\n\n ############################################################\n ### Getters and setters\n ############################################################\n def SetPushingSimulator(self, sim):\n self.sim_ = sim\n\n def GetPushingSimulator(self):\n return self.sim_\n\n def SetMaxGoalSampleCount(self, max_goalsamples):\n self.max_goalsamples_ = max_goalsamples\n\n def GetMaxGoalSampleCount(self):\n return self.max_goalsamples_\n\n def SetMaxIterations(self, maxiters):\n self.maxiters_ = maxiters\n\n def GetMaxIterations(self):\n return self.maxiters_\n\n def SetGoalBias(self, goalbias):\n self.goalbias_ = goalbias\n\n def GetGoalBias(self):\n return self.goalbias_\n\n def SetEta(self, eta):\n self.eta_ = eta\n\n def GetEta(self):\n return self.eta_\n\n def SetNearestNeighbors(self, nn):\n self.nn_ = nn\n\n def GetNearestNeighbors(self):\n return self.nn_\n\n def SetSampler(self, ss):\n self.ss_ = ss\n\n def GetSampler(self):\n return self.ss_\n\n def GetRoot(self):\n return self.root_\n\n def GetCosts(self):\n return self.costs_\n\n def GetTimes(self):\n return self.times_\n\n ############################################################\n ### RRT functions.\n ############################################################\n def Solve(self, x_start):\n # Preconditions.\n assert self.sim_ is not None\n sim = self.sim_\n self.Reset()\n\n # Set start and goal nodes.\n root = RRTNode()\n root.SetState(x_start)\n root.SetCost(0)\n self.root_ = root\n\n # Get goal positions.\n sim.SetRedSliderPositions(sim.GetRedGoalPosition())\n sim.SetBlueSliderPositions(sim.GetBlueGoalPosition())\n x_goal = sim.GetPoses()\n\n z_prev = root\n\n # Run RRT.\n self.ti_ = time.time()\n for i in range(self.maxiters_):\n # print 'Sampling...', i\n if np.random.uniform() < self.goalbias_:\n # Sample goal.\n x_rand = x_goal\n else:\n # Sample state using pushing simulator.\n x_rand = sim.SamplePoses()\n\n # Extend from nearest to sample.\n # print 'Extending...'\n z_new = self.Extend(x_rand, z_prev)\n\n if z_new is None:\n continue\n\n # Check if we've reached the goal.\n x_new = z_new.GetState()\n # sim.SetPoses(x_new)\n # sim.Draw()\n # plt.show()\n if sim.AreAllSlidersAtGoal():\n # print 'Goal...'\n path, ctrls = self.ExtractPath(root)\n # TODO Add more nuanced return value.\n return path, ctrls, z_new.GetCost(), True\n \n # Record time.\n self.times_[i] = time.time()-self.ti_\n\n z_prev = z_new\n\n # Report failure.\n path, ctrls = self.ExtractPath(root)\n \n return path, ctrls, z_prev.GetCost(), False\n\n def Extend(self, x_rand, z_prev):\n # Get simulator.\n sim = self.sim_\n \n # Find nearest state.\n z_nearest = z_prev\n x_nearest = z_nearest.GetState()\n\n # Get goal positions.\n sim.SetPoses(x_rand)\n t_goal = sim.GetSliderPositions()\n\n # Sample a pushing action.\n eta = self.eta_\n u = sim.SamplePushingAction(x_nearest, t_goal, eta)\n\n if u is None:\n return None\n\n # Steer.\n traj = sim.Steer(x_nearest, t_goal, u, eta)\n\n if not traj:\n return None\n \n # Create node for the new pose.\n z_new = RRTNode()\n z_new.SetState(traj[-1])\n\n # Set parent of z_new.\n edge = z_nearest.AddEdge(z_new, 1)\n\n # Add controls and trajectory to edge.\n sim.SetPoses(traj[-1])\n u = (u[0], sim.GetHandPose())\n edge.SetControls(u)\n edge.SetTrajectory(traj)\n\n return z_new\n\n def ExtractPath(self, root):\n path = []\n ctrls = []\n node = root\n while True:\n path.append(node.GetState())\n if len(node.GetOutgoingEdges()) == 0:\n break\n edge = node.GetOutgoingEdges()[0]\n ctrls.append(edge.GetControls())\n node = node.GetChildren()[0]\n return path, ctrls\n\n def ExtractTrajectory(self, root):\n traj = []\n node = root\n while True:\n if len(node.GetOutgoingEdges()) == 0:\n break\n edge = node.GetOutgoingEdges()[0]\n traj.append(edge.GetTrajectory())\n node = node.GetChildren()[0]\n return traj\n\n def Reset(self):\n self.root_ = None\n self.goalqueue_ = []\n self.costs_ = np.empty(self.maxiters_)\n self.costs_[:] = np.NAN\n self.times_ = np.empty(self.maxiters_)\n self.times_[:] = np.NAN\n self.ti_ = None\n","sub_path":"deep2d/RRTPushing.py","file_name":"RRTPushing.py","file_ext":"py","file_size_in_byte":5594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"459015039","text":"N = int(input())\nle = []\nchan = []\nsl = 0\narr = []\nwhile sl < N:\n arrtmp = list(int(i) for i in input().split())\n for so in arrtmp:\n sl = sl + 1\n if so % 2 != 0:\n le.append(so)\n else:\n chan.append(so)\n arr.extend(arrtmp) #lặp và thêm từng phần tử arrtmp vào arr\nle.sort(reverse=True)\nchan.sort()\ni = 0\nj = 0\nfor x in arr:\n if x % 2 != 0:\n print(le[i], end = ' ')\n i = i + 1\n else:\n print(chan[j], end =' ')\n j = j + 1\nprint()","sub_path":"PY02012_SapXepChanLe.py","file_name":"PY02012_SapXepChanLe.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"264826446","text":"import re\nfrom .common import classes\n\ndef run():\n skyliner = classes.Region()\n\n skyliner.create_soup(\"https://www.skyline.co.nz/en/rotorua/things-to-do/\" \n \"rotorua-mountain-biking/rotorua-mountain-bike-park-info/\")\n \n #find table after h2\n try:\n trail_list = skyliner.soup.find(\n \"h2\",\n text=re.compile(r\"Trail Information\")\n ).find_next(\"ul\")\n\n except AttributeError:\n raise ConnectionError(\"Website could not be reached\")\n\n #grade numeric conversion from strings - as skyliner rotorua uses IMBA\n # trail grades, certain fields are null for NZ only grades\n grades = [None, \"Beginner\", \"Intermediate\",\\\n None, \"Advanced\", \"Expert\", None]\n\n for row in trail_list.find_all(\"li\"):\n name_and_status = row.find_all(\"div\")[0].h3.string\n #strip weird punctuation\n name_and_status = re.sub(r\"[\\\"“”]\", \"\", name_and_status)\n\n print(name_and_status)\n \n #this is kinda fucked because its a mess of spans and divs\n #so i had to do some weird shit\n grade = row.find_all(\"div\")[1].find_all(\"strong\")[-1]\n\n try:\n (parsed_name, status) = skyliner.parse(\n r\"(.+)\\s-\\s+([A-Za-z]+)\",\n name_and_status\n )\n except:\n (parsed_name, status) = skyliner.parse(\n r\"([A-Z].+)\\s([A-Z])\",\n name_and_status\n )\n\n #more weird shit cause sometimes a span is scraped\n if not type(grade) == str:\n grade = grade.string\n \n #no grade conversion needed for queenstown\n #as the correct number is already specified\n parsed_grade = skyliner.parse(r\".+\\s-\\s+([A-Z][a-z]+)\", grade)\n \n if parsed_grade:\n parsed_grade = parsed_grade[0]\n parsed_grade = grades.index(parsed_grade)\n else:\n parsed_grade = -1\n \n parsed_status = not status.upper() == \"CLOSED\"\n\n skyliner.trail_status.append(classes.Trail(parsed_name, parsed_grade, parsed_status))\n \n #convert to json\n return skyliner.json_encode()","sub_path":"trailscrape/templates/api/modules/scrapers/dev/skyliner.py","file_name":"skyliner.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"377226120","text":"import numpy as np\n\nimport torch\nfrom torch import optim\n\nimport random\nimport scipy.sparse\nfrom copy import deepcopy\n\nfrom utils import load_data, split_into_train_and_test, ndcg, recall\nfrom model import VAE\nfrom recpack.metrics import NDCGK, RecallK\nfrom recpack.algorithms import RecVAE\n\nimport argparse\nparser = argparse.ArgumentParser()\nparser.add_argument('--dataset', type=str)\nparser.add_argument('--hidden-dim', type=int, default=600)\nparser.add_argument('--latent-dim', type=int, default=200)\nparser.add_argument('--batch-size', type=int, default=500)\nparser.add_argument('--beta', type=float, default=None)\nparser.add_argument('--gamma', type=float, default=0.005)\nparser.add_argument('--lr', type=float, default=5e-4)\nparser.add_argument('--n-epochs', type=int, default=50)\nparser.add_argument('--n-enc_epochs', type=int, default=3)\nparser.add_argument('--n-dec_epochs', type=int, default=1)\nparser.add_argument('--not-alternating', type=bool, default=False)\nparser.add_argument('--user-col', type=str, default='user_id')\nparser.add_argument('--item-col', type=str, default='item_id')\nparser.add_argument('--timestamp-col', type=str, default='timestamp')\nparser.add_argument('--min-users-per-item', type=int, default=3)\nparser.add_argument('--min-items-per-user', type=int, default=3)\nparser.add_argument('--t', type=float, default=None)\n\n\nargs = parser.parse_args()\n\nseed = 1337\nrandom.seed(seed)\nnp.random.seed(seed)\ntorch.manual_seed(seed)\n\ndevice = torch.device(\"cuda:0\")\n\n# Load data using recpack\n\ndata = load_data(\n args.dataset,\n args.item_col,\n args.user_col,\n args.timestamp_col,\n args.min_users_per_item,\n args.min_items_per_user\n)\n\nt = args.t\nif t is None:\n t = data.timestamps.min() + ((data.timestamps.max() - data.timestamps.min()) * 0.7)\n\nprint(f\"splitting at t = {t}\")\n\ntrain_data, valid_in_data, valid_out_data, test_in_data, test_out_data = split_into_train_and_test(\n data, t)\n# subselect the nonzero users:\ntrain_users = set(train_data.nonzero()[0])\nvalidation_users = set(valid_in_data.nonzero()[0]).intersection(\n valid_out_data.nonzero()[0])\ntest_users = set(test_in_data.nonzero()[0]).intersection(\n test_out_data.nonzero()[0]\n)\n\ntrain_data = train_data[list(train_users)]\nvalid_in_data = valid_in_data[list(validation_users)]\nvalid_out_data = valid_out_data[list(validation_users)]\n\ntest_in_data = test_in_data[list(test_users)]\ntest_out_data = test_out_data[list(test_users)]\n\n# Log the shapes and nnz of all the data segments\nprint(f\"train_data - shape: {train_data.shape} -- nnz: {train_data.nnz}\")\nprint(\n f\"valid_in_data - shape: {valid_in_data.shape} -- nnz: {valid_in_data.nnz}\")\nprint(\n f\"valid_out_data - shape: {valid_out_data.shape} -- nnz: {valid_out_data.nnz}\")\nprint(f\"test_in_data - shape: {test_in_data.shape} -- nnz: {test_in_data.nnz}\")\nprint(\n f\"test_out_data - shape: {test_out_data.shape} -- nnz: {test_out_data.nnz}\")\n\n# THIS IS RECPACK THINGS:\n\nalgorithm = RecVAE(\n batch_size=args.batch_size,\n max_epochs=args.n_epochs,\n n_enc_epochs=args.n_enc_epochs,\n n_dec_epochs=args.n_dec_epochs,\n seed=seed,\n learning_rate=args.lr,\n dim_bottleneck_layer=args.latent_dim,\n dim_hidden_layer=args.hidden_dim,\n gamma=args.gamma,\n beta=args.beta\n)\n\n# Train the model.\nalgorithm.fit(train_data, validation_data=(\n valid_in_data,\n valid_out_data))\n\n# predict\nprediction = algorithm.predict(test_in_data)\n\nprint(f\"prediction shape: {prediction.shape}\")\nprint(\n f\"nonzero predicted users: {len(set(prediction.nonzero()[0]))}\")\nprint(\n f\"nonzero expected users: {len(set(test_out_data.nonzero()[0]))}\"\n)\nfroomle_metrics = [NDCGK(100), RecallK(20), RecallK(50)]\n# Evaluate:\nfor metric in froomle_metrics:\n metric.calculate(test_out_data, prediction)\n\n\ndef generate(batch_size, device, data_in, data_out=None,\n shuffle=False, samples_perc_per_epoch=1):\n assert 0 < samples_perc_per_epoch <= 1\n\n total_samples = data_in.shape[0]\n samples_per_epoch = int(total_samples * samples_perc_per_epoch)\n\n if shuffle:\n idxlist = np.arange(total_samples)\n np.random.shuffle(idxlist)\n idxlist = idxlist[:samples_per_epoch]\n else:\n idxlist = np.arange(samples_per_epoch)\n\n for st_idx in range(0, samples_per_epoch, batch_size):\n end_idx = min(st_idx + batch_size, samples_per_epoch)\n idx = idxlist[st_idx:end_idx]\n\n yield Batch(device, idx, data_in, data_out)\n\n\nclass Batch:\n def __init__(self, device, idx, data_in, data_out=None):\n self._device = device\n self._idx = idx\n self._data_in = data_in\n self._data_out = data_out\n\n def get_idx(self):\n return self._idx\n\n def get_idx_to_dev(self):\n return torch.LongTensor(self.get_idx()).to(self._device)\n\n def get_ratings(self, is_out=False):\n data = self._data_out if is_out else self._data_in\n return data[self._idx]\n\n def get_ratings_to_dev(self, is_out=False):\n return torch.Tensor(\n self.get_ratings(is_out).toarray()\n ).to(self._device)\n\n\ndef evaluate(model, data_in, data_out, metrics,\n samples_perc_per_epoch=1, batch_size=500):\n metrics = deepcopy(metrics)\n model.eval()\n\n for m in metrics:\n m['score'] = []\n\n for batch in generate(batch_size=batch_size,\n device=device,\n data_in=data_in,\n data_out=data_out,\n samples_perc_per_epoch=samples_perc_per_epoch\n ):\n\n ratings_in = batch.get_ratings_to_dev()\n ratings_out = batch.get_ratings(is_out=True)\n\n ratings_pred = model(\n ratings_in,\n calculate_loss=False).cpu().detach().numpy()\n\n if not (data_in is data_out):\n ratings_pred[batch.get_ratings().nonzero()] = -np.inf\n\n for m in metrics:\n m['score'].append(m['metric'](ratings_pred, ratings_out, k=m['k']))\n\n for m in metrics:\n m['score'] = np.concatenate(m['score']).mean()\n\n return [x['score'] for x in metrics]\n\n\ndef evaluate_recpack(model, data_in, data_out, metrics,\n samples_perc_per_epoch=1, batch_size=500):\n metrics = deepcopy(metrics)\n model.eval()\n print(f\"shape of output: {data_out.shape}\")\n full_expected = scipy.sparse.lil_matrix(data_out.shape)\n full_predicted = scipy.sparse.lil_matrix(data_out.shape)\n for i, batch in enumerate(generate(\n batch_size=batch_size,\n device=device,\n data_in=data_in,\n data_out=data_out,\n samples_perc_per_epoch=samples_perc_per_epoch\n )):\n\n ratings_in = batch.get_ratings_to_dev()\n ratings_out = batch.get_ratings(is_out=True)\n print(ratings_in.shape, ratings_out.shape)\n\n ratings_pred = model(\n ratings_in,\n calculate_loss=False).cpu().detach().numpy()\n\n start = i * batch_size\n end = (i * batch_size) + batch_size\n print(ratings_pred.shape)\n full_predicted[start:end] = ratings_pred\n full_expected[start:end] = ratings_out\n print(f\"prediction shape: {full_expected.shape}\")\n print(f\"nonzero predicted users: {len(set(full_predicted.nonzero()[0]))}\")\n print(f\"nonzero expected users: {len(set(full_expected.nonzero()[0]))}\")\n for m in metrics:\n m.calculate(full_expected.tocsr(), full_predicted.tocsr())\n\n return [x.value for x in metrics]\n\n\ndef run(model, opts, train_data, batch_size,\n n_epochs, beta, gamma, dropout_rate):\n model.train()\n for epoch in range(n_epochs):\n for batch in generate(batch_size=batch_size,\n device=device, data_in=train_data, shuffle=True):\n ratings = batch.get_ratings_to_dev()\n\n for optimizer in opts:\n optimizer.zero_grad()\n\n _, loss = model(ratings, beta=beta, gamma=gamma,\n dropout_rate=dropout_rate)\n loss.backward()\n\n for optimizer in opts:\n optimizer.step()\n\n\nmodel_kwargs = {\n 'hidden_dim': args.hidden_dim,\n 'latent_dim': args.latent_dim,\n 'input_dim': train_data.shape[1]\n}\nmetrics = [{'metric': ndcg, 'k': 100}]\n\nbest_ndcg = -np.inf\ntrain_scores, valid_scores = [], []\n\nmodel = VAE(**model_kwargs).to(device)\nmodel_best = VAE(**model_kwargs).to(device)\n\nlearning_kwargs = {\n 'model': model,\n 'train_data': train_data,\n 'batch_size': args.batch_size,\n 'beta': args.beta,\n 'gamma': args.gamma\n}\n\ndecoder_params = set(model.decoder.parameters())\nencoder_params = set(model.encoder.parameters())\n\noptimizer_encoder = optim.Adam(encoder_params, lr=args.lr)\noptimizer_decoder = optim.Adam(decoder_params, lr=args.lr)\n\n\nfor epoch in range(args.n_epochs):\n\n if args.not_alternating:\n run(opts=[optimizer_encoder, optimizer_decoder],\n n_epochs=1, dropout_rate=0.5, **learning_kwargs)\n else:\n run(opts=[optimizer_encoder],\n n_epochs=args.n_enc_epochs,\n dropout_rate=0.5,\n **learning_kwargs)\n model.update_prior()\n run(opts=[optimizer_decoder],\n n_epochs=args.n_dec_epochs,\n dropout_rate=0,\n **learning_kwargs)\n\n train_scores.append(\n evaluate(model, train_data, train_data, metrics, 0.01)[0]\n )\n valid_scores.append(\n evaluate(model, valid_in_data, valid_out_data, metrics, 1)[0]\n )\n\n if valid_scores[-1] > best_ndcg:\n best_ndcg = valid_scores[-1]\n model_best.load_state_dict(deepcopy(model.state_dict()))\n\n print(f'epoch {epoch} | valid ndcg@100: {valid_scores[-1]:.4f} | ' +\n f'best valid: {best_ndcg:.4f} | train ndcg@100: {train_scores[-1]:.4f}')\n\n\ntest_metrics = [NDCGK(100), RecallK(20), RecallK(50)]\n\nfinal_scores = evaluate_recpack(\n model_best,\n test_in_data,\n test_out_data,\n test_metrics)\n\nprint(\"Original results\")\nfor metric, score in zip(test_metrics, final_scores):\n print(f\"{metric.name}:\\t{score:.4f}\")\n\nprint(\"Recpack results\")\nfor metric in froomle_metrics:\n print(f\"{metric.name}: \\t {metric.value}\")\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":10140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"59700932","text":"import json\nimport os.path\n\n\n# changes values of headers already in the file, and appends lines with new headers to the end, or creates new file if dosn't already exist\ndef log_vars(log_dict, json_file_path):\n if os.path.isfile(json_file_path): \n json_data = read(json_file_path)\n else:\n json_data = {}\n\n for log_header, log_val in log_dict.items():\n json_data[log_header] = log_val\n\n write(json_data, json_file_path)\n \n \n \ndef write(data, output_file_path, indent = 4):\n with open(output_file_path, 'w') as outfile: \n json.dump(data, outfile, indent = indent)\n\n\ndef read(json_file_path):\n with open(json_file_path, \"r\") as read_file:\n data = json.load(read_file)\n return data\n \n \n \n# data = {} \n# data['people'] = [] \n# data['people'].append({ \n# 'name': 'Scott',\n# 'website': 'stackabuse.com',\n# 'from': 'Nebraska'\n# })\n# data['people'].append({ \n# 'name': 'Larry',\n# 'website': 'google.com',\n# 'from': 'Michigan'\n# })\n# data['people'].append({ \n# 'name': 'Tim',\n# 'website': [1,2,3,4],\n# 'from': 'Alabama'\n# })\n# \n# \n# write(data,'json_test.json')\n# print(read('json_test.json'))\n# print(read('project_vars.json'))\n\n\n# var_data = {'a': 5,\n# 'b': 6}\n# \n# #log_vars(var_data, 'test.json')\n# log_vars({'c': 11}, 'test.json')\n","sub_path":"json_logger.py","file_name":"json_logger.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"259769311","text":"import email.utils as email_utils\n\nfrom collected.dict.caseless import CaseLessDict\nfrom dated import utc\nfrom unicoder import byte_string\n\n\nclass HttpHeaders(CaseLessDict):\n\n def __init__(self, seq=None, encoding='utf-8'):\n self.encoding = encoding\n super(HttpHeaders, self).__init__(seq)\n\n def _normalize_key(self, key):\n return byte_string(key.title(), encoding=self.encoding)\n\n def _normalize_value(self, value):\n if hasattr(value, '__iter__'):\n value = [byte_string(x, encoding=self.encoding) for x in value]\n value = value[0] if len(value) == 1 else value\n else:\n value = byte_string(value)\n\n return value\n\n def __getitem__(self, key):\n try:\n value = super(HttpHeaders, self).__getitem__(key)\n return value if not isinstance(value, list) else value[-1]\n except IndexError:\n return None\n\n def get(self, key, default=None):\n try:\n return self[key]\n except KeyError:\n return default\n\n def get_list(self, key, def_val=None):\n try:\n return super(HttpHeaders, self).__getitem__(key)\n except KeyError:\n return self._normalize_value(def_val) if def_val is not None else None\n\n def append(self, key, value):\n value = self._normalize_value(value)\n existing = self.get(key)\n if existing:\n if not isinstance(existing, list):\n existing = [existing]\n if isinstance(value, list):\n existing.extend(value)\n else:\n existing.append(value)\n value = existing\n self[key] = value\n\n def to_string(self):\n return _headers_dict_to_raw(self)\n\n def __copy__(self):\n return self.__class__(self)\n\n copy = __copy__\n\n\ndef header_dict_to_lines(headers_dict):\n raw_lines = []\n\n for key, value in headers_dict.items():\n if isinstance(value, (str, unicode)):\n raw_lines.append('%s: %s' % (key, value))\n elif isinstance(value, (list, tuple)):\n for v in value:\n raw_lines.append('%s: %s' % (key, v))\n return raw_lines\n\n\ndef _headers_dict_to_raw(headers_dict):\n if headers_dict is None:\n return None\n\n raw_lines = header_dict_to_lines(headers_dict)\n\n return '\\r\\n'.join(raw_lines)\n\n\ndef header_string_to_dict(headers_raw):\n if headers_raw is None:\n return None\n\n header_split = (header.split(':', 1) for header in headers_raw.splitlines())\n header_items = (header_item for header_item in header_split if len(header_item) == 2)\n\n return HttpHeaders([(item[0].strip(), [item[1].strip()]) for item in header_items])\n\n\ndef date_header(headers):\n date_string = headers.get('date')\n if date_string:\n time_tuple = email_utils.parsedate(date_string)\n date = utc.from_time_tuple(time_tuple).to_datetime()\n return date","sub_path":"httpy/http/headers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"173533586","text":"from tensorflow import keras\nfrom tensorflow.python.keras.applications import mobilenet\nfrom tensorflow.python.keras._impl.keras.applications.mobilenet import DepthwiseConv2D, relu6\n\n\nIMAGE_SHAPE = (224, 224, 3)\n\n\ndef preprocess_input(input):\n return mobilenet.preprocess_input(input)\n\n\ndef liveness_model():\n input_layer = keras.layers.Input(shape=IMAGE_SHAPE)\n base_model = mobilenet.MobileNet(\n input_tensor=input_layer,\n input_shape=IMAGE_SHAPE,\n include_top=False,\n weights='imagenet',\n pooling='avg',\n )\n\n dense_layer = keras.layers.Dense(256, activation='elu')(base_model.output)\n output_layer = keras.layers.Dense(1, activation=None)(dense_layer)\n\n model = keras.models.Model(inputs=input_layer, outputs=output_layer)\n return model\n\n\ndef load_liveness_model(checkpoint_path):\n model = keras.models.load_model(str(checkpoint_path), custom_objects={\n 'relu6': relu6,\n 'DepthwiseConv2D': DepthwiseConv2D,\n })\n return model\n","sub_path":"src/liveness/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"212247376","text":"import numpy as np\nfrom matplotlib import pyplot\nfrom input_file_operations import *\nfrom linear_regression_operations import *\nfrom plot_operations import *\n\n\ndef main():\n # read the input file\n ip_array = read_input_file(\"ex1data1.txt\")\n\n # separate input file into training set input and output\n (ip_x_array, ip_y_array) = prepare_input_matrices(ip_array)\n (training_set_sample_count,training_set_feature_count) = ip_x_array.shape\n\n # perform feature normalization\n (norm_x_array, mean_x_array, range_x_array) = perform_feature_normalization(ip_x_array)\n\n # create the design array (X) and the model parameter array (theta)\n ip_design_array = create_design_array(norm_x_array)\n model_parameter_array = np.zeros((training_set_feature_count+1,1))\n\n # compute the model output and cost with initial guess for theta\n init_model_output_array = compute_model_output_array(ip_design_array, model_parameter_array)\n init_cost = compute_cost_function_square_mean_error(ip_design_array, model_parameter_array, ip_y_array)\n # print(\"initial theta: \\n\", model_parameter_array)\n # print(\"initial cost: \", init_cost)\n\n # compute the model parameters using gradient descent\n learning_rate = 0.01\n max_iter = 20000\n (model_parameter_array_gradient_descent,gradient_descent_cost_array,iter_count) = perform_gradient_descent(ip_design_array,model_parameter_array,ip_y_array,learning_rate,init_cost,max_iter)\n\n print(\"theta after gradient descent: \\n\", model_parameter_array_gradient_descent)\n print(\"cost: \", gradient_descent_cost_array[iter_count-1])\n print(\"iter count: \", iter_count)\n\n # compute the model parameters using the normal equation\n # the normal equation does not require feature normalization\n ip_design_array = create_design_array(ip_x_array)\n (model_parameter_array_normal_equation,normal_equation_cost) = perform_normal_equation(ip_design_array,ip_y_array)\n\n print(\"theta after normal equation: \\n\", model_parameter_array_normal_equation)\n print(\"cost: \", normal_equation_cost)\n\n # create some plots\n # plot the input data as a scatter plot\n plot_1d_scatterplot(ip_x_array[:, 0],ip_y_array[:, 0],\"input data\",\"population (x 10k)\",\"profit (x 10k)\",[4, 25, -5, 25],\"rx\",2)\n\n # plot scatter plot along with gradient descent fit\n x_vals = np.arange(0,25,0.1)\n (x_vals_count,) = x_vals.shape\n x_vals_array = np.ones((x_vals_count,2))\n x_vals_array[:,1] = x_vals\n\n x_vals_norm = (x_vals - mean_x_array[0,0])/range_x_array[0,0]\n x_vals_norm_array = np.ones((x_vals_count, 2))\n x_vals_norm_array[:, 1] = x_vals_norm\n\n y_vals_array = compute_model_output_array(x_vals_norm_array, model_parameter_array_gradient_descent)\n\n plot_1d_scatter_and_fit(ip_x_array[:, 0],ip_y_array[:, 0],x_vals_array[:,1], y_vals_array[:,0],\n \"input data and gradient descent fit\",\"population (x 10k)\",\"profit (x 10k)\",[4, 25, -5, 25],\n \"rx\",2,\"b-\",1,\"input\",\"gradient descent\")\n\n # plot scatter plot along with normal equation fit\n y_vals_array = compute_model_output_array(x_vals_array, model_parameter_array_normal_equation)\n\n plot_1d_scatter_and_fit(ip_x_array[:, 0], ip_y_array[:, 0], x_vals_array[:, 1], y_vals_array[:, 0],\n \"input data and normal equation fit\", \"population (x 10k)\", \"profit (x 10k)\",\n [4, 25, -5, 25],\n \"rx\", 2, \"b-\", 1, \"input\", \"normal equation\")\n\n # plot the variation of the cost function with each iteration\n plot_1d_scatterplot(range(0,max_iter), gradient_descent_cost_array[0:max_iter], \"Cost during gradient descent\", \"gradient descent iteration\", \"mean square error cost\",\n [0, 20000, 0, 35], \"r-\", 2)\n\n # plot the contour plot of the cost function varying with the model parameters\n theta_0_vals = np.arange(-10,10,0.01)\n theta_1_vals = np.arange(-1,4,0.01)\n\n # reallocate ip_design_array to correspond to feature normalized values\n #ip_design_array = create_design_array(norm_x_array)\n\n cost_function_array = np.zeros((theta_1_vals.size,theta_0_vals.size))\n\n for i in range(theta_0_vals.size):\n for j in range(theta_1_vals.size):\n curr_parameter_array = np.array([[theta_0_vals[i]], [theta_1_vals[j]]])\n curr_cost = compute_cost_function_square_mean_error(ip_design_array, curr_parameter_array, ip_y_array)\n cost_function_array[j, i] = curr_cost[0,0]\n\n plot_contour_plot(cost_function_array,theta_0_vals,theta_1_vals,\"Cost function\",\"theta_0\",\"theta_1\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tutorials/1_andrewng_machine_learning/week2/python_solutions/univariate_linear_regression_main.py","file_name":"univariate_linear_regression_main.py","file_ext":"py","file_size_in_byte":4659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"449113458","text":"# -----------------------------------------------------------------------------\n# Name: spartanquest - v2\n# Purpose: Illustrate advantages and limitations of various search algorithms\n#\n# Author: Rula Khayrallah\n#\n# Copyright © Rula Khayrallah, 2018\n# -----------------------------------------------------------------------------\n\"\"\"\nMain program to guide Sammy the Spartan on a quest within a given maze\n\nUsage: spartanquest.py maze_file search_algoritm\nThe maze_file is a text file such as SJSU.txt\nThe search_algorithm in homework 2 is:\n dfs: for depth first search\n bfs: for breadth first search\n ucs for uniform cost search\nThe search_algorithm in homework 3 is:\n astar: for A* search\n\nExample: spartanquest.py SJSU.txt dfs\n\nThe search algorithms functions are implemented in the file\nsearch_algo.py.\n\ndfs has been implemented for you.\nYour task for homework 2 is to implement bfs and ucs in uninformed_search.py\nYour task for homework 3 is to implement astar in informed_search.py\n\n\"\"\"\nimport time\nimport argparse\nimport uninformed_search\nimport informed_search\nimport graphics\n\nclass Maze(object):\n \"\"\"\n Represent the maze layout: its width, height and walls\n\n Arguments:\n width (int): the width of the maze\n height (int): the height of the maze\n\n Attributes:\n width (int): the width of the maze\n height (int): the height of the maze\n walls (two dimensional list of booleans):\n Each element represents a position in the maze.\n True indicates that there is a wall in that position.\n False indicates the absence of a wall.\n self.walls[r][c] indicates the presence or absence of a wall\n at row r and column c in the maze.\n\n \"\"\"\n def __init__(self, width, height):\n self.walls = [[False for col in range(width)]\n for row in range(height)]\n self.width = width\n self.height = height\n\n def add_wall(self, position):\n \"\"\"\n Add a wall in the specified position\n :param position: tuple (row, column) representing a maze position\n :return: None\n \"\"\"\n row, col = position\n self.walls[row][col] = True\n\n def is_wall(self, position):\n \"\"\"\n Is there a wall in the given position?\n :param position: tuple (row, column) representing a maze position\n :return:\n (Boolean) True if there is a wall in that position, False otherwise\n \"\"\"\n row, col = position\n return self.walls[row][col]\n\n def within_bounds(self, position):\n \"\"\"\n Is the given position within the maze?\n :param position: tuple (row, column) representing a position\n :return:\n (Boolean) True if the position is inside the maze, False otherwise\n \"\"\"\n row, col = position\n return row in range(self.height) and col in range(self.width)\n\n\nclass Problem(object):\n \"\"\"\n Represent our search problem at any point in the quest\n\n Arguments:\n mazefile (file): text file containing the maze info\n\n Attributes:\n maze (Maze object): the maze for this quest\n The maze is constant throughout the quest\n mascot_position (tuple of integers):\n The current position of Sammy in the maze\n medals (a set of tuples):\n A set containing the positions of the remaining medals in the quest\n \"\"\"\n NORTH = \"N\"\n SOUTH = \"S\"\n EAST = \"E\"\n WEST = \"W\"\n actions = (NORTH, SOUTH, EAST, WEST) # fixed the order of the actions\n moves = {NORTH: (-1, 0), SOUTH: (1, 0), EAST: (0, 1), WEST: (0, -1)}\n\n # The cost associated with each move. Moving backward is the most costly\n cost = {NORTH: 2, SOUTH: 2, EAST: 5, WEST: 1}\n #cost = {NORTH: 1, SOUTH: 1, EAST: 1, WEST: 1}\n def __init__(self, mazefile):\n self._nodes_expanded = 0 # private variable to keep track of the search\n self.medals = set()\n self.read_quest(mazefile)\n\n def read_quest(self, mazefile):\n \"\"\"\n Read the maze file specified and encode the information in the object\n The length of the first line in the file is used to determine the\n width of the maze. So the last position in the first row of the maze\n must be represented by a character in the first line (not a space).\n X or x: represent a wall\n M or m: represent the presence of a medal at that position\n S or s: represent the starting position of our Spartan mascot, Sammy\n Any other character: a vacant maze position\n\n :param\n mazefile (file): the text file containing the maze info\n :return: None\n \"\"\"\n layout = mazefile.readlines()\n width = len(layout[0].strip()) # the first line\n height = len(layout) # the number of lines represents the height\n self.maze = Maze(width, height)\n row = 0\n for line in layout:\n col = 0\n for char in line:\n if char in {'X', 'x'}: # X represents a wall\n self.maze.add_wall((row, col))\n elif char in {'M', 'm'}: # M represents a medal position\n self.add_medal((row, col))\n elif char in {'S', 's'}: # S represents Sammy's position\n self.add_mascot((row, col))\n col += 1 # anything else is a vacant maze position\n row += 1\n mazefile.close()\n\n\n def add_mascot(self, position):\n \"\"\"\n Save the mascot's position\n :param position: tuple (row, column) representing a maze position\n :return: None\n \"\"\"\n self.mascot_position = position\n\n def add_medal(self, position):\n \"\"\"\n Add the specified position to the set containing all the medals\n :param position: tuple (row, column) representing a maze position\n :return: None\n \"\"\"\n self.medals.add(position)\n\n def is_goal(self, state):\n \"\"\"\n Is the state specified a goal state?\n The state is a goal state when there are no medals left to collect.\n :param\n state - A state is represented by a tuple containing two other tuples:\n the current position (row, column) of Sammy the Spartan\n a tuple containing the positions of the remaining medals\n\n :return: Boolean - True if this is a goal state and False otherwise\n \"\"\"\n position, medals_left = state\n return not medals_left\n\n def start_state(self):\n \"\"\"\n Return the start state in this quest\n The start state is identified by the mascot's position and the initial\n distribution of the medals in the maze.\n represented by a tuple containing two other tuples:\n the current position (row, column) of Sammy teh Spartan\n a tuple containing all the positions of the remaining medals\n\n :return:\n state - The start state in the quest\n A state is represented by a tuple containing two other tuples:\n the current position (row, column) of Sammy the Spartan\n a tuple containing the positions of the remaining medals\n \"\"\"\n return self.mascot_position, tuple(self.medals)\n\n def successors(self, state):\n \"\"\"\n Return a list of tuples representing all states that are reachable\n from the current state with their corresponding action and costs\n :param\n state - A state is represented by a tuple containing two other tuples:\n the current position (row, column) of Sammy the Spartan\n a tuple containing the positions of the remaining medals\n :return:\n a list of tuples representing all states that are reachable\n from the current state with their corresponding action and cost\n \"\"\"\n result = []\n self._nodes_expanded += 1 # update private variable\n position, current_medals = state\n current_x, current_y = position\n for action in self.actions: \n new_position = (current_x + self.moves[action][0],\n current_y + self.moves[action][1])\n # if the move in that direction is valid\n if self.maze.within_bounds(new_position) and \\\n not self.maze.is_wall(new_position):\n new_medals = set(current_medals) - {new_position}\n new_state = (new_position, tuple(new_medals))\n result.append((new_state, action, self.cost[action]))\n return result\n\n\n def path_cost(self, actions):\n \"\"\"\n Return the total cost of a sequence of actions/moves\n :param\n actions (list) - A list of actions/moves\n :return (int): the total cost of these actions\n \"\"\"\n return sum(self.cost[action] for action in actions)\n\n def nodes_expanded(self):\n return self._nodes_expanded\n\n\ndef get_arguments():\n '''\n Parse and validate the command line arguments\n :return: (tuple containing a file object and a string)\n the maze file specified and the search algoeithm specified\n '''\n parser = argparse.ArgumentParser()\n parser.add_argument('maze_file',\n help='name of the text file containing the maze info',\n type=argparse.FileType('r')) # open the file\n parser.add_argument('search_algorithm',\n help='astar, dfs, bfs or ucs?',\n choices=['astar', 'dfs', 'bfs', 'ucs'])\n parser.add_argument('heuristic',\n help='A* heuristic',\n nargs='?',\n default='null_heuristic')\n arguments = parser.parse_args()\n\n maze_file = arguments.maze_file\n search = arguments.search_algorithm\n heuristic = arguments.heuristic\n return maze_file, search, heuristic\n\ndef main():\n maze_file, search, heuristic = get_arguments()\n quest = Problem(maze_file) # Initialize our search problem for this quest\n start_time = time.time()\n if search == \"astar\":\n heuristic_function = getattr(informed_search, heuristic)\n solution = informed_search.astar(quest, heuristic_function)\n else:\n search_function = getattr(uninformed_search, search)\n solution = search_function(quest) # Invoke the search algorithm\n elapsed_time = time.time() - start_time\n\n # Print some statistics\n if solution is not None:\n print('Path length: ', len(solution))\n print('Path cost: ', quest.path_cost(solution))\n else:\n print('The quest failed!')\n print('Number of nodes expanded: {:,}'.format(quest.nodes_expanded()))\n print('Processing time: {:.4f} (sec)'.format(elapsed_time))\n\n graphics.Display(quest, solution) # Visualize the solution\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"CS156HW3/spartanquest.py","file_name":"spartanquest.py","file_ext":"py","file_size_in_byte":10919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"304806436","text":"#!/usr/bin/env python\n\nfrom tkinter import *\nfrom tkinter.filedialog import askopenfilename\nfrom tkinter.messagebox import showerror\nfrom algorithm import *\nfrom useData import *\nfrom drawPlat import *\nimport sys\n\nclass MyFrame(Frame):\n def __init__(self):\n Frame.__init__(self)\n self.master.title(\"Analysis Practice\")\n self.master.rowconfigure(4, weight=1)\n self.master.columnconfigure(3, weight=1)\n self.master.resizable(0,0)\n self.grid(sticky=W+E+N+S)\n self.trainData=StringVar()\n self.trainData.set(\"\")\n\n self.label= Label(self,text=\"Training data: \",width=15)\n self.label.grid(row=1,column=0,sticky=W)\n self.label1= Entry(self,textvariable=self.trainData,width=20)\n self.label1.grid(row=1,column=1)\n self.button = Button(self, text=\"Browse\", command=self.load_file, width=10)\n self.button.grid(row=1, column=2, sticky=E)\n self.label2=Label(self,text=\"Initial vector:\\n(example: 0 1)\",width=15)\n self.label2.grid(row=2,column=0,sticky=W)\n self.vector= Entry(self,width=20)\n self.vector.grid(row=2,column=1,sticky=W)\n self.learning=Label(self,text=\"Learning rate:\\n(between 0 ~ 1.0)\",width=15)\n self.learning.grid(row=3,column=0,sticky=W)\n self.learningrate=Entry(self,width=20)\n self.learningrate.grid(row=3,column=1,sticky=W)\n self.button2 = Button(self, text=\"Run\", command=self.runAnaly, width=10)\n self.button2.grid(row=2, column=2, sticky=E)\n self.button3 = Button(self,text=\"Reset\",command=self.reset,width=10)\n self.button3.grid(row=3, column=2,sticky=E)\n\n def load_file(self):\n fname = askopenfilename(title=\"Choose Data\",filetypes=((\"Text data\",\"*.txt\"),(\"All files\", \"*.*\") ))\n if fname:\n try:\n self.trainData.set(fname)\n except:\n self.trainData.set(\"\")\n return\n self.update()\n\n def runAnaly(self):\n suc = False\n testData=open(self.trainData.get(),'r',encoding='utf-8')\n if testData is not None:\n trainList,group=transDataToList(testData)\n testData.close()\n # trainList, examList=cutList(testList)\n while not suc:\n vector = [float(x) for x in self.vector.get().split()]\n tdata=list(trainList)\n # print(tdata)\n gr,trainList=divide2Group(trainList)\n line = normalAlgo(trainList,vector,float(self.learningrate.get().strip()))\n # print(line)\n if line==-1:\n showerror(title=\"Warning\",message=\"We couldn't find the vector.\\nYou should choose another initial vector.\")\n break\n else:\n suc = True\n draw(trainList,group,line, len(trainList[0])-1)\n \n\n def reset(self):\n self.trainData.set(\"\")\n self.vector.delete(first=0,last=END)\n self.learningrate.delete(first=0,last=END)\n self.update()\n\nif __name__ == \"__main__\":\n MyFrame().mainloop()","sub_path":"project1/analyWin.py","file_name":"analyWin.py","file_ext":"py","file_size_in_byte":3059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"76397049","text":"l = input().split(\",\")\r\nfor i in l:\r\n k =i.split(':')\r\n word = k[0]\r\n num = k[1]\r\n digit_sum=0\r\n for j in num:\r\n digit_sum+=(int(j)**2)\r\n if digit_sum%2==0:\r\n word= word[-2::]+word[0:len(word)-2]\r\n else:\r\n word = word[1::]+word[0]\r\n print(word,end=\" \")\r\n\r\n","sub_path":"shifting_character.py","file_name":"shifting_character.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"354924876","text":"\nclass Node:\n def __init__(self, r):\n self.right = None\n self.left = None\n self.val = r\n\n def __str__(self):\n return str(self.val)\n\n\ndef insert(root, node):\n if root is None:\n root = node\n else:\n if root.val < node.val:\n if root.right is None:\n root.right = node\n else:\n insert(root.right, node)\n else:\n if root.left is None:\n root.left = node\n else:\n insert(root.left, node)\n\ndef search(root, x):\n if root:\n if root.val == x:\n return True\n if x > root.val:\n return search(root.right,x)\n elif x < root.val:\n return search(root.left,x)\n return False\n\ndef breadthfirst(root):\n if root:\n q = []\n\n q.append(root)\n\n while(len(q) > 0):\n print(q[0].val)\n node = q.pop(0)\n\n if node.left is not None:\n q.append(node.left)\n\n if node.right is not None:\n q.append(node.right)\n \n\n\ndef inorder(root):\n if root:\n inorder(root.left)\n print(root)\n inorder(root.right)\n\n\n\n\n\nroot = Node(25)\ninsert(root, Node(22))\ninsert(root, Node(21))\ninsert(root, Node(29))\n\nbreadthfirst(root)","sub_path":"search/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"74224873","text":"import time\nimport random\n\n\nclass SearchBoardPage:\n def __init__(\n self,\n main_keyword,\n include_keyword,\n exclude_keyword,\n search_cafe_base_url,\n chrome_driver\n ):\n\n self.main_keyword = main_keyword\n self.include_keyword = include_keyword\n self.exclude_keyword = exclude_keyword\n self.search_cafe_base_url = search_cafe_base_url\n self.chrome_driver = chrome_driver\n\n def search_main_keyword_page(self):\n self._connect_naver_cafe()\n self._search_main_keyword()\n self._switch_frame()\n self._expand_search_result_count()\n\n return self.chrome_driver\n\n def _switch_frame(self):\n self.chrome_driver.switch_to.frame('cafe_main')\n time.sleep(random.randint(5, 10))\n\n def _connect_naver_cafe(self):\n self.chrome_driver.get(self.search_cafe_base_url)\n time.sleep(random.randint(4, 9))\n\n def _search_main_keyword(self):\n self.chrome_driver.find_element_by_name('query').send_keys(self.main_keyword)\n time.sleep(5)\n\n # button click\n try:\n self.chrome_driver.find_element_by_xpath(\n '//*[@id=\"info-search\"]/form/button'\n ).click()\n time.sleep(random.randint(4, 9))\n except:\n try:\n self.chrome_driver.find_element_by_xpath(\n '//*[@id=\"cafe-search\"]/form/button'\n ).click()\n time.sleep(random.randint(4, 9))\n except Exception as e:\n raise print('unknown cafe')\n\n def _expand_search_result_count(self):\n # 50개씩으로 전환\n current_url = self.chrome_driver.find_element_by_xpath(\n '//*[@id=\"listSizeSelectDiv\"]/ul/li[7]/a'\n ).get_attribute('href')\n time.sleep(random.randint(4, 9))\n\n self.chrome_driver.get(current_url)\n time.sleep(random.randint(7, 12))\n\n def search_specific_keyword(self):\n self._switch_frame()\n self._click_the_specific_search()\n self._search_specific_keyword()\n\n return self.chrome_driver\n\n def _click_the_specific_search(self):\n # 상세 검색 클릭\n self.chrome_driver.find_element_by_xpath(\n '//*[@id=\"detailSearchBtn\"]'\n ).click()\n time.sleep(random.randint(4, 9))\n\n def _search_specific_keyword(self):\n # 다음 단어 중 1개 이상 포함\n self.chrome_driver.find_element_by_xpath(\n '//*[@id=\"srch_detail\"]/div[3]/input'\n ).send_keys(self.include_keyword)\n time.sleep(random.randint(4, 9))\n\n # 다음 단어 제외\n self.chrome_driver.find_element_by_xpath(\n '//*[@id=\"srch_detail\"]/div[2]/input'\n ).send_keys(self.exclude_keyword)\n time.sleep(random.randint(8, 13))\n\n # 검색 다시 하기\n self.chrome_driver.find_element_by_xpath(\n '//*[@id=\"main-area\"]/div[1]/div[1]/form/div[4]/button'\n ).click()\n time.sleep(random.randint(8, 13))\n","sub_path":"naver_cafe_board_scraping/scraping_search_board_page.py","file_name":"scraping_search_board_page.py","file_ext":"py","file_size_in_byte":3075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"88568111","text":"# 4. Написать функцию, которая вычислит площадь и объем конуса по его радиусу и высоте.\n# Функция должна вернуть два значения.\n\nimport math\nr = float(input('Enter radius\\n'))\nh = float(input('Enter height\\n'))\n\ndef cone_square_and_volume(radius, height):\n V = math.pi * radius**2 * height / 3\n S = math.pi * radius * (radius + height)\n return V, S\n\nvolume, square = cone_square_and_volume(r, h)\n\nprint('The volume is', volume, 'and square is', square)","sub_path":"HW7/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"508400587","text":"#Desafio28\r\nimport random\r\nfrom time import sleep\r\n\r\nn = random.randint(0,5)\r\nop = int(input('\\nDigite um numero entre 0 e 5: '))\r\nprint('\\nLoading...')\r\nsleep(3) #espera 3 segundos para mostrar a linha abaixo\r\nprint('\\nPC = {} Você = {}'.format(n, op))\r\n\r\nif n == op:\r\n print('\\nParabens! Você acertou o número')\r\nelse:\r\n print('\\nQue pena, você errou!')\r\n \r\n","sub_path":"Desafio028.py","file_name":"Desafio028.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"503334812","text":"#!/usr/bin/env python3.5\n# Copyright (c) 2016 Apple, Inc. All rights reserved.\n\"\"\"\ncheck the class.data class.weight.bigG class.weight.smallG files for possible errors\n\"\"\"\n\nimport argparse\nimport gzip\nimport logging\nimport os\nimport re\nimport sys\n\nsys.path.append(os.path.dirname(__file__))\nimport python3_utils\n\ndef check_class_files(classdata, smallG, bigG, onbfg=False):\n \"\"\" check the class files \"\"\"\n seenError = set()\n myError, clusterNames = check_class_data_file(classdata, onbfg=onbfg )\n seenError.add(myError)\n seenError.add(check_class_weight_file(smallG, clusterNames=clusterNames))\n seenError.add(check_class_weight_file(bigG, clusterNames=clusterNames))\n thisError = max(seenError)\n if thisError:\n logging.error(\"Finished checking all %s. returning with status %s\" %(classdata, thisError))\n else:\n logging.info(\"Finished checking all %s. returning with status %s\" %(classdata, thisError))\n return thisError\n\n\ndef check_class_data_file(infn, onbfg=False ):\n \"\"\" check the class.data file\n see https://wiki.siri.apple.com/display/~hong_chen/Building+classLM+with+LM+automation\n format is clustername hadoop-list cutoff power scale tokenization\n (0) line must contain 6 tab-separated fields\n (1) cluster name must not be duplicated\n (2) hadoop-list must exist if running on bfg\n (3) check 3rd field is an integer\n (4) check 4th field is an integer\n (5) check 5th field is an integer\n (6) tokenization must be \"tokenized\" or \"on\"\n (7) no missing trailing carriage return\n \"\"\"\n\n logging.info(\"checking %s\" %(infn))\n seenError=0\n\n clusterNames = set()\n\n with open(infn, encoding='utf-8') as infp:\n for line in infp:\n # (7) no missing trailing carriage return\n if not line.endswith(\"\\n\"):\n do_error(\"Missing carriage return on line %s in %s\" %(line, infn))\n seenError = 1\n line = line.strip()\n # (0) line must contain 6 tab-separated fields\n try:\n (clustername, hdfslist, cutoff, power, scale, tokenization) = line.split('\\t')\n except:\n do_error(\"cannot split line %s into 6 by tab in %s\" %(line, infn))\n seenError=1\n continue\n # (1) cluster name must not be duplicated\n if clustername in clusterNames:\n do_error(\"clustername %s appears more than once in %s\" %(clustername, infn))\n seenError=1\n clusterNames.add(clustername)\n # (2) if --onbfg check 2nd field exists on hdfs\n if onbfg and not python3_utils.hdfs_file_exists(hdfslist):\n do_error(\"%s in %s doesnt exist\" %(hdfslist, infn))\n seenError=1\n # (3) check 3rd field is an integer\n if not python3_utils.is_int_str(cutoff):\n do_error(\"cutoff :%s: is not an int on line %s in %s\" %(cutoff, line, infn))\n seenError=1\n # (4) check 4th field is an integer\n if not python3_utils.is_int_str(power):\n do_error(\"power :%s: is not an int on line %s in %s\" %(power, line, infn))\n seenError=1\n # (5) check 5th field is an integer\n if not python3_utils.is_int_str(scale):\n do_error(\"scale :%s: is not an int on line %s in %s\" %(scale, line, infn))\n seenError=1\n # (6) tokenization must be \"tokenized\" or \"on\"\n if tokenization not in [\"tokenized\", \"on\" ]:\n do_error(\"tokenization :%s: is not tokenized or on, line %s in %s\" %(tokenization, line, infn))\n seenError=1\n logging.info(\"checked %s returning with status %s\" %(infn, seenError))\n return(seenError, clusterNames)\n\ndef check_class_weight_file(infn, clusterNames=[]):\n \"\"\" check the class.weight.*G file to make sure\n (1) line contains an =\n (2) RHS numbers sum to 1\n (3) RHS cluster names match clusters in the class.data file\n (4) no missing trailing carriage return\n \"\"\"\n logging.info(\"checking %s\" %(infn))\n seenError=0\n\n with open(infn, encoding='utf-8') as infp:\n for line in infp:\n # (4) no missing trailing carriage return\n if not line.endswith(\"\\n\"):\n do_error(\"Missing carriage return on line %s in %s\" %(line, infn))\n seenError = 1\n line = line.strip()\n # (1) line contains an =\n try:\n (cluster, makeup) = line.split(\"=\")\n except:\n do_error(\"cannot split line %s into 2 by = in %s\" %(line, infn))\n seenError=1\n continue\n makeup = makeup.replace(\" \",\"\")\n # (2) RHS numbers sum to 1\n sources = makeup.split(\"|\")\n numbersum = 0.0\n unweighted = False\n for source in sources:\n try:\n (clust,weight) = source.split(\",\")\n numbersum += float(weight)\n except:\n unweighted = True\n clust = source\n # (3) RHS cluster names match clusters in the class.data file\n if clust not in clusterNames:\n do_error(\"cluster %s not in class.data file, line %s file %s\" %(clust, line, infn))\n seenError=1\n if unweighted:\n if numbersum != 0.0: # some have weights others don't\n do_error(\"mix of weights and no weights in line %s in %s\" %(line, infn))\n seenError=1\n else:\n if numbersum != 1.0:\n do_error(\"weights do not sum to 1.0 in line %s in %s\" %(line, infn))\n seenError=1\n\n logging.info(\"checked %s returning with status %s\" %(infn, seenError))\n return seenError\n\n#---------------------------------------------------------\n# input arg parsing\ndef main():\n\n parser = argparse.ArgumentParser(\n description=\n\"\"\"\nCheck the class.data, class.weight.smallG and class.weight.bigG files for syntax issues\n\"\"\",\n epilog=\n\"\"\"\nexamples:\n\n # set $SMA to your speech-model-automation github checkout\n\n # check the en_US TH class files when on the bfg and report all errors\n e.g. checkClassFiles.py --onbfg --noraise --data $SMA/config/TH/eng-USA/class.data --smallG $SMA/config/TH/eng-USA/class.weight.smallG --bigG $SMA/config/TH/eng-USA/class.weight.bigG\n\n # check when not on the bfg and die on first error\n e.g. checkClassFiles.py --data $SMA/config/TH/eng-USA/class.data --smallG $SMA/config/TH/eng-USA/class.weight.smallG --bigG $SMA/config/TH/eng-USA/class.weight.bigG\n\n checks the following:\n class.data:\n ( format clustername hadoop-list cutoff power scale tokenization )\n (0) contains 6 tab-separated fields\n (1) cluster name must not be duplicated\n (2) if --onbfg check 2nd field exists on hdfs\n (3) check 3rd field is an integer\n (4) check 4th field is an integer\n (5) check 5th field is an integer\n (6) check 6th field is \"on\" or \"tokenized\"\n (7) no missing trailing carriage return\n\n class.weight*:\n (1) line contains an =\n (2) RHS numbers sum to 1\n (3) RHS cluster names match clusters in the class.data file\n (4) no missing trailing carriage return\n\"\"\",\n formatter_class=lambda prog: argparse.RawDescriptionHelpFormatter(prog))\n\n parser.add_argument(\"--onbfg\", action='store_true', default=False,\n help=\"Run checks for file existance on the bfg\")\n parser.add_argument(\"--noraise\", action='store_true', default=False,\n help=\"Don't exit on first error\")\n parser.add_argument(\"--debug\", action='store_true', default=False,\n help=\"Log debug output\")\n parser.add_argument(\"--data\", type=str, required=True,\n help=\"class.data file\")\n parser.add_argument(\"--smallG\", type=str, required=True,\n help=\"class.weight.smallG file\")\n parser.add_argument(\"--bigG\", type=str, required=True,\n help=\"class.weight.bigG file\")\n\n # get command line\n args = parser.parse_args()\n python3_utils.init_logger()\n if args.debug:\n logging.getLogger().setLevel(logging.DEBUG)\n\n # check input files exist\n python3_utils.check_path(args.data)\n python3_utils.check_path(args.smallG)\n python3_utils.check_path(args.bigG)\n\n global do_error\n if args.noraise:\n do_error = python3_utils.do_error_noraise\n else:\n do_error = python3_utils.do_error_raise\n python3_utils.do_error = do_error\n\n status = check_class_files( classdata=args.data, smallG=args.smallG, bigG=args.bigG, onbfg=args.onbfg )\n\n return status\n\nif __name__ == \"__main__\" :\n status = main()\n sys.exit(status)\n\n","sub_path":"resource/tools/admin/checkClassFiles.py","file_name":"checkClassFiles.py","file_ext":"py","file_size_in_byte":9020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"526678044","text":"from openerp.osv import fields, osv\nfrom openerp import api\nfrom openerp.tools.translate import _\nfrom datetime import date, time\n\nclass add_bill(osv.osv):\n _name = \"add.bill\"\n\n\n def button_add_action(self,cr,uid,ids,context=None):\n\n admission_line=self.pool.get('leih.admission.line')\n admission_id=context.get(\"leih_admission_id\")\n add_test_object=self.browse(cr,uid,ids,context=None)\n test_name=add_test_object.name.id\n test_price=add_test_object.price\n test_discount=add_test_object.discount\n test_amount=add_test_object.total_amount\n\n\n vals_dict = {'discount': test_discount, 'price': test_price, 'leih_admission_id': admission_id, 'name': test_name, 'total_amount': test_amount}\n # import pdb\n # pdb.set_trace()\n admission_id_confirm=admission_line.create(cr,uid,vals=vals_dict,context=None)\n #querying all details of paid,due,total\n\n query = \"select total,grand_total,paid,after_discount,other_discount,due from leih_admission where id=%s\"\n cr.execute(query, ([admission_id]))\n all_data = cr.dictfetchall()\n after_discount=0.00\n for item in all_data:\n total=item.get('total')\n grand_total = item.get('grand_total')\n paid_amount = item.get('paid')\n due_amount = item.get('due')\n after_discount = item.get('after_discount') if item.get('after_discount') else 0.00\n other_discount = item.get('other_discount') if item.get('other_discount') else 0.00\n\n\n # import pdb\n # pdb.set_trace()\n total=total+test_amount\n grand_total = total-(after_discount+other_discount)\n due_amount =grand_total-paid_amount\n cr.execute('update leih_admission set total=%s,grand_total=%s,due=%s where id=%s',\n (total, grand_total, due_amount, admission_id))\n cr.commit()\n # import pdb\n # pdb.set_trace()\n\n\n\n\n\n return admission_id_confirm\n #\n\n\n _columns = {\n\n 'name': fields.many2one(\"examination.entry\", \"Test Name\", required=True, ondelete='cascade'),\n # 'bill_register_id': fields.many2one('bill.register', \"Information\"),\n # 'currency_id': fields.related('pricelist_id', 'currency_id', type=\"many2one\", relation=\"res.currency\",\n # string=\"Currency\", readonly=True, required=True),\n # 'price_subtotal': fields.function(_amount_line, string='Subtotal', digits_compute=dp.get_precision('Account')),\n 'price': fields.integer(\"Price\"),\n 'discount': fields.integer(\"Discount(%)\"),\n 'total_amount': fields.integer(\"Total Amount\")\n\n }\n\n\n def onchange_test(self,cr,uid,ids,name,context=None):\n tests = {'values': {}}\n dep_object = self.pool.get('examination.entry').browse(cr, uid, name, context=None)\n abc = {'price': dep_object.rate,'total_amount':dep_object.rate}\n tests['value'] = abc\n # import pdb\n # pdb.set_trace()\n return tests\n\n @api.onchange('discount')\n def onchange_disocunt(self):\n if self.discount!=0:\n self.total_dis=(self.price*self.discount)/100\n self.total_amount=self.price-self.total_dis\n else:\n self.total_amount=self.price\n return 'X'\n","sub_path":"bill_register/add_bill.py","file_name":"add_bill.py","file_ext":"py","file_size_in_byte":3320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"27410086","text":"'''\n27/11/2020 Asier Blazquez\n\n5- Celsius Farenheitera pasatzen du\n'''\n\nprint('Programa honek Celsius gradutatik \\n Farenheit-era pasatzen du\\n')\ncelsius = float(input(\"Sartu Celsius: \"))\n\nfar =0.0\n\nif (celsius==0):\n far=32.0\n print(celsius, \" ºC \", far, \"F dira \");\nelse:\n far = celsius * 33.80;\n print(celsius, \" ºC \", far, \"F dira \");\n\n","sub_path":"HasierakoAriketak/Ariketa5.py","file_name":"Ariketa5.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"488243123","text":"# python3 test.py [v]\n\nimport sys\nif len(sys.argv) == 2:\n v = sys.argv[1]\nelse:\n v = '1'\n\nname = 'friend-circles'\nfrom importlib.machinery import SourceFileLoader\nmodule = SourceFileLoader('', name + '.' + v + '.py').load_module()\n\ndef test(s, input, exp):\n print('----------')\n M = input\n print('M:', M)\n print('expect:', exp)\n res = s.findCircleNum(M)\n print('result:', res)\n if exp != res:\n print('--- ERROR ---')\n print()\n\ns = module.Solution()\n\n# -----\ninput = [ [1, 1, 0], [1, 1, 0], [0, 0, 1] ]\nexp = 2\ntest(s, input, exp)\n","sub_path":"juice/leet/0547/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"332550111","text":"from sklearn.mixture import GMM\nimport matplotlib \nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import ImageGrid\nfrom Coordinates import *\nimport numpy as np\n\nclass Pair:\n\n\tdef __init__(self, si, sf, gms):\n\n\t\tself.angm = None\n\t\tmag, angc, angm = vectorToPolar( si, sf, self.angm )\n\t\n\t\tgmm = GMM( n_components = gms, covariance_type = 'full' )\n\n\t\tgmm.fit( np.hstack( (mag, angc) ) )\n\t\tself.gmm = gmm\n\t\tself.angm = angm\n\t\tself.mag = mag\n\t\tself.angc = angc\n\n\tdef calcPotential(self, si, sf):\n\n\t\txf, xi = np.meshgrid(sf.x , si.x )\n\t\tyf, yi = np.meshgrid(sf.y, si.y )\n\n\t\tdx = (xf - xi).reshape((si.num*sf.num),1)\n\t\tdy = (yf - yi).reshape((si.num*sf.num),1)\n\n\t\tpot = self.evalDelta( dx, dy )\n\n\t\tself.potential = pot.reshape( (si.num, sf.num ) )\n\n\tdef calcMeshPotentials(self, xi, xf, yi, yf, steps):\n\n\t\tx = np.linspace(xi, xf, steps).reshape((steps,1))\n\t\ty = np.linspace(yi, yf, steps).reshape((steps,1))\n\n\t\tX,Y = mesh( x, y )\n\t\tpot = self.evalDelta( X, Y )\n\n\t\treturn pot.reshape( (steps, steps ) )\n\t\n\tdef messageOut(self, mess = None):\n\t\treturn Message( self.si, self.sf, self.potential, mess )\n\t\n\tdef messageIn(self, mess = None):\n\t\treturn Message( self.sf, self.si, self.potential.T, mess )\n\t\n\tdef evalDelta( self, dx, dy ):\n\n\t\tmag, angc, angm = deltaToPolar( dx, dy, self.angm )\n\t\treturn self.gmm.eval( np.hstack( (mag, angc) ) )[0]\n\n\tdef evalSingle( self, initial, final ):\n\n\t\tmag, angc, angm = vectorToPolar( initial, final, self.angm )\n\t\treturn self.gmm.eval( np.hstack( (mag, angc) ) )[0]\n\n\ndef PlotGMMXY( pair, num = 250 ):\n\n\tmatplotlib.rc('xtick', labelsize=14) \n\tmatplotlib.rc('ytick', labelsize=14) \n\t\n\tdx = np.linspace( -50, 50, num )\n\tdy = np.linspace( -50, 50, num )\n\n\tDx,Dy = np.meshgrid( dx, dy)\n\n\tDx = Dx.reshape( (num*num, 1) )\n\tDy = Dy.reshape( (num*num, 1) )\n\n\tM,A, angm = deltaToPolar( Dx, Dy, pair.angm )\n\n\tz = pair.gmm.eval( np.hstack( (M, A) ) )[0].reshape((num,num))\n\n\tfig = plt.figure()\n\n\tax = fig.add_subplot(111)\n\n\tax.set_xlabel('X dist', fontsize=18)\n\tax.set_ylabel('Y dist', fontsize=18)\n\n\tplt.contour(dx,dy,z)\n\t#plt.plot(pair.mag,pair.angc, '.' )\n\t\n\tplt.show()\n\n\treturn fig\n\n\ndef PlotGMM( pair, num = 250 ):\n\n\tmatplotlib.rc('xtick', labelsize=14) \n\tmatplotlib.rc('ytick', labelsize=14) \n\n\tmagmin = pair.mag.min()\n\tmagmax = pair.mag.max()\n\n\tm = np.linspace( magmin, magmax, num)\n\ta = np.linspace( 0, 2*np.pi, num)\n\n\tM,A = mesh( m, a)\n\n\tA = A.reshape((num*num,1))\n\n\tz = pair.gmm.eval( np.hstack( (M, A) ) )[0].reshape((num,num)).T\n\n\tfig = plt.figure()\n\n\tax = fig.add_subplot(111)\n\n\tax.set_xlabel('Distance in pixels', fontsize=18)\n\tax.set_ylabel('Angle in radians', fontsize=18)\n\n\tplt.contour(m,a,z)\n\tplt.plot(pair.mag,pair.angc, '.' )\n\t\n\tplt.show()\n\n\treturn fig\n","sub_path":"ver1/Pair.py","file_name":"Pair.py","file_ext":"py","file_size_in_byte":2703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"12283922","text":"def make_shirt(shirt_size, shirt_text):\n \"\"\"Display info about a t-shirt.\"\"\"\n print(f\"\\nThe shirt size is {shirt_size.title()}.\")\n print(f\"\\nThe {shirt_size.title()} shirt should read, {shirt_text}.\")\n\nmake_shirt('l', 'Just Do It')\nmake_shirt(shirt_size='m', shirt_text='3 stripe life')\n\n# write a func called make_shirt that accepts a size and the text of a message that should be printed on the shirt. \n# the func should print a sentence summarizing the size of the shirt and the message printed on it.\n# use pos arg and keyword args.\n","sub_path":"section-8/t-shirt1.py","file_name":"t-shirt1.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"305410211","text":"#########################################################################\n\n# COVID-19 Machine Learning Prediction Program\n# Matt Taylor\n# 03/29/2020\n# MJT65@ProtonMail.com\n\n########################################################################\n\n\n#Import Required Modules\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nimport seaborn as sns\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error\n\n# Import CSV file from John Hopkins\nCOVID_CONFIRMED_URL = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv'\ncovid_confirmed = pd.read_csv(COVID_CONFIRMED_URL)\n\n# Print HEAD of CSV Import File\n# print(covid_confirmed.head())\n\ncovid_confirmed_long = pd.melt(covid_confirmed,\n id_vars=covid_confirmed.iloc[:, :4],\n var_name='date',\n value_name='confirmed')\n\ncovid_confirmed_long['Country/Region'].replace('Mainland China', 'China', inplace=True)\ncovid_confirmed_long[['Province/State']] = covid_confirmed_long[['Province/State']].fillna('')\ncovid_confirmed_long.fillna(0, inplace=True)\ncovid_confirmed_long.isna().sum().sum()\ncovid_countries_date_df = covid_confirmed_long.groupby(['Country/Region', 'date'], sort=False).sum().reset_index()\ncovid_countries_date_df.drop(['Lat', 'Long'], axis=1, inplace=True)\n\n# Filter out by Country\nCOUNTRY = 'US'\ncovid_country = covid_countries_date_df[covid_countries_date_df['Country/Region'] == COUNTRY]\ndays = np.array([i for i in range(len(covid_country['date']))])\n\n# Skip Days the First 30 Days After January 22/2020\nSKIP_DAYS = 30\ncovid_country_confirmed_sm = list(covid_country['confirmed'][SKIP_DAYS:])\ncovid_country_confirmed_sm[:15]\nX = days[SKIP_DAYS:].reshape(-1, 1)\ny = list(np.log(covid_country_confirmed_sm))\n\n#Train The Data\nX_train, X_test, y_train, y_test = train_test_split(X, y,\n test_size=0.1,\n shuffle=False)\n\nlinear_model = LinearRegression(fit_intercept=True)\nlinear_model.fit(X_train, y_train)\n\ny_pred = linear_model.predict(X_test)\n\n# Print Mean Absolute & Mean Standard Error Rate\nprint('MAE:', mean_absolute_error(y_pred, y_test))\nprint('MSE:',mean_squared_error(y_pred, y_test))\n\na = linear_model.coef_\nb = linear_model.intercept_\nX_fore = list(np.arange(len(days), len(days) + 14))\ny_fore = [(a*x+b)[0] for x in X_fore]\n\ny_train_l = list(np.exp(y_train))\ny_test_l = list(np.exp(y_test))\ny_pred_l = list(np.exp(y_pred))\ny_fore_l = list(np.exp(y_fore))\n\n#Linear Scale with Predictions\nfig, ax = plt.subplots(figsize=(16, 6))\n\nsns.lineplot(x=days, y=covid_country['confirmed'],\n markeredgecolor=\"#2980b9\", markerfacecolor=\"#2980b9\", markersize=8, marker=\"o\",\n sort=False, linewidth=1, color=\"#2980b9\")\n\nsns.lineplot(x=X_train.reshape(-1), y=y_train_l,\n markeredgecolor=\"#051118\", markerfacecolor=\"#051118\", markersize=8, marker=\"o\",\n sort=False, linewidth=1, color=\"#3498db\")\n\nsns.lineplot(x=X_test.reshape(-1), y=y_test_l,\n markeredgecolor=\"#e67e22\", markerfacecolor=\"#e67e22\", markersize=8, marker=\"o\",\n sort=False, linewidth=1, color=\"#e67e22\")\n\nsns.lineplot(x=X_test.reshape(-1), y=y_pred_l,\n markeredgecolor=\"#f1c40f\", markerfacecolor=\"#f1c40f\", markersize=8, marker=\"o\",\n sort=False, linewidth=1, color=\"#f1c40f\")\n\nsns.lineplot(x=X_fore, y=y_fore_l,\n markeredgecolor=\"#2ecc71\", markerfacecolor=\"#2ecc71\", markersize=8, marker=\"o\",\n sort=False, linewidth=1, color=\"#2ecc71\")\n\nplt.suptitle(f\"COVID-19 confirmed cases and forecasting in {COUNTRY} over the time\", fontsize=16, fontweight='bold', color='white')\n\nplt.ylabel('Confirmed cases')\nplt.xlabel('Days since 1/22')\n\nplt.legend(['Unused train data', 'Train data', 'Test data', 'Predictions', 'Forecast'])\nplt.savefig('reg.svg', format='svg', dpi=1200)\nplt.show()\n\n","sub_path":"log_predic.py","file_name":"log_predic.py","file_ext":"py","file_size_in_byte":4089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"297514251","text":"import requests\nfrom bs4 import BeautifulSoup\n#import urllib2\nimport re\n# coding: utf-8\n\n\ndef get_medic(medic):\n r = requests.post(\"http://base-donnees-publique.medicaments.gouv.fr/index.php\", data={'choixRecherche': 'medicament', 'txtCaracteres': medic, 'action': 'show'})\n soup = BeautifulSoup(r.text, \"lxml\")\n names_medic = soup.findAll('td',{'class':'ResultRowDeno'})\n liste_medoc=[]\n for name in names_medic:\n liste_medoc.append(name.text)\n return liste_medoc\n\nibus = get_medic('IBUPROFENE')\n#print get_medic('IBUPROFENE')\n\nibuprofene=[]\nfor ibu in ibus:\n temp = (re.findall(r'(.*)\\s(\\d{1,4})\\s(mg?)(?:\\/\\d+ mg?)?\\s?(.*),\\s(\\S*)\\s(\\S*)', ibu))\n ibuprofene.append(temp)\n\n\nfor i in range(len(ibuprofene)):\n if ibuprofene[i]!=[]:\n print (ibuprofene[i][0][0]+ibuprofene[i][0][1]+' '+ibuprofene[i][0][2]+' '+ibuprofene[i][0][3])","sub_path":"sidoine-kakeuhfosso/lesson5/exo_cc_lesson5_ibuprofene.py","file_name":"exo_cc_lesson5_ibuprofene.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"585754402","text":"from database.models import Team, UserProfile, Media, Community, TeamMember, CommunityAdminGroup\nfrom _main_.utils.massenergize_errors import MassEnergizeAPIError, InvalidResourceError, ServerError, CustomMassenergizeError, NotAuthorizedError\nfrom _main_.utils.massenergize_response import MassenergizeResponse\nfrom django.utils.text import slugify\nfrom _main_.utils.context import Context\nfrom _main_.utils.constants import COMMUNITY_URL_ROOT, ADMIN_URL_ROOT\nfrom .utils import get_community_or_die, get_user_or_die, get_admin_communities\nfrom database.models import Team, UserProfile\nfrom sentry_sdk import capture_message\nfrom _main_.utils.emailer.send_email import send_massenergize_email\n\ndef can_set_parent(parent, this_team=None):\n if parent.parent:\n return False\n if this_team and Team.objects.filter(parent=this_team, is_deleted=False).exists():\n return False\n return True\n\ndef get_team_users(team):\n team_users = [tm.user for tm in\n TeamMember.objects.filter(team=team, is_deleted=False).select_related('user')]\n if team.parent:\n return team_users\n else:\n child_teams = Team.objects.filter(parent=team, is_deleted=False, is_published=True)\n child_team_users = [tm.user for tm in\n TeamMember.objects.filter(team__in=child_teams, is_deleted=False).select_related('user')]\n return set().union(team_users, child_team_users)\n\nclass TeamStore:\n def __init__(self):\n self.name = \"Team Store/DB\"\n\n def get_team_info(self, context: Context, team_id) -> (dict, MassEnergizeAPIError):\n try:\n team = Team.objects.filter(id=team_id).first()\n if not team:\n return None, InvalidResourceError()\n\n userOnTeam = False \n if context.user_id: # None for anonymous usage\n user = UserProfile.objects.get(id=context.user_id)\n userOnTeam = TeamMember.objects.filter(team=team, user=user).exists()\n \n #TODO: untested\n if not team.is_published and not (context.user_is_admin() or userOnTeam):\n return None, CustomMassenergizeError(\"Cannot access team until it is approved\")\n return team, None\n except Exception as e:\n capture_message(str(e), level=\"error\")\n return None, CustomMassenergizeError(e)\n\n\n def get_team_admins(self, context, team_id):\n try:\n if not team_id:\n return None, CustomMassenergizeError(\"provide_team_id\")\n team_admins = TeamMember.objects.filter(is_admin=True, team__id=team_id, is_deleted=False)\n team_admins = [a.user for a in team_admins if a.user]\n return team_admins, None\n except Exception as e:\n capture_message(str(e), level=\"error\")\n return None, CustomMassenergizeError(e)\n\n \n def list_teams(self, context: Context, args) -> (list, MassEnergizeAPIError):\n try:\n community = get_community_or_die(context, args)\n user = get_user_or_die(context, args)\n\n if community:\n teams = Team.objects.filter(community=community, is_published=True, is_deleted=False)\n elif user:\n teams = user.team_set.all()\n return teams, None\n except Exception as e:\n capture_message(str(e), level=\"error\")\n return None, CustomMassenergizeError(e)\n\n\n def team_stats(self, context: Context, args) -> (list, MassEnergizeAPIError):\n try:\n community = get_community_or_die(context, args)\n teams = Team.objects.filter(community=community, is_deleted=False)\n\n # show unpublished teams only in sandbox.\n # TODO: Better solution would be to show also for the user who created the team, but more complicated\n if not context.is_sandbox:\n teams = teams.filter(is_published=True)\n\n ans = []\n for team in teams:\n res = {\"members\": 0, \"households\": 0, \"actions\": 0, \"actions_completed\": 0, \"actions_todo\": 0, \"carbon_footprint_reduction\": 0}\n res[\"team\"] = team.simple_json()\n \n users = get_team_users(team)\n res[\"members\"] = len(users)\n for user in users:\n res[\"households\"] += user.real_estate_units.count()\n actions = user.useractionrel_set.all()\n res[\"actions\"] += len(actions)\n done_actions = actions.filter(status=\"DONE\").prefetch_related('action__calculator_action')\n res[\"actions_completed\"] += done_actions.count()\n res[\"actions_todo\"] += actions.filter(status=\"TODO\").count()\n for done_action in done_actions:\n if done_action.action and done_action.action.calculator_action:\n res[\"carbon_footprint_reduction\"] += done_action.action.calculator_action.average_points\n\n ans.append(res)\n\n return ans, None\n except Exception as e:\n capture_message(str(e), level=\"error\")\n return None, CustomMassenergizeError(e)\n\n\n def create_team(self, context:Context, args) -> (dict, MassEnergizeAPIError):\n team = None\n try:\n # generally a Team will have one community, but in principle it could span multiple. If it \n community_id = args.pop('community_id', None)\n community_ids = args.pop('community_ids', None) # in case of a team spanning multiple communities\n logo_file = args.pop('logo', None)\n image_files = args.pop('pictures', None)\n video = args.pop('video', None)\n parent_id = args.pop('parent_id', None)\n args.pop('undefined', None)\n\n admin_emails = args.pop('admin_emails', [])\n \n verified_admins = []\n #verify that provided emails are valid user\n for email in admin_emails:\n admin = UserProfile.objects.filter(email=email).first()\n if admin:\n verified_admins.append(admin)\n else:\n return None, CustomMassenergizeError(f\"Email: {email} is not registered with us\")\n \n if not verified_admins:\n return None, CustomMassenergizeError(f\"Please provide at least one admin's email\")\n\n if community_id:\n community = Community.objects.filter(pk=community_id).first()\n if not community:\n return None, CustomMassenergizeError(\"Please provide a valid community\")\n args[\"community\"] = community\n community_list = None\n elif community_ids: # the case of multiple communities\n community_list = []\n for community_id in community_ids:\n community = Community.objects.filter(pk=community_id).first()\n if not community:\n return None, CustomMassenergizeError(\"Please provide a valid community in the list\")\n community_list.append(community)\n else:\n return None, CustomMassenergizeError(\"Please provide a community\")\n \n team, _ = Team.objects.get_or_create(**args)\n\n # add multiple communities if that is the case (generally not)\n if community_list:\n for community in community_list:\n team.community.add(community)\n\n # for the case of a sub-team, record the parent\n if parent_id:\n parent = Team.objects.filter(pk=parent_id).first()\n if parent and can_set_parent(parent):\n team.parent = parent\n else:\n return None, CustomMassenergizeError(\"Cannot set parent team\")\n\n if logo_file:\n logo = Media.objects.create(file=logo_file, name=f\"{slugify(team.name)}-TeamLogo\")\n logo.save()\n team.logo = logo\n\n # TODO: this code does will not make sense when there are multiple communities for the team...\n # TODO: create a rich email template for this?\n \n # Wnen team initially created, it is not visible until reviewed by community admin\n is_published = False\n team.is_published = is_published\n if not is_published:\n cadmins = CommunityAdminGroup.objects.filter(community__id=community_id).first().members.all()\n message = \"A team has requested creation in your community. Visit the link below to view their information and if it is satisfactory, check the approval box and update the team.\\n\\n%s\" % (\"%s/admin/edit/%i/team\" %\n (ADMIN_URL_ROOT, team.id))\n\n for cadmin in cadmins:\n send_massenergize_email(subject=\"New team awaiting approval\",\n msg=message, to=cadmin.email)\n team.save()\n for admin in verified_admins:\n teamMember, _ = TeamMember.objects.get_or_create(team=team,user=admin)\n teamMember.is_admin = True\n teamMember.save()\n\n return team, None\n except Exception as e:\n capture_message(str(e), level=\"error\")\n if team:\n team.delete()\n return None, CustomMassenergizeError(str(e))\n\n\n def update_team(self, context, team_id, args) -> (dict, MassEnergizeAPIError):\n try:\n community_id = args.pop('community_id', None)\n if community_id:\n community = Community.objects.filter(pk=community_id).first()\n subdomain = community.subdomain\n else:\n subdomain = \"your_community\"\n\n logo = args.pop('logo', None)\n parent_id = args.pop('parent_id', None)\n is_published = args.pop('is_published', False)\n \n team = Team.objects.filter(id=team_id)\n\n # to update Team, need to be super_admin, community_admin of that community, or a team_admin\n allowed = False\n if context.user_is_super_admin:\n allowed = True\n elif context.user_is_community_admin:\n community = team.first().community\n admin_communities, err = get_admin_communities(context)\n if community in admin_communities:\n allowed = True\n else:\n # user has to be on the team admin list\n teamMembers = TeamMember.objects.filter(team=team.first())\n for teamMember in teamMembers:\n if teamMember.user.id == user_id and teamMember.is_admin:\n allowed = True\n break\n\n if not allowed:\n return None, NotAuthorizedError()\n\n team.update(**args)\n team = team.first()\n\n # TODO: create a rich email template for this?\n # TODO: only allow a cadmin or super admin to change this particular field?\n if is_published and not team.is_published:\n team.is_published = True\n team_admins = TeamMember.objects.filter(team=team, is_admin=True).select_related('user')\n # fix the broken URL in this message, needs to have community nam\n message = \"Your team %s has now been approved by a Community Admin and is viewable to anyone on the MassEnergize portal. See it here:\\n\\n%s\" % (team.name, (\"%s/%s/teams/%i\") % (COMMUNITY_URL_ROOT, subdomain, team.id))\n for team_admin in team_admins:\n send_massenergize_email(subject=\"Your team has been approved\",\n msg=message, to=team_admin.user.email)\n else:\n # this is how teams can get be made not live\n team.is_published = is_published\n\n if community_id:\n community = Community.objects.filter(pk=community_id).first()\n if community:\n team.community = community \n\n if parent_id:\n team.parent = None\n parent = Team.objects.filter(pk=parent_id).first()\n if parent and can_set_parent(parent, this_team=team):\n team.parent = parent\n \n if logo:\n # if existing logo, the string length is around 300 characters\n # If a new logo updated, this will be the length of the file, much larger than that \n new_logo = len(logo) > 1000\n if new_logo:\n logo = Media.objects.create(file=logo, name=f\"{slugify(team.name)}-TeamLogo\")\n logo.save()\n team.logo = logo\n else: \n team.logo = None \n\n team.save()\n return team, None\n except Exception as e:\n capture_message(str(e), level=\"error\")\n return None, CustomMassenergizeError(e)\n \n\n def delete_team(self, team_id) -> (dict, MassEnergizeAPIError):\n try:\n teams = Team.objects.filter(id=team_id)\n if not teams:\n return None, InvalidResourceError()\n\n\n # team.members deprecated. Delete TeamMembers separate step\n team = teams.first()\n members = TeamMember.objects.filter(team=team)\n msg = \"delete_team: Team %s deleting %d members\" % (team.name,members.count())\n members.delete()\n teams.delete() # or should that be team.delete()?\n\n return teams.first(), None\n except Exception as e:\n capture_message(str(e), level=\"error\")\n return None, CustomMassenergizeError(e)\n\n\n def join_team(self, team_id, user_id) -> (Team, MassEnergizeAPIError):\n try:\n team = Team.objects.get(id=team_id)\n user = UserProfile.objects.get(id=user_id)\n teamMember = TeamMember.objects.create(team=team, user=user)\n teamMember.save()\n #team.members.add(user_id)\n #team.save()\n return team, None\n except Exception as e:\n capture_message(str(e), level=\"error\")\n return None, CustomMassenergizeError(str(e))\n\n def leave_team(self, team_id, user_id) -> (Team, MassEnergizeAPIError):\n try:\n team = Team.objects.get(id=team_id)\n user = UserProfile.objects.get(id=user_id)\n teamMembers = TeamMember.objects.filter(team=team, user=user)\n teamMembers.delete()\n\n return team, None\n except Exception as e:\n capture_message(str(e), level=\"error\")\n return None, CustomMassenergizeError(str(e))\n\n def add_team_member(self, context: Context, args) -> (Team, MassEnergizeAPIError):\n try:\n team_id = args.pop('team_id', None)\n user = get_user_or_die(context, args)\n status = args.pop('is_admin', None) == 'true'\n\n if not team_id :\n return None, CustomMassenergizeError(\"Missing team_id\")\n\n team_member: TeamMember = TeamMember.objects.filter(team__id=team_id, user=user).first()\n if team_member:\n team_member.is_admin = status\n team_member.save()\n else:\n team = Team.objects.filter(pk=team_id).first()\n if not team_id and not user:\n return None, CustomMassenergizeError(\"Invalid team or user\")\n team_member = TeamMember.objects.create(is_admin=status, team=team, user=user)\n\n return team_member, None\n except Exception as e:\n capture_message(str(e), level=\"error\")\n return None, CustomMassenergizeError(e)\n\n def remove_team_member(self, context: Context, args) -> (Team, MassEnergizeAPIError):\n try:\n team_id = args.pop('team_id', None)\n user = get_user_or_die(context, args)\n res = {}\n if team_id and user:\n team_member = TeamMember.objects.filter(team__id=team_id, user=user)\n res = team_member.delete()\n return res, None\n except Exception as e:\n capture_message(str(e), level=\"error\")\n return None, CustomMassenergizeError(e)\n\n\n def members(self, context: Context, args) -> (Team, MassEnergizeAPIError):\n try:\n if not context.user_is_admin():\n return None, NotAuthorizedError()\n team_id = args.get('team_id', None)\n if not team_id:\n return [], CustomMassenergizeError('Please provide a valid team_id')\n\n members = TeamMember.objects.filter(is_deleted=False, team__id=team_id)\n return members, None\n except Exception:\n return None, InvalidResourceError()\n\n\n def members_preferred_names(self, context: Context, args) -> (Team, MassEnergizeAPIError):\n try:\n team_id = args.get('team_id', None)\n if not team_id:\n return [], CustomMassenergizeError('Please provide a valid team_id')\n\n team = Team.objects.filter(id=team_id).first()\n users = get_team_users(team)\n res = []\n for user in users:\n member = TeamMember.objects.filter(user=user, team=team).first()\n member_obj = {\"id\": None, \"user_id\": user.id, \"preferred_name\": user.preferred_name, \"is_admin\": False}\n if member:\n member_obj['id'] = member.id\n member_obj['is_admin'] = member.is_admin\n res.append(member_obj)\n\n return res, None\n except Exception as e:\n capture_message(str(e), level=\"error\")\n return None, InvalidResourceError()\n\n\n def list_teams_for_community_admin(self, context: Context, args) -> (list, MassEnergizeAPIError):\n try:\n if context.user_is_super_admin:\n return self.list_teams_for_super_admin(context)\n\n elif not context.user_is_community_admin:\n return None, NotAuthorizedError()\n\n community_id = args.pop('community_id', None)\n if not community_id or community_id=='undefined':\n user = UserProfile.objects.get(pk=context.user_id)\n admin_groups = user.communityadmingroup_set.all()\n comm_ids = [ag.community.id for ag in admin_groups]\n teams = Team.objects.filter(community__id__in = comm_ids, is_deleted=False).select_related('logo', 'community')\n return teams, None\n\n teams = Team.objects.filter(community__id = community_id, is_deleted=False).select_related('logo', 'community')\n return teams, None\n\n except Exception as e:\n capture_message(str(e), level=\"error\")\n return None, CustomMassenergizeError(e)\n\n def list_teams_for_super_admin(self, context: Context):\n try:\n if not context.user_is_super_admin:\n return None, NotAuthorizedError()\n teams = Team.objects.filter(is_deleted=False).select_related('logo', 'community')\n return teams, None\n\n except Exception as e:\n capture_message(str(e), level=\"error\")\n return None, CustomMassenergizeError(str(e))\n","sub_path":"src/api/store/team.py","file_name":"team.py","file_ext":"py","file_size_in_byte":17338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"543009845","text":"\"\"\"\nDefinition of urls for DjangoWebProject.\n\"\"\"\n\nfrom django.conf.urls import patterns, url\n\n# Uncomment the next lines to enable the admin:\n# from django.conf.urls import include\n# from django.contrib import admin\n# admin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n url(r'^$', 'app.views.home', name='home'),\n url(r'service', 'app.views.service', name='service')\n\n )\n","sub_path":"DjangoWebProject/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"124662908","text":"def collatz(n):\n \"\"\"Returns Hailstone number for n.\n Expects n to be a positive integer.\"\"\"\n i = 0\n while n != 1:\n if n % 2 == 0:\n n = n // 2\n else:\n n = 3 * n + 1\n i = i + 1\n return i\n","sub_path":"collatz.py","file_name":"collatz.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"420086788","text":"from django.urls import path, re_path\n\nfrom assets.views import upload_file, request_asset_dump\n\nurlpatterns = []\n\n# These are supposed to be URLs that look like\n# https://assets.wprdc.org/edit/update-assets/\n# and that handle bulk database edits.\nurlpatterns = [\n path('update-assets//', upload_file, name='update-assets'),\n re_path(r'^dump_assets/', request_asset_dump, name='request_asset_dump'),\n]\n","sub_path":"assets/urls_edit.py","file_name":"urls_edit.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"102926194","text":"\"\"\"\nJakub Karbowski\n\nDefiniujemy stan robota krotką (x, y, rotation, speed).\nNiech to będą wierzchołki w grafie.\nDla każdego stanu dodajemy możliwe przejścia do innych stanów.\nDijkstrą liczymy odległości od stanu początkowego.\n\n\nZłożoność:\nGeneracja grafu: O(w * h) # width, height planszy\nDijkstra na adj list: O(ElogV); ile to E a ile V?\nV = ilość stanów = w * h * N_ROTS * N_SPEEDS\nE <= V^2 na pewno.\nAle jest lepiej.\nZ każdego stanu możemy przejść do najwyżej 3 innych (forward, left, right).\nCzyli krawędzi będzie najwyżej 3V.\n\nFinalna złożoność: O(w*h*log(w*h))\n\n\nPamięć:\nPrzechowujemy różne rzeczy dla każdego stanu, więc mamy O(w*h)\n\"\"\"\n\n\nfrom zad2testy import runtests\nfrom math import inf, isinf\nfrom queue import PriorityQueue\n\n\nN_SPEEDS = 3\nTOP_SPEED = 2\nN_ROTS = 4\n\n\ndef accelerate(s):\n return min(TOP_SPEED, s + 1)\n\n\nROT_COST = 45\n\nMOVE_COST = [ # MOVE_COST[s] = ...\n 60,\n 40,\n 30\n]\n\n\ndef robot(L, A, B):\n h = len(L) # height\n w = len(L[0]) # width\n\n \"\"\"\n stan robota to:\n x\n y\n r - rotation (0, 1, 2, 3)\n s - speed (0, 1, 2)\n \"\"\"\n\n \"\"\"\n plansza ma X w prawo, Y w dół\n \"\"\"\n\n # adj list\n G = [[[[[] for s in range(N_SPEEDS)] for r in range(N_ROTS)] for y in range(h)] for x in range(w)]\n\n # generujemy możliwe ruchy\n for x in range(w):\n for y in range(h):\n # tych pętli nie wliczamy do złożoniści bo mają stałą długość\n for r in range(N_ROTS):\n for s in range(N_SPEEDS):\n # prawo\n if r == 0:\n # wykrywanie kolizji\n if x + 1 < w and L[y][x + 1] != 'X':\n # do przodu rozpędzając się\n G[x][y][r][s].append(((x + 1, y, r, accelerate(s)), MOVE_COST[s]))\n # | x | y |r| s | time |\n\n # zakręty\n G[x][y][r][s].append(((x, y, 1, 0), ROT_COST))\n G[x][y][r][s].append(((x, y, 3, 0), ROT_COST))\n\n # góra\n if r == 1:\n if 0 <= y - 1 and L[y - 1][x] != 'X':\n G[x][y][r][s].append(((x, y - 1, r, accelerate(s)), MOVE_COST[s]))\n G[x][y][r][s].append(((x, y, 0, 0), ROT_COST))\n G[x][y][r][s].append(((x, y, 2, 0), ROT_COST))\n\n # lewo\n if r == 2:\n if 0 <= x - 1 and L[y][x - 1] != 'X':\n G[x][y][r][s].append(((x - 1, y, r, accelerate(s)), MOVE_COST[s]))\n G[x][y][r][s].append(((x, y, 1, 0), ROT_COST))\n G[x][y][r][s].append(((x, y, 3, 0), ROT_COST))\n\n # dół\n if r == 3:\n if y + 1 < h and L[y + 1][x] != 'X':\n G[x][y][r][s].append(((x, y + 1, r, accelerate(s)), MOVE_COST[s]))\n G[x][y][r][s].append(((x, y, 2, 0), ROT_COST))\n G[x][y][r][s].append(((x, y, 0, 0), ROT_COST))\n\n # dijkstra\n\n # odległość każdego stanu\n d = [[[[inf for s in range(N_SPEEDS)] for r in range(N_ROTS)] for y in range(h)] for x in range(w)]\n visited = [[[[False for s in range(N_SPEEDS)] for r in range(N_ROTS)] for y in range(h)] for x in range(w)]\n Q = PriorityQueue()\n\n d[A[0]][A[1]][0][0] = 0\n Q.put((0, (A[0], A[1], 0, 0)))\n\n while not Q.empty():\n _, state = Q.get()\n x, y, r, s = state\n\n if visited[x][y][r][s]:\n continue\n visited[x][y][r][s] = True\n\n for (new_state, cost) in G[x][y][r][s]:\n nx, ny, nr, ns = new_state\n if d[x][y][r][s] + cost < d[nx][ny][nr][ns]:\n d[nx][ny][nr][ns] = d[x][y][r][s] + cost\n Q.put((d[nx][ny][nr][ns], (nx, ny, nr, ns)))\n\n best_cost = inf\n for r in range(N_ROTS):\n for s in range(N_SPEEDS):\n best_cost = min(best_cost, d[B[0]][B[1]][r][s])\n\n return None if isinf(best_cost) else best_cost\n\n\nruntests(robot)\n","sub_path":"exam/1/zad2.py","file_name":"zad2.py","file_ext":"py","file_size_in_byte":4208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"305313309","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# ########### ########### ########## ##########\n# ############ ############ ############ ############\n# ## ## ## ## ## ## ##\n# ## ## ## ## ## ## ##\n# ########### #### ###### ## ## ## ## ######\n# ########### #### # ## ## ## ## # #\n# ## ## ###### ## ## ## ## # #\n# ## ## # ## ## ## ## # #\n# ############ ##### ###### ## ## ## ##### ######\n# ########### ########### ## ## ## ##########\n#\n# S E C U R E M O B I L E N E T W O R K I N G\n#\n# Author: Daniel Steinmetzer\n# E-Mail: dsteinmetzer@seemoo.tu-darmstadt.de\n# Website: https:://www.seemoo.de/dsteinmetzer\n# Date: 2018-03-20\n# Last Modified: 2018-10-31\n\nimport argparse\nimport configparser\nimport inspect\nimport logging\nimport pkg_resources\nimport Pyro4\nimport sys\nimport os\nimport signal\nimport time\n\nfrom daemonize import Daemonize\nfrom pluginbase import PluginBase\nfrom tabulate import tabulate\n\nfrom .tpynode import TPyNode\nimport tpynode.modules\n\n# -----------------------------------------------------------------------------\n# --- Settings ----------------------------------------------------------------\n# -----------------------------------------------------------------------------\n\nsys.excepthook = Pyro4.util.excepthook\ncfgfile_default = '/etc/tpynode.conf'\n\n# -----------------------------------------------------------------------------\n# --- Logger Settings ---------------------------------------------------------\n# -----------------------------------------------------------------------------\n\nlog_format = '%(asctime)s %(levelname)-5s %(message)s'\nlog_level = logging.INFO\n\nformatter = logging.Formatter(log_format)\nlogging.basicConfig(level=log_level,\n format=log_format)\nlogger = logging.getLogger(__name__)\nlogger.setLevel(log_level)\n\n\n# -----------------------------------------------------------------------------\n# --- Functions ---------------------------------------------------------------\n# -----------------------------------------------------------------------------\n\ndef load_external_modules(module_path, base_type=object):\n\n if not module_path:\n logger.info('Skipping loading external modules')\n return list()\n\n logger.info('Loading external modules from %s' % (module_path))\n pluginbase = PluginBase(package='modules_ext')\n plugin_source = pluginbase.make_plugin_source(searchpath=[module_path],\n persist=True,\n identifier='tpymodules')\n modules = list()\n\n # Find the Plugins\n for plugin_module in plugin_source.list_plugins():\n\n # Try to load the plugin\n try:\n plugin = plugin_source.load_plugin(plugin_module)\n plugin_classes = inspect.getmembers(plugin, inspect.isclass)\n\n # Check the classes in the plugin\n for plugin_class in plugin_classes:\n\n # Only scan local classes\n if plugin_class[1].__module__ == plugin.__name__:\n\n # Check base type\n if issubclass(plugin_class[1], base_type):\n\n module_name = plugin_class[0]\n module = plugin_class[1]\n module_file = os.path.basename(plugin.__file__) \n logger.info('Importing external module %s from %s' % (module_name, module_file))\n module.__file__ = plugin.__file__\n module.__plugin__ = True\n\n # Add this module\n modules.append(module)\n except Exception as e:\n logger.error('Unable to load external modules from %s, import failed' % plugin_module)\n # ToDo: Real parsing here\n logger.exception(e)\n return modules\n\n\ndef load_internal_modules(base_type=object):\n\n # Find internal modules\n modules = list()\n int_modules = inspect.getmembers(tpynode.modules, inspect.isclass)\n for module_class in int_modules:\n module = module_class[1]\n if issubclass(module, base_type):\n logger.info('Using internal module %s' % module.__name__)\n module.__plugin__ = False\n modules.append(module)\n return modules\n\n\ndef load_modules(ext_module_path, base_type=object):\n modules = load_internal_modules(base_type)\n modules.extend(load_external_modules(ext_module_path, base_type))\n return modules\n\n\ndef get_module_by_name(modules, name):\n for module in modules:\n if module.__name__ == name:\n return module\n return None\n\n\n# -----------------------------------------------------------------------------\n# --- Daemon ------------------------------------------------------------------\n# -----------------------------------------------------------------------------\n\ndef run_tpynode(config, modules):\n\n tpy_config = config['TPyNode']\n host = tpy_config.get('host', 'localhost')\n port = int(tpy_config.get('port', '42337'))\n token = tpy_config.get('token', None) # Not used yet\n\n setattr(Pyro4.config, 'HOST', host)\n\n # Start the Pyro Daemon\n pyro = Pyro4.Daemon(port=port)\n tpynode = TPyNode(pyro=pyro)\n uri = pyro.register(tpynode, 'tpynode')\n if not uri:\n raise Exception('Unable to register TPyHost in daemon service.')\n logger.info('Registered TPyHost instance at %s' % uri)\n\n # Register modules ...\n modulecfg = [{**dict(config.items(k)), **{'name': k}}\n for k in config.keys() if k != 'TPyNode' and\n k != 'DEFAULT']\n for mcfg in modulecfg:\n if mcfg.get('module') is None:\n mcfg['module'] = mcfg['name']\n logger.info('Exposing module %s as %s' % (mcfg['module'],\n mcfg['name']))\n module = get_module_by_name(modules, mcfg['module'])(**mcfg)\n uri = pyro.register(module, mcfg['name'])\n if not uri:\n raise Exception('Unable to register module %s in daemon service.' % mcfg['name'])\n logger.info('Registered %s Module instance at %s' % (mcfg['module'], uri))\n tpynode.register_module(mcfg['module'], mcfg['name'])\n\n logger.info('Awaiting incoming Connections ...')\n pyro.requestLoop()\n\n\n# -----------------------------------------------------------------------------\n# --- MAIN --------------------------------------------------------------------\n# -----------------------------------------------------------------------------\n\ndef main():\n\n # Initialize argument parser\n parser = argparse.ArgumentParser(description='TPyNode Daemon')\n parser.add_argument('--version', action='version', help='show version',\n version=pkg_resources.require(\"tpynode\")[0].version)\n\n parser.add_argument('cmd', action='store', help='operation mode',\n nargs='?', choices=['start', 'stop', 'restart', 'run',\n 'modules', 'info'],\n default='run')\n\n parser.add_argument(\n \"-c\", \"--conf\", dest='cfgfile', default=cfgfile_default,\n type=str, help='configuration file')\n\n # Parse Command Line Arguments\n args = parser.parse_args(sys.argv[1:])\n\n # Load the configuration file\n config = configparser.ConfigParser()\n logger.info('Loading configuration from %s' % args.cfgfile)\n if not config.read(args.cfgfile) or 'TPyNode' not in config.sections():\n logger.error('Unable to parse configuration, please check file')\n sys.exit(1)\n\n ext_module_path = config['TPyNode'].get('module_path')\n modules = load_modules(ext_module_path)\n\n def run():\n logger.info('Running TPyNode')\n run_tpynode(config, modules)\n\n def start():\n logger.info('Starting TPyNode in Daemon Mode')\n\n pidfile = config['TPyNode'].get('pidfile')\n\n def runner():\n run_tpynode(config, modules)\n\n daemon = Daemonize(app=\"tpynode\", pid=pidfile, action=runner)\n daemon.start()\n\n def stop():\n logger.info('Stopping TPyNode Daemon')\n try:\n pidfile = config['TPyNode'].get('pidfile')\n with open(pidfile) as pid:\n os.kill(int(pid.read()), signal.SIGTERM)\n time.sleep(1) # make sure that pid file is released\n except FileNotFoundError:\n logger.info('No running instance found')\n\n def restart():\n stop()\n start()\n\n def list_modules():\n # list all modules\n module_info = list()\n for m in modules:\n module_name = m.__name__\n module_desc = m.__doc__\n module_desc = ' '.join([str.strip() for str in module_desc.splitlines()]) if module_desc else ''\n module_base = m.__base__.__name__\n module_file = os.path.basename(m.__file__) if m.__plugin__ else 'builtin'\n\n module_info.append({\n 'Name': module_name,\n 'Base': module_base,\n 'Definition': module_file,\n 'Description': module_desc})\n\n print('Available Modules:')\n print(tabulate(module_info, headers='keys'))\n\n def info():\n logger.error('Not yet implemented')\n\n cmd_map = {\n 'run': run,\n 'start': start,\n 'stop': stop,\n 'restart': restart,\n 'modules': list_modules,\n 'info': info,\n }\n\n cmd_map[args.cmd]()\n sys.exit(0)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"node/tpynode/daemon.py","file_name":"daemon.py","file_ext":"py","file_size_in_byte":9763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"566451852","text":"from pyspark import SparkContext\nfrom pyspark.streaming import StreamingContext\nimport spark_streaming\n\n#Need to setup spark instance to run test\ndef test_streaming_mean():\n input_rdds = [(\"a1-b1\", 5), (\"a1-b1\", 3), (\"a1-b1\", 4)]\n\n sc = SparkContext(appName=\"arithmetic_mean_consumer\")\n sc.setLogLevel(\"WARN\")\n ssc = StreamingContext(sc, 10)\n ssc.checkpoint(\"./\")\n input_stream = ssc.queueStream(input_rdds)\n\n mapCount = input_stream.mapValues(lambda v: (v, 1))\n reduceKey = mapCount.reduceByKey(lambda x, y: (x[0] + y[0], x[1] + y[1]))\n dataCheckpoint = reduceKey.updateStateByKey(spark_streaming.updateArithmicMean)\n results = dataCheckpoint.mapValues(lambda v: v[0] / v[1])\n\n expected_results = [\n (\"a1-b1\", 4)\n ]\n\n assert results == expected_results","sub_path":"consumer_data/unit_test.py","file_name":"unit_test.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"290688674","text":"#!/usr/bin/python3\nimport time\nimport datetime\nimport tkinter as tk\nimport tkinter.ttk as ttk\n\n\n\nclass TodoElement:\n def __init__(self, description = \"\", expiration_date = datetime.datetime.now(datetime.timezone.utc)):\n self.description = description\n self.checked = False\n self.expiration_date = expiration_date\n\n\n\nclass TodoList:\n def __init__(self):\n self.elements = []\n\n def add(self, element):\n self.elements.append(element)\n\n def sort(self, attr):\n self.elements.sort(attrgetter(attr))\n\n\n\nclass TextBox(object):\n def __init__(self, master):\n self.frame = tk.Frame(master)\n self.frame.grid_propagate(False)\n self.frame.grid_rowconfigure(0, weight = 1)\n self.frame.grid_columnconfigure(0, weight = 1)\n\n self.view = ttk.Treeview(columns=['Description', '', ''], show=\"headings\")\n self.view.grid(row = 0, column = 0, sticky = \"nsew\")\n\n self.xscroll = tk.Scrollbar(self.frame, orient = tk.HORIZONTAL, command = self.view.xview)\n self.xscroll.grid(row = 1, column = 0, sticky = \"nsew\")\n\n self.yscroll = tk.Scrollbar(self.frame, orient = tk.VERTICAL, command = self.view.yview)\n self.yscroll.grid(row = 0, column = 1, sticky = \"nsew\")\n\n self.view.config(xscrollcommand = self.xscroll.set)\n self.view.config(yscrollcommand = self.yscroll.set)\n\n\n\nclass App:\n def __init__(self):\n self.root = tk.Tk()\n self.root.title(\"Todo\")\n self.root.geometry(\"768x480\")\n\n self.root.grid_rowconfigure(0, weight = 1)\n self.root.grid_rowconfigure(1, weight = 0)\n self.root.grid_columnconfigure(0, weight = 0)\n self.root.grid_columnconfigure(1, weight = 1)\n\n self.textbox = TextBox(self.root)\n self.textbox.frame.grid(row = 0, column = 0, sticky = \"nsew\", padx = 0, pady = 0, columnspan = 3)\n\n self.password_label = tk.Label(self.root, text = \"Password: \", justify = tk.CENTER)\n self.password_label.grid(row = 1, column = 0, sticky = \"nsw\", padx = 8, pady = 8)\n\n self.keybox = tk.Entry(self.root, width = 32, show = '*', bd = 2)\n self.keybox.grid(row = 1, column = 1, sticky = \"nsw\", padx = 8, pady = 8)\n\n\n def run(self):\n self.root.mainloop()\n\n\n\nif __name__ == \"__main__\":\n App().run()\n","sub_path":"todo.py","file_name":"todo.py","file_ext":"py","file_size_in_byte":2314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"414307333","text":"def calculate_ans(flats):\n needed, shortest = len(set(flats)), len(flats)\n\n counter = dict()\n ind1, ind2 = 0, 0\n while ind1 < len(flats):\n if len(counter.keys()) == needed:\n shortest = min(shortest, ind2-ind1)\n\n counter[flats[ind1]] -= 1\n if counter[flats[ind1]] == 0:\n del counter[flats[ind1]]\n ind1 += 1\n else:\n if ind2 == len(flats):\n break\n\n if flats[ind2] in counter:\n counter[flats[ind2]] += 1\n else:\n counter[flats[ind2]] = 1\n ind2 += 1\n\n return shortest\n\nif __name__ == '__main__':\n _ = input()\n print(calculate_ans(input()))\n","sub_path":"cf/701/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"42980746","text":"import numpy as np\n\n\ndef shift_network_simple(nodes, w, b, output, target):\n\n if output >= 0: \n result = 1\n else: \n result = 0\n \n error = calc_error(target, result)\n\n w[0,0] = shift_weight(0.5, error, nodes[0,0], w[0,0])\n w[1,0] = shift_weight(0.5, error, nodes[0,1], w[1,0])\n b = change_bias(1, error, b)\n\n return (w, b, result, error)\n\ndef shift_network(nodes, hidden, weight1, weight2, bias1, bias2, output, target):\n\n if output >= 0: \n result = 1\n else: \n result = 0\n \n error = calc_error(target, result)\n error_3 = 0.5 * error * weight2[0,0]\n error_4 = 0.5 * error * weight2[1,0] \n\n weight2[0,0] = shift_weight(0.5, error, hidden[0,0], weight2[0,0])\n weight2[1,0] = shift_weight(0.5, error, hidden[0,1], weight2[1,0])\n\n\n weight1[0,0] = shift_weight(0.5, error_3, nodes[0,0], weight1[0,0])\n weight1[1,0] = shift_weight(0.5, error_3, nodes[0,0], weight1[1,0])\n weight1[0,1] = shift_weight(0.5, error_4, nodes[0,1], weight1[0,1])\n weight1[1,1] = shift_weight(0.5, error_4, nodes[0,1], weight1[1,1])\n\n\n\n bias1[0,0] = change_bias(0.5, error_3, bias1[0,0])\n bias1[0,1] = change_bias(0.5, error_4, bias1[0,1])\n bias2 = change_bias(0.5, error, bias2)\n\n return (weight1, weight2, bias1, bias2, result, error, error_3, error_4)\n\ndef print_all_simple(nodes, target, output, result, error, weights, bias):\n print(\" {} {} {} {} {} {} {} {} {}\".format(nodes[0,0], nodes[0,1], target, output, result, error, weights[0,0], weights[1,0], bias))\n\ndef print_all(nodes, target, hidden, output, result, error, error_3, error_4, weight1, weight2, bias1, bias2): \n print(\"{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}\".format(nodes[0,0], nodes[0,1], target, hidden[0,0], hidden[0,1], output, result, error, error_3, error_4, weight1[0,0], weight1[1,0], weight1[0,1], weight1[1,1], weight2[0,0], weight2[1,0], bias1[0,0], bias1[0,1], bias2))\n\n\ndef calc_error(target, output):\n return target - output\n\ndef shift_weight(alpha, error, node, weight):\n shift = alpha * error * node\n return weight + shift\n\ndef change_bias(alpha, error, bias):\n shift = alpha * error\n return bias + shift\n\ndef activate_hidden(h):\n \n if h[0,0] >= 0: \n h[0,0] = .85\n else: \n h[0,0] = .01\n\n if h[0,1] >= 0: \n h[0,1] = .85\n else: \n h[0,1] = .01\n\n return h\n\n\n\nx1 = np.array([[0,0]], float)\nx2 = np.array([[0,1]], float)\nx3 = np.array([[1,0]], float)\nx4 = np.array([[1,1]], float)\nw = np.array([[0],[0]], float)\n\ne = -1\nb = -0.5\nv3 = 1\n\ni = 0\n\nprint(\" V1 V2 t3 y3 V3 e W1 W2 b\")\n\n\nwhile (i < 100): \n\n #0 and 1 \n output = b + np.dot(x2,w)\n w,b,v3,e = shift_network_simple(x2,w,b,output, 1)\n print_all_simple(x2, 1, output, v3, e, w, b)\n\n #1 and 0\n output = b + np.dot(x3,w)\n w,b,v3,e = shift_network_simple(x3,w,b,output, 1)\n print_all_simple(x3, 1, output, v3, e, w, b)\n\n #1 and 1 \n output = b + np.dot(x4,w)\n w,b,v3,e = shift_network_simple(x4,w,b,output, 1)\n print_all_simple(x4, 1, output, v3, e, w, b)\n\n #0 and 0 \n output = b + np.dot(x1,w)\n w,b,v3,e = shift_network_simple(x1,w,b,output, 0)\n print_all_simple(x1, 0, output, v3, e, w, b)\n\n i = i + 1\n j = -1\n\nwhile (True):\n\n j = j + 1 \n x1 = np.array([[0,0]], float)\n x2 = np.array([[0,1]], float)\n x3 = np.array([[1,0]], float)\n x4 = np.array([[1,1]], float)\n\n w1 = np.random.rand(2,2)\n w2 = np.random.rand(2,1)\n b1 = np.random.rand(1,2)\n b2 = 0\n\n print(\" V1 V2 t3 y1 y2 y3 V3 e1 e2 e3 W1 W2 W3 W4 W5 W6 b1 b2 b3\")\n\n i = 0\n\n while (i < 100): \n\n #0 and 0\n h = b1 + np.dot(x1, w1)\n hidden = activate_hidden(h)\n output = b2 + np.dot(hidden,w2)\n w1,w2,b1,b2,o5,e,e3,e4 = shift_network(x1,hidden,w1,w2,b1,b2,output,0)\n result1 = o5\n print_all(x1, 0, h, output, o5, e, e3, e4, w1, w2, b1, b2)\n\n #0 and 1\n h = b1 + np.dot(x2, w1)\n hidden = activate_hidden(h)\n output = b2 + np.dot(hidden,w2)\n w1,w2,b1,b2,o5,e,e3,e4 = shift_network(x2,hidden,w1,w2,b1,b2,output,1)\n result2 = o5\n print_all(x2, 1, h, output, o5, e, e3, e4, w1, w2, b1, b2)\n\n #1 and 0 \n h = b1 + np.dot(x3, w1)\n hidden = activate_hidden(h)\n output = b2 + np.dot(hidden,w2)\n w1,w2,b1,b2,o5,e,e3,e4 = shift_network(x3,hidden,w1,w2,b1,b2,output,1)\n result3 = o5\n print_all(x3, 1, h, output, o5, e, e3, e4, w1, w2, b1, b2)\n\n\n #1 and 1 \n h = b1 + np.dot(x4, w1)\n hidden = activate_hidden(h)\n output = b2 + np.dot(hidden,w2)\n w1,w2,b1,b2,o5,e,e3,e4 = shift_network(x4,hidden,w1,w2,b1,b2,output,0)\n result4 = o5\n print_all(x4, 0, h, output, o5, e, e3, e4, w1, w2, b1, b2)\n\n i = i + 1\n \n if(result1 == 0 and result2 == 1 and result3 == 1 and result4 == 0):\n break\n\n \nprint(w1)\nprint(w2)","sub_path":"hw1/perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":5061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"80309691","text":"'''\r\nCreated on Nov 11, 2015\r\n\r\n@author: Norbi\r\n'''\r\n\r\n\r\nclass Validator :\r\n @staticmethod\r\n def read_positive_integer(message):\r\n \"\"\"\r\n Reads a positive integer\r\n input:message\r\n output:n as integer no\r\n \"\"\"\r\n n=-1\r\n while n < 0 :\r\n try:\r\n n=int (input (message))\r\n except ValueError:\r\n print(\"Please insert a number that is positive\")\r\n \r\n return n\r\n @staticmethod\r\n def read_day(message):\r\n \"\"\"\r\n Args:message-string\r\n Reads day between 1-31\r\n \"\"\"\r\n day=-1\r\n while not (day>1 and day<32):\r\n try:\r\n day=int(input(message))\r\n except ValueError:\r\n print(\"Please introduce a day betweem 1-31\")\r\n return day\r\n @staticmethod \r\n def read_month(message):\r\n \"\"\"\r\n Args:message-string\r\n Reads a month between 1-12\r\n Returns:month-int between 1->12\r\n \"\"\"\r\n month=-1\r\n while month < 1 or month > 12 :\r\n try:\r\n month=int(input(message))\r\n return month\r\n except ValueError: \r\n print(\"Please introduce a month between 1-12\")\r\n @staticmethod \r\n def read_year(message):\r\n \"\"\"\r\n Args:message-string to be shown to user\r\n reads a year\r\n Returns:positive integer\r\n \"\"\"\r\n return Validator.read_positive_integer(message)\r\n @staticmethod\r\n def simple_read(message):\r\n '''\r\n\r\n Args:\r\n message:string\r\n\r\n Returns:n-anything that was read from user (string)\r\n\r\n '''\r\n n=input(message)\r\n return n\r\n @staticmethod\r\n def read_grade(grade_list):\r\n try :\r\n grade=int(input(\"Introduce grade:\"))\r\n except ValueError :\r\n print(\"\"\"Don't be hasty!\r\nYou have not introduced antyhing.\"\"\")\r\n return \r\n\r\n print(grade_list)\r\n\r\n while not grade in grade_list and not grade == None :\r\n try:\r\n grade=int (input(\"Please introduce a grade between\" + str(grade_list)))\r\n except ValueError:\r\n print(\"You have not inserted a number!\")\r\n grade=-1\r\n \r\n return grade\r\n \r\n @staticmethod\r\n def read_good_option(op_list):\r\n \"\"\"\r\n Reads an option between list op_list\r\n if enter is pressed too early then message\r\n Returns:option-int between op_list\r\n \"\"\"\r\n try :\r\n option= int (input(\"choose option:\"))\r\n except ValueError :\r\n print(\"\"\"Don't be hasty!\r\nYou have not introduced antyhing.\"\"\")\r\n return \r\n \r\n while not option in op_list: \r\n try :\r\n option=int(input(\"Please introduce an option between\" + str(op_list)))\r\n except ValueError:\r\n print(\"You have not introduced an integer!\")\r\n option=-1\r\n return option\r\n @staticmethod\r\n def sverifyid(verifstud,studrepo):\r\n \"\"\"\r\n Verifies if id of student is in the list of students\r\n Input:student and repository of students\r\n Output:0 if founnd\r\n 1 if not found\r\n \"\"\"\r\n if not studrepo.get_all() :\r\n return True\r\n \r\n for stud in studrepo.get_all() :\r\n if verifstud.get_id() == stud.get_id() :\r\n return False\r\n return True\r\n\r\n @staticmethod\r\n def averifyid(verifassign,assignrepo):\r\n \"\"\"\r\n Verifies if id is in list of assignments\r\n Input: student with the id which will be verified, repository of assginments\r\n Output:0 if found\r\n 1 if not found\r\n \"\"\"\r\n if not assignrepo.get_all() :\r\n return True\r\n \r\n for assign in assignrepo.get_all() :\r\n if verifassign.get_id() == assign.get_id() :\r\n return False\r\n return True\r\n\r\ndef veriftest():\r\n m=student_repository()\r\n s=Student(5, \"john\", 7)\r\n s1=Student(6, \"marry\", 8)\r\n \r\n m.add(s)\r\n m.add(s1)\r\n \r\n ver=Student(5, \"\", 0)\r\n Validator.sverifyid(ver, m)\r\n \r\n#veriftest()\r\n\r\nclass ObjectException(Exception):\r\n \r\n def __init__(self,msg):\r\n self.__msg=msg\r\n \r\n def __str__(self):\r\n return self.__msg\r\n\r\nclass studValidator :\r\n\r\n @staticmethod\r\n def validStud(stud):\r\n \"\"\"\r\n verifies if the atributes of stud are corectly introduced by certain rules\r\n Args:stud:object type Student\r\n Returns:\r\n object:\r\n \"\"\"\r\n errMsg=\"\"\r\n if not isinstance(stud,Student) :\r\n errMsg=\"The object is not type Student!\"\r\n if not isinstance(stud.get_id(),int) or stud.get_id()<0 :\r\n errMsg+=\"Student Id is not a positive integer!\"\r\n try :\r\n stud.get_name().isalpha\r\n except AttributeError :\r\n errMsg+=\"You have not introduced a name!\"\r\n if not isinstance(stud.get_group(),int) or stud.get_group()<1 :\r\n errMsg+=\"Student's groud is not a positive integer!\"\r\n\r\n if len(errMsg)>0 :\r\n raise ObjectException(errMsg)\r\nfrom Domain.domstud import *\r\ndef teststudValidator():\r\n x=Student(-3,3,0)\r\n try:\r\n studValidator.validStud(x)\r\n assert False\r\n except ObjectException as e:\r\n if e == \"Student Id is not a positive integer!You have not introduced a name!Student's groud is not a positive integer!\" :\r\n assert True\r\n else:\r\n False\r\nteststudValidator()","sub_path":"Exams and lab3/Lab3/Domain/Validity.py","file_name":"Validity.py","file_ext":"py","file_size_in_byte":5679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"376992992","text":"# %load q03_skewness_log/build.py\nfrom scipy.stats import skew\nimport pandas as pd\nimport numpy as np\n\ndata = pd.read_csv('data/train.csv')\n\n\n# Write code here:\ndef skewness_log(data):\n s1=np.log(data['GrLivArea'])\n skw1=skew(s1)\n s2=np.log(data['SalePrice'])\n skw2=skew(s2)\n return skw1,skw2\n\n\n","sub_path":"q03_skewness_log/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"217102338","text":"import numpy as np\n\n\nclass KMeans_Clustering():\n\n \"\"\"\n KMeans clustering\n K : number of clusters\n init : initialization. 'points' or 'centroids'.\n \"\"\"\n\n def __init__(self, K, init='points', max_iter=300):\n self.K = K\n self.init = init\n self.max_iter = 300\n\n def fit(self, X):\n self.N, self.P = X.shape\n self.X = X\n\n if self.init == 'centroids':\n rd_init_mean_idx = np.random.randint(0, self.N, size=self.K)\n init_centroids = X[rd_init_mean_idx].T\n # assignment\n self.assigment_step_(X, init_centroids)\n # update\n self.update_step_(X, self.Z)\n\n elif self.init == 'points':\n rd_init_assign = np.random.randint(0, self.K, size=self.N)\n self.Z = np.zeros((self.K, self.N))\n for i in range(self.N):\n self.Z[rd_init_assign[i], i] = 1\n # update\n self.update_step_(X, self.Z)\n\n else:\n raise ValueError(\"init should be either 'points' or 'centroids'\")\n\n self.compute_epsilon_(X, self.Z, self.centroids)\n\n nb_iter = 0\n assign_cond = True\n epsilon_cond = True\n while nb_iter < self.max_iter and assign_cond and epsilon_cond:\n old_Z = np.copy(self.Z)\n old_epsilon = self.epsilon\n # assignment\n self.assignment_step_(X, self.centroids)\n # update\n self.update_step_(X, self.Z)\n\n self.compute_epsilon_(X, self.Z, self.centroids)\n\n if np.sum(np.abs(old_Z - self.Z)) == self.Z.shape[0] * self.Z.shape[1]:\n assign_cond = False\n\n if old_epsilon == self.epsilon:\n epsilon_cond = False\n\n nb_iter += 1\n\n def predict(self, X):\n N = X.shape[0]\n Z = np.zeros((self.K, N))\n for i in range(N):\n kp = np.argmin(np.sum((self.centroids - X[i])**2, axis=1))\n Z[kp, i] = 1\n return np.argmax(Z, axis=0)\n\n def fit_predict(self, X):\n self.fit(X)\n return np.argmax(self.Z, axis=0)\n\n def assignment_step_(self, X, centroids):\n self.Z = np.zeros((self.K, self.N))\n for i in range(self.N):\n kp = np.argmin(np.sum((self.centroids - X[i])**2, axis=1))\n self.Z[kp, i] = 1\n\n def update_step_(self, X, Z):\n self.centroids = Z.dot(X) / np.sum(Z, axis=1).reshape((self.K, 1))\n\n def compute_epsilon_(self, X, Z, centroids):\n self.epsilon = 0\n for k in range(self.K):\n self.epsilon += np.sum(Z[k, :] *\n np.sum((X - centroids[k])**2, axis=1))\n","sub_path":".ipynb_checkpoints/Model_KMeans-checkpoint.py","file_name":"Model_KMeans-checkpoint.py","file_ext":"py","file_size_in_byte":2674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"260034394","text":"# external imports\nfrom selenium.common.exceptions import TimeoutException, NoSuchElementException, WebDriverException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as ec\n\n# internal imports\nfrom secret_info.secret import web_address_babe\nfrom create_log import ErrorLogModel\n\n\ndef find_person_on_beibisida(driver, person_name):\n driver.get(web_address_babe)\n\n # enter the name of the person in the search bar\n xpath_search_bar = \"//form[@id='search']/input[@id='searchfield']\"\n driver.find_element_by_xpath(xpath_search_bar).send_keys(person_name)\n\n try:\n # select the users in the search bar\n xpath_complete_person_name = \"//ul/li[@class='ui-menu-item']/div[text() = '{}']\".format(person_name)\n WebDriverWait(driver, 10).until(ec.element_to_be_clickable((By.XPATH, xpath_complete_person_name))).click()\n except (TimeoutException, WebDriverException):\n log_message = \"{} was not found in the search bar on {}\".format(person_name, web_address_babe)\n ErrorLogModel(person_name=person_name, message_type=\"Progression\",\n message_text=log_message).add_message_document()\n\n try:\n # find the users in the results of the page that are given\n driver.find_element_by_xpath(xpath_search_bar).send_keys(Keys.ENTER)\n xpath_thumbnail = '//a/span[@class=\"thumbtextsmall\"][text() = \"{}\"]'.format(person_name)\n WebDriverWait(driver, 10).until(ec.element_to_be_clickable((By.XPATH, xpath_thumbnail))).click()\n except(TimeoutException, WebDriverException):\n log_message = \"{} was not found between the results on {}\".format(person_name, web_address_babe)\n ErrorLogModel(person_name=person_name, message_type=\"Progression\",\n message_text=log_message).add_message_document()\n\n try:\n # pick the first thumbnail and check if it is the right users\n xpath_first_result = \"//span/div[@class='thumbshot thumbshotsmall '][1]/a/span[@class='thumbtextsmall']\"\n WebDriverWait(driver, 10).until(ec.element_to_be_clickable((By.XPATH, xpath_first_result))).click()\n driver.find_element_by_xpath('//div[@id=\"bioarea\"]/h2[contains(text(),\"{}\")]'.format(person_name))\n except(NoSuchElementException, TimeoutException):\n log_message = \"{} was not found on {}\".format(person_name, web_address_babe)\n ErrorLogModel(person_name=person_name, message_type=\"Warning\",\n message_text=log_message).add_message_document()\n # if the users is not found on the website exit the function\n return None\n\n else:\n log_message = \"{} has been found with a different name on {}\".format(person_name, web_address_babe)\n ErrorLogModel(person_name=person_name, message_type=\"Progression\",\n message_text=log_message).add_message_document()\n else:\n log_message = \"{} has been found in the result on {}\".format(person_name, web_address_babe)\n ErrorLogModel(person_name=person_name, message_type=\"Progression\",\n message_text=log_message).add_message_document()\n else:\n log_message = \"{} has been found with the name in the search bar on {}\".format(person_name, web_address_babe)\n ErrorLogModel(person_name=person_name, message_type=\"Progression\",\n message_text=log_message).add_message_document()\n\n return driver.current_url\n","sub_path":"beibisida/parts/beibisida_person_search.py","file_name":"beibisida_person_search.py","file_ext":"py","file_size_in_byte":3737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"251117632","text":"# 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。\n# 最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。\n# 你可以假设除了整数 0 之外,这个整数不会以零开头。\n# 示例 1:\n# 输入: [1,2,3]\n# 输出: [1,2,4]\n# 解释: 输入数组表示数字 123。\n# 示例 2:\n# 输入: [4,3,2,1]\n# 输出: [4,3,2,2]\n# 解释: 输入数组表示数字 4321。\nclass Solution:\n def plusOne(self, digits):\n \"\"\"\n :type digits: List[int]\n :rtype: List[int]\n \"\"\"\n # temp = 1\n # for i in range(len(digits)-1,-1,-1):\n # digits[i] += temp\n # if digits[i] == 10:\n # digits[i] = 0\n # temp = 1\n # else:\n # temp = 0\n # if temp == 1:\n # digits.insert(0,1)\n # return digits\n for i in range(len(digits)-1, -1, -1):\n if digits[i] == 9:\n digits[i] = 0\n else:\n digits[i] += 1\n return digits\n ans = [0]*(len(digits)+1)\n ans[0] = 1\n return ans\n\n\na = Solution().plusOne([9,9,9])\nprint(a)\n","sub_path":"all_topic/esay_topic/66.加1.py","file_name":"66.加1.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"596321276","text":"import collections\nclass Solution:\n def minAreaRect(self, points):\n \"\"\"\n :type points: List[List[int]]\n :rtype: int\n \"\"\"\n heights = collections.defaultdict(set)\n for x,y in points:\n heights[x].add(y)\n\n minArea = float('inf')\n xPoints = sorted(heights)\n\n for i,x1 in enumerate(xPoints[:-1]):\n if xPoints[i+1] - x1 >= minArea:\n continue\n\n for x2 in xPoints[i+1:]:\n width = x2 - x1\n if width >= minArea:\n break\n\n commonHeights = heights[x1].intersection(heights[x2])\n print(i, x1, x2, commonHeights, heights, xPoints)\n if len(commonHeights) < 2:\n continue\n sortedCommon = sorted(list(commonHeights))\n minHeight = float('inf')\n\n for j in range(len(sortedCommon)-1):\n h = sortedCommon[j+1] - sortedCommon[j]\n if h < minHeight:\n minHeight = h\n\n\n\n tempMinArea = width*minHeight\n if tempMinArea < minArea:\n minArea = tempMinArea\n\n\n return minArea if minArea < float('inf') else 0\n\npoints = [[1,1],[1,3],[3,1],[3,3],[2,2]]\npoints2 = [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]\npoints3 = [[3,2],[3,1],[4,4],[1,1],[4,3],[0,3],[0,2],[4,0]]\nprint(Solution().minAreaRect(points3))","sub_path":"minAreaRect.py","file_name":"minAreaRect.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"606494781","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport sqlalchemy as sql\nimport sqlalchemy.sql.expression as expression\n\n\ndef upgrade(migrate_engine):\n meta = sql.MetaData()\n meta.bind = migrate_engine\n\n user_table = sql.Table('user', meta, autoload=True)\n federated_table = sql.Table('federated_user', meta, autoload=True)\n idp_table = sql.Table('identity_provider', meta, autoload=True)\n\n join = sql.join(federated_table, idp_table,\n federated_table.c.idp_id == idp_table.c.id)\n sel = sql.select(\n [federated_table.c.user_id, idp_table.c.domain_id]).select_from(join)\n with migrate_engine.begin() as conn:\n for user in conn.execute(sel):\n values = {'domain_id': user['domain_id']}\n stmt = user_table.update().where(\n sql.and_(\n user_table.c.domain_id == expression.null(),\n user_table.c.id == user['user_id'])).values(values)\n conn.execute(stmt)\n","sub_path":"keystone/common/sql/data_migration_repo/versions/015_migrate_update_federated_user_domain.py","file_name":"015_migrate_update_federated_user_domain.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"235626681","text":"'''\nKICKSTARTER SERVER SETTING\nAUTHOR: DRTAGKIM\n2014\n'''\n# GENERAL SETTING ===============================\nHAS_IMAGE = False\nQUIETLY = False\nRECOVER_TRIAL = -1\n# DATABASE SETTING ==============================\nDATABASE_NAME = \"sample.db\" #SQLite3 database name (main)\nCREATE_SCHEMA = False\nSQLITE_MYSQL = \"mysql\" # (sqlite / mysql)\nLOCK_TIMEOUT = 120 #seconds\n# MYSQL SETTING =================================\nHOST = \"localhost\"\nDATABASE = \"kickstarter\" # database name\nUSER = \"kimtk\"\nPASSWORD = \"\"\n\n# SCHEDULE ======================================\nPROJECT_LOG_START_HOUR = '0' # project log starts at\nPROJECT_LOG_START_MIN = '0' #0-59\nPROJECT_LOG_START_SEC = '59' #0-59\n\nPROJECT_PAGE_START_HOUR = '3'\nPROJECT_PAGE_START_MIN = '0'\nPROJECT_PAGE_START_SEC = '59'\n\nRECOVER_ERROR_HOUR = '9'\nRECOVER_ERROR_MIN = '0'\nRECOVER_ERROR_SEC = '59'\n\nVACUUM_DATABASE_HOUR = '15'\nVACUUM_DATABASE_MIN = '0'\nVACUUM_DATABASE_SEC = '59'\n\n\n# PROJECT_LOG_SERVER SETTING ====================\n# Data collection range. If True, full collection (from the beginning); othersie, False\nSCRAP_FULL = False\n# Page call again if the server responses too late.\nPAGE_REQUEST_TRIAL = 10 # how many calls if it fails?\nPROJECT_LOG_PORT = 10001\nPROJECT_LOG_SERVER_THREAD_POOL = 13\nCATEGORIES = [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"11\",\"12\",\"13\"]\n\n# PROJECT_PAGE_SERVER SETTING ===================\nPROJECT_PAGE_PORT = 10002\nPROJECT_PAGE_SERVER_THREAD_POOL = 20\nBACKER_CONNECTION_RECOVER = 10 # second","sub_path":"ks_project/server_setting.py","file_name":"server_setting.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"580554256","text":"t = int(input())\nwhile t > 0:\n\tn = int(input())\n\tt-=1\n\n\tif n == 1:\n\t\tprint(\"(0,1)\",end = ' ')\n\t\tcontinue\n\n\tfor a in range(n//2):\n\t\tfor b in range(a,n//2):\n\t\t\tif (a*a) + (b*b) == n:\n\t\t\t\tprint(\"(\" + str(a) + \",\" + str(b) + \")\",end = ' ')","sub_path":"python problems/pythagoreanChallenge.py","file_name":"pythagoreanChallenge.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"476126204","text":"\"\"\"Maximize Sum Of Array After K Negations\nhttps://leetcode.com/problems/maximize-sum-of-array-after-k-negations/\n\nTime complexity O(nlogn) \nSpace complexity O(1), there is a limited number of recursive calls\n\"\"\"\nfrom typing import List\n\n\ndef largest_sum(arr: List[int], k: int) -> int:\n arr.sort()\n \n # 0 is the smallest number, modify it\n if arr[0] == 0:\n return sum(arr)\n \n # all numbers are positive, modify the smallest one \n if arr[0] > 0:\n if k % 2 == 1:\n arr[0] = -arr[0]\n return sum(arr)\n \n # there are negative numbers, modify them\n i = 0\n while arr[i] < 0 and i < len(arr) and i < k:\n arr[i] = -arr[i]\n i += 1\n \n if k - i == 0:\n return sum(arr)\n \n return largest_sum(arr, k - i)","sub_path":"python/largest_sum.py","file_name":"largest_sum.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"154463814","text":"class ReadScoreMatrixForSmith:\n lines = None\n scoreLines= [\"\" for x in range(48)]\n\n\n def __init__(self):\n with open('scorematrix.txt') as f:\n self.lines = f.readlines()\n\n # print(self.operator(0))\n\n\n def operator(self,i):\n # print(len(self.lines))\n #print(len(self.lines[1]))\n y=0\n z=0\n for self.i in range(len(self.lines)):\n if(len(self.lines[i])==4):\n self.scoreLines[z]=self.lines[i][y]\n z+=1\n self.scoreLines[z]=self.lines[i][y+1]\n z+=1\n self.scoreLines[z]=int(self.lines[i][y+2])\n z+=1\n i+=1\n elif(len(self.lines[i])==5):\n self.scoreLines[z]=self.lines[i][y]\n z+=1\n self.scoreLines[z]=self.lines[i][y+1]\n z+=1\n say = int(self.lines[i][y+3])\n say*=(-1)\n self.scoreLines[z]=say\n z+=1\n i+=1\n else:return self.parseScoreMatrix(self.scoreLines)\n\n def parseScoreMatrix(self,scoreLines):\n my_dict = {}\n i=0\n while i<46:\n my_dict.update({scoreLines[i]+scoreLines[i+1]:scoreLines[i+2]})\n if(scoreLines[i+2]<0):\n my_dict.update({scoreLines[i]+scoreLines[i+1]:0})\n i+=3\n #print(my_dict)\n return my_dict\n","sub_path":"ReadScoreMatrixForSmith.py","file_name":"ReadScoreMatrixForSmith.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"258940410","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 28 16:06:03 2020\n\n@author: desai\n\"\"\"\n#Rutvik Desai\n#100664467\nimport math\nimport numpy as np\nimport scipy as sp\n\ndef f(x):\n return math.cos(1+t**2)\n\ndef compositeSimpsons(f,a,b,M):\n x = sp.linspace(a,b,M+1)\n h = (b-a)/float(M)\n I = 0.0 \n \n for i in range(1,M+1):\n I += (h/6.0) * (f(x[i-1]) + 4 * f((x[i-1] + x[i])/2.0) + f(x[i])) \n return I\n\nprint(compositeSimpsons(f,1.0,-1.0,2))","sub_path":"assignments/Assignment5/compositeSimpsons.py","file_name":"compositeSimpsons.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"327915434","text":"import pandas as pd\nimport numpy as np\nfrom scipy.optimize import curve_fit\n\n\"\"\" \nfunction calculates valleyOccupation-weighted mean (first calculates\nmean of each valley and then sums those mean up, weighted by the valley)\n\ninput:\n data read-in data from outputfile of bulkSimulation\n occupationData read-in data from valleyOccupation output file\n startAvgTime values that are recorded after that time are used \n for the averaging\n\"\"\"\ndef calcValleyOccupationWeightedMean(data, occupationData, startAvgTime=1e-12 ):\n if(data[\"time\"].iat[-1] < startAvgTime):\n print(\" PROBLEM: Can't calculate mean: startAvgTime > simulationTime -> Change startAvgTime.\")\n data = data[data[\"time\"] > startAvgTime]\n occupationData = occupationData[occupationData[\"time\"] > startAvgTime]\n\n mean = 0\n for i in range(0, data.shape[1] - 1):\n tmp = data[\"valley_\" + str(i)] * occupationData[\"valley_\" + str(i)]\n mean += tmp.mean()\n return mean\n\n\"\"\" \nfunction calculates mean for each valley\n\ninput:\n data read-in data from outputfile of bulkSimulation\n startAvgTime values that are recorded after that time are used \n for the averaging\n\"\"\"\n# calculates the mean of a characteristic for each valley\ndef calcValleywiseMean(data, startAvgTime=1e-12 ):\n if(data[\"time\"].iat[-1] < startAvgTime):\n print(\" PROBLEM: Can't calculate mean: startAvgTime > simulationTime -> Change startAvgTime.\")\n\n data = data[data[\"time\"] > startAvgTime]\n mean = data.mean(axis=0)\n return mean[1:]\n\n\ndef linearFunc(x, a):\n return a * x\n\n# fits the given fields and dirft velocities to a linear function\n# \n# parameter:\n# fields list of applied electric fields\n# avgDriftVel list of avgDriftVel for each field\n# maxFieldUsed maximal electricField that is used for fitting\n# \n# return:\n# popt mobility\n# perr fitting error of mobility (std-dev)\ndef fitMobility(fields, avgDriftVel):\n popt, pcov = curve_fit(linearFunc, fields, avgDriftVel)\n perr = np.sqrt(np.diag(pcov)) # std-dev\n return popt[0], perr[0]\n\n","sub_path":"helper/emcPlottingFiles/emcPlottingFiles/plotBulkSimulationResults.py","file_name":"plotBulkSimulationResults.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"556611438","text":"s = \"ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY\" # Currently raw string not within a list.\r\ns = s.split(\" \") # This is doing 2 things. The first is making it into a list and the second is spacing it out by putting a space (a comma) between every word.\r\nunique = [] # This setting an empty list which is used later on\r\nfor letter in s: #Letter is defined by looking in S.\r\n if not letter in unique: # If the word in letter is not in unique. Append it. This will print the place of where it is\r\n unique.append(letter) # This is adding the numbers \r\n print(letter) # Prints variable \"letter\"\r\n print(unique) # Prints variable \"unique\"\r\n\r\nfor letter in s: # If letter and s contain the same string\r\n print(unique.index(letter)) # Print the place of the word.\r\n \r\n","sub_path":"ReplaceIndex.py","file_name":"ReplaceIndex.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"66652441","text":"import os\nimport os.path\n\nimport pytest\n\nfrom pypi2nix.archive import Archive\nfrom pypi2nix.logger import Logger\nfrom pypi2nix.requirement_parser import requirement_parser\nfrom pypi2nix.requirement_set import RequirementSet\nfrom pypi2nix.source_distribution import DistributionNotDetected\nfrom pypi2nix.source_distribution import SourceDistribution\n\nfrom .logger import get_logger_output\nfrom .switches import nix\n\n\n@pytest.fixture\ndef source_distribution(six_source_distribution_archive, logger):\n return SourceDistribution.from_archive(six_source_distribution_archive, logger)\n\n\n@pytest.fixture\ndef flit_requirements(current_platform):\n requirements = RequirementSet(current_platform)\n requirements.add(requirement_parser.parse(\"flit == 1.3\"))\n return requirements\n\n\n@pytest.fixture\ndef flit_distribution(pip, project_dir, download_dir, flit_requirements, logger):\n pip.download_sources(flit_requirements, download_dir)\n archives = [\n Archive(path=os.path.join(download_dir, filename))\n for filename in os.listdir(download_dir)\n ]\n distributions = list(\n map(lambda archive: SourceDistribution.from_archive(archive, logger), archives)\n )\n for distribution in distributions:\n if distribution.name == \"flit\":\n return distribution\n raise Exception(\"Could not download source distribution for `flit`\")\n\n\n@nix\ndef test_from_archive_picks_up_on_name(source_distribution):\n assert source_distribution.name == \"six\"\n\n\n@nix\ndef test_that_a_source_distributions_name_is_canonicalized(logger):\n distribution = SourceDistribution(name=\"NaMe_teSt\", logger=logger)\n assert distribution.name == \"name-test\"\n\n\n@nix\ndef test_six_package_has_no_pyproject_toml(source_distribution):\n assert source_distribution.pyproject_toml is None\n\n\n@nix\ndef test_that_flit_pyproject_toml_is_recognized(flit_distribution):\n assert flit_distribution.pyproject_toml is not None\n\n\n@nix\ndef test_that_flit_build_dependencies_contains_requests(\n flit_distribution, current_platform\n):\n assert \"requests\" in flit_distribution.build_dependencies(current_platform)\n\n\n@nix\ndef test_that_we_can_generate_objects_from_source_archives(\n source_distribution_archive, logger\n):\n SourceDistribution.from_archive(source_distribution_archive, logger)\n\n\n@nix\ndef test_that_we_can_detect_setup_requirements_for_setup_cfg_projects(\n distribution_archive_for_jsonschema, current_platform, logger\n):\n distribution = SourceDistribution.from_archive(\n distribution_archive_for_jsonschema, logger\n )\n assert \"setuptools-scm\" in distribution.build_dependencies(current_platform)\n\n\ndef test_that_trying_to_create_source_distribution_from_random_zip_throws(\n test_zip_path, logger\n):\n archive = Archive(path=test_zip_path)\n with pytest.raises(DistributionNotDetected):\n SourceDistribution.from_archive(archive, logger)\n\n\ndef test_build_dependencies_for_invalid_deps_logs_warning(\n data_directory, current_platform, logger: Logger\n):\n spacy_distribution_path = os.path.join(data_directory, \"spacy-2.1.0.tar.gz\")\n archive = Archive(spacy_distribution_path)\n\n dist = SourceDistribution.from_archive(archive, logger)\n\n assert \"WARNING:\" not in get_logger_output(logger)\n dist.build_dependencies(current_platform)\n assert \"WARNING:\" in get_logger_output(logger)\n\n\ndef test_invalid_build_dependencies_for_setupcfg_package_logs_warning(\n data_directory, current_platform, logger\n):\n distribution_path = os.path.join(\n data_directory, \"setupcfg-package\", \"setupcfg-package.tar.gz\"\n )\n archive = Archive(distribution_path)\n\n dist = SourceDistribution.from_archive(archive, logger)\n\n assert \"WARNING:\" not in get_logger_output(logger)\n dist.build_dependencies(current_platform)\n assert \"WARNING:\" in get_logger_output(logger)\n","sub_path":"unittests/test_source_distribution.py","file_name":"test_source_distribution.py","file_ext":"py","file_size_in_byte":3843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"368308629","text":"\nimport sys\nimport pandas as pd\nimport numpy as np\nimport manager\n\n\nclass SOLTCalibration:\n \"\"\" \n One-port: 3-Term Error Model\n\n s0 o--->---+------->------+--->---+\n | e10 | |\n v e00 e11 ^ v G\n | e01 | |\n b0 o---<---+-------<------+---<---+\n\n Two-port: 6-Term Error Model\n\n +----------------------->-----------------------+\n | e30 |\n a0 o-->--+----->-----+-->--+----->-----+-->--+----->-----+-->--o b3\n | 1 | | S21 | | e10 e32\n v e00 e11 ^ v S11 S22 ^ v e22\n | e10 e01 | | S12 | |\n b0 o--<--+-----<-----+--<--+-----<-----+--<--+\n\n (The 12 term model includes more leakage terms: e20, e02, e31, e21, e12)\n\n Two-port: 8-Term Error Model (One can be normalized to give 7 terms)\n\n a0 o-->--+----->-----+-->--+----->-----+-->--+----->-----+-->--o b3\n | e10 | | S21 | | e32 |\n v e00 e11 ^ v S11 S22 ^ v e22 e33 ^\n | e01 | | S12 | | e23 |\n b0 o--<--+-----<-----+--<--+-----<-----+--<--+-----<-----+--<--o a3\n \"\"\" \n\n @classmethod\n def load(cls, filename):\n df = pd.read_csv(filename, index_col=['path', 'index'])\n df = df.apply(lambda series: series.apply(lambda x: complex(x)))\n return cls(df=df)\n\n ####\n\n def __init__(self, index=None, resample=None, df=None):\n if df is not None:\n forward = df.loc['forward']\n reverse = df.loc['reverse']\n elif resample:\n forward = resample.df.loc['forward']\n reverse = resample.df.loc['reverse']\n ux = forward.index.union(index)\n forward = forward.reindex(ux).interpolate().reindex(index)\n reverse = reverse.reindex(ux).interpolate().reindex(index)\n else:\n columns = [ 'S11M', 'load', 'open', 'short',\n 'S21M', 'thru', 'thrumatch', 'crosstalk' ]\n data = [(0, 0, 0, 1, -1, 0, 0, 0)] \n forward = pd.DataFrame(data, columns=columns, index=index)\n reverse = pd.DataFrame(data, columns=columns, index=index)\n\n forward = self.recalibrate(forward)\n reverse = self.recalibrate(reverse)\n self.df = pd.concat(\n [forward, reverse], \n names=['path', 'index'],\n keys=['forward', 'reverse'])\n\n def __repr__(self):\n index = self.df.loc['forward'].index\n return '<%s start=%s, stop=%s, points=%s>' % (\n self.__class__.__name__, index[0], index[-1], len(index)-1)\n\n def recalibrate(self, df):\n gmo = df['open']\n gms = df['short'] \n df['e00'] = df['load']\n df['e11'] = (gmo + gms - 2 * df['e00']) / (gmo - gms)\n df['e10e01'] = -2 * (gmo - df['e00']) * (gms - df['e00']) / (gmo - gms)\n df['de'] = df['e00'] * df['e11'] - df['e10e01']\n df['e30'] = df['crosstalk']\n df['e22'] = ((df['thrumatch'] - df['e00']) / \n (df['thrumatch'] * df['e11'] - df['de']))\n df['e10e32'] = (df['thru'] - df['e30']) * (1 - df['e11'] * df['e22'])\n return df\n\n # public\n\n def update(self, gm, reverse=False):\n key = 'reverse' if reverse else 'forward'\n df = self.df.loc[key].copy()\n df[gm.name] = gm\n self.df.loc[key] = self.recalibrate(df).values\n return gm\n\n @property\n def index(self):\n return self.df.loc['forward'].index\n\n def save(self, filename):\n self.df.to_csv(filename)\n\n # real-time\n\n def return_loss(self, gm, reverse=False):\n df = self.df.loc['reverse' if reverse else 'forward']\n gamma = (gm - df['e00']) / (gm * df['e11'] - df['de'])\n return gamma.rename('S22' if reverse else 'S11')\n\n def response(self, gm, reverse=False):\n df = self.df.loc['reverse' if reverse else 'forward']\n gamma = gm / df['e10e32']\n return gamma.rename('S12' if reverse else 'S21')\n\n def enhanced_response(self, gm, reverse=False):\n df = self.df.loc['reverse' if reverse else 'forward']\n gamma = gm / df['e10e32'] * (df['e10e01'] / (df['e11'] * df['S11M'] - df['de']))\n return gamma.rename('S12' if reverse else 'S21')\n \n # batch\n\n def two_port(self):\n forward = self.df.loc['forward']\n reverse = self.df.loc['reverse']\n\n S11M, S21M = forward['S11M'], forward['S21M']\n S22M, S12M = reverse['S11M'], reverse['S21M']\n e00, e11, e22 = forward['e00'], forward['e11'], forward['e22']\n e33r, e22r, e11r = reverse['e00'], reverse['e11'], reverse['e22']\n e30, e10e01, e10e32 = forward['e30'], forward['e10e01'], forward['e10e32']\n e03r, e23re32r, e23re01r = reverse['e30'], reverse['e10e01'], reverse['e10e32']\n\n N11 = (S11M - e00) / e10e01\n N21 = (S21M - e30) / e10e32\n N22 = (S22M - e33r) / e23re32r\n N12 = (S12M - e03r) / e23re01r\n D = (1 + N11 * e11) * (1 + N22 * e22r) - N21 * N12 * e22 * e11r\n\n df = pd.DataFrame()\n df.name = 'Two Port Parameters'\n df['S11'] = (N11 * (1 + N22 * e22r) - e22 * N21 * N12) / D\n df['S21'] = (N21 * (1 + N22 * (e22r - e22))) / D\n df['S22'] = (N22 * (1 + N11 * e11) - e11r * N21 * N12) / D\n df['S12'] = (N12 * (1 + N11 * (e11 - e11r))) / D\n return df\n \n\n# pyvna\n######################################\n\n# initialize driver\n\ndef init(**args):\n manager.init(**args)\n return version()\n\ndef version():\n return manager.driver.version()\n\ndef temperature():\n return manager.driver.temperature()\n\ndef reset():\n manager.driver.reset()\n\ndef close():\n manager.close()\n\n# intialize calibration object\n \ndef load(filename):\n return SOLTCalibration.load(filename)\n\ndef save(cal, filename):\n cal.save(filename)\n\ndef create(start=None, stop=None, points=None, resample=None):\n driver = manager.driver\n start = driver.min_freq if start is None else start\n stop = driver.max_freq if stop is None else stop\n points = driver.default_points if points is None else points\n step = (stop - start) // points\n if start > stop or stop > driver.max_freq or start < driver.min_freq: \n raise ValueError(\"bad frequency range\")\n if points < 1:\n raise ValueError(\"bad number of points\")\n if step < 1:\n raise ValueError(\"step size too small\")\n index = np.array([int(start + i * step) for i in range(points + 1)])\n return SOLTCalibration(index, resample=resample)\n\n## measurements\n\ndef transmission(cal, name=None, average=3, window=3, reverse=False):\n index = cal.index\n gm = pd.Series(0, index, name='')\n for i in range(average):\n gm += manager.driver.transmission(index, reverse=reverse)\n gm = gm / average\n gm = rolling_mean(gm, window=window)\n if name:\n gm = cal.update(gm.rename(name), reverse=reverse)\n return gm\n\ndef reflection(cal, name=None, average=3, window=3, reverse=False):\n index = cal.index\n gm = pd.Series(0, index, name='')\n for i in range(average):\n gm += manager.driver.reflection(index, reverse=reverse)\n gm = gm / average\n gm = rolling_mean(gm, window=window)\n if name:\n gm = cal.update(gm.rename(name), reverse=reverse)\n return gm\n\n## calibrate\n\ndef cal_open(cal, **kw):\n return reflection(cal, name='open', **kw)\n\ndef cal_short(cal, **kw):\n return reflection(cal, name='short', **kw)\n\ndef cal_load(cal, **kw):\n return reflection(cal, name='load', **kw)\n\ndef cal_thru(cal, **kw):\n return transmission(cal, name='thru', **kw)\n\ndef cal_thrumatch(cal, **kw):\n return transmission(cal, name='thrumatch', **kw)\n\ndef cal_crosstalk(cal, **kw):\n return transmission(cal, name='crosstalk', **kw)\n\n# measure\n\ndef S11M(cal, **kw):\n return reflection(cal, name='S11M', reverse=False, **kw)\n\ndef S21M(cal, **kw):\n return transmission(cal, name='S21M', reverse=False, **kw)\n\ndef S22M(cal, **kw):\n gm = reflection(cal, name='S11M', reverse=True, **kw)\n return gm.rename('S22M')\n\ndef S12M(cal, **kw):\n gm = transmission(cal, name='S21M', reverse=True, **kw)\n return gm.rename('S12M')\n\n# real-time corrected measurements\n\ndef return_loss(cal, **kw):\n gm = reflection(cal, name='S11M', **kw)\n return cal.return_loss(gm, reverse=kw.get('reverse'))\n\ndef response(cal, **kw):\n gm = transmission(cal, name='S21M', **kw)\n return cal.response(gm, reverse=kw.get('reverse'))\n\ndef enhanced_response(cal, **kw):\n gm = transmission(cal, name='S21M', **kw)\n return cal.enhanced_response(gm, reverse=kw.get('reverse'))\n\ndef forward_path(cal, **kw):\n gloss = return_loss(cal, **kw)\n gresp = enhanced_response(cal, **kw)\n df = pd.DataFrame()\n df.name = 'Forward Path'\n df[gloss.name] = gloss\n df[gresp.name] = gresp\n return df\n\n# batch corrected measurements\n\ndef two_port(cal):\n return cal.two_port()\n\n# utilities\n\ndef rolling_mean(gm, window=3):\n re = gm.apply(np.real).rolling(window, min_periods=1).mean()\n im = gm.apply(np.imag).rolling(window, min_periods=1).mean()\n return re + 1j * im\n\n##\n\ndef to_impedance(gm):\n z = 50 * (1 + gm) / (1 - gm)\n return z.rename(gm.name + ' (impedance)')\n\ndef to_admittance(gm):\n z = 50 * (1 + gm) / (1 - gm)\n y = 1 / z\n return y.rename(gm.name + ' (admittance)')\n\ndef to_parallel(gm):\n z = 50 * (1 + gm) / (1 - gm)\n y = 1 / z\n xp = pd.Series(1 / y.real - 1j / y.imag, gm.index)\n return xp.rename(gm.name + ' (parallel)')\n\ndef to_quality_factor(gm):\n z = 50 * (1 + gm) / (1 - gm)\n q = pd.Series(np.abs(z.imag) / z.real, gm.index)\n return q.rename(gm.name + ' (Q)')\n\n##\n\ndef to_inductance(x):\n f = x.index.values\n im = x.imag / (2 * np.pi * f)\n s = pd.Series(x.real + 1j * im, x.index, name=x.name)\n return s.rename(x.name + ' (inductance)')\n \ndef to_capacitance(x):\n f = x.index.values\n im = -1 / (2 * np.pi * f * x.imag)\n s = pd.Series(x.real + 1j * im, x.index, name=x.name)\n return s.rename(x.name + ' (capacitance)')\n\n# plot\n\ndef polar(gm, figsize=(6, 6), color='r', rmax=1.0, lw=2):\n import matplotlib.pyplot as plt\n fig = plt.figure(figsize=figsize)\n ax = plt.subplot(polar=True)\n ax.set_title(gm.name)\n ax.plot(np.angle(gm), np.abs(gm), color, lw=lw)\n if rmax: ax.set_rmax(rmax)\n fig.tight_layout()\n plt.show()\n\ndef bode(gm, figsize=(10, 6), color=['r', 'b'], ylim=[], lw=2, log=False):\n import matplotlib.pyplot as plt\n fig, ax = plt.subplots(figsize=figsize)\n ax.set_title(gm.name)\n ax.set_xlabel('frequency')\n\n ax.plot(gm.index, 10 * np.log10(np.abs(gm)), color[0], lw=lw)\n ax.set_ylabel('gain (db)', color=color[0])\n ax.tick_params('y', colors=color[0])\n if ylim: ax.set_ylim(ylim[0])\n if log: ax.set_xscale('log')\n\n ax = ax.twinx()\n ax.plot(gm.index, np.degrees(np.angle(gm)), color[1], lw=lw)\n ax.set_ylabel('phase (deg)', color=color[1])\n ax.tick_params('y', colors=color[1])\n if ylim: ax.set_ylim(ylim[1])\n if log: ax.set_xscale('log')\n\n fig.tight_layout()\n plt.show()\n\ndef plot(gm, figsize=(10, 6), color=['r', 'b'], ylim=[], lw=2, log=False):\n import matplotlib.pyplot as plt\n fig, ax = plt.subplots(figsize=figsize)\n ax.set_title(gm.name)\n ax.set_xlabel('frequency')\n\n ax.plot(gm.index, np.real(gm), color[0], lw=lw)\n ax.set_ylabel('real', color=color[0])\n ax.tick_params('y', colors=color[0])\n if ylim: ax.set_ylim(ylim[0])\n if log: ax.set_xscale('log')\n\n ax = ax.twinx()\n ax.plot(gm.index, np.imag(gm), color[1], lw=lw)\n ax.set_ylabel('imag', color=color[1])\n ax.tick_params('y', colors=color[1])\n if ylim: ax.set_ylim(ylim[1])\n if log: ax.set_xscale('log')\n\n fig.tight_layout()\n plt.show()\n\ndef cartesian(gm, figsize=(10, 6), color='r', ylim=None, lw=2):\n import matplotlib.pyplot as plt\n fig, ax = plt.subplots(figsize=figsize)\n ax.set_title(gm.name)\n ax.plot(np.real(gm), np.imag(gm), color, lw=lw)\n ax.set_xlabel('real')\n ax.set_ylabel('imag', color=color)\n if ylim: ax.set_ylim(ylim)\n fig.tight_layout()\n plt.show()\n\n\n","sub_path":"pyvna.py","file_name":"pyvna.py","file_ext":"py","file_size_in_byte":12234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"599885935","text":"# -*- coding: utf-8 -*-\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom django.utils.datetime_safe import datetime\nfrom jamifactory.home.models import get_or_none\nfrom jamifactory.main.models import PlanDiagnostic, Question, PlanUnit4, PlanTraining\nfrom jamifactory.plan.models import Plan, Schedule, Lesson\nfrom jamifactory.study.models import PlanDiagnosticRecord, PlanUnit4Record, PlanTrainingRecord\n\n\ndef study(request):\n user = request.user\n\n plan = []\n lesson = Lesson.objects.filter(user=user)\n for l in lesson :\n plans = Plan.objects.filter(lesson=l)\n schedules = Schedule.objects.filter(lesson=l).order_by(\"date_study\")\n for i in range(0,len(schedules)):\n if schedules[i].date_study == datetime.now().date() :\n plan.append(plans[i])\n\n context = {\n 'user': user,\n 'plan':plan,\n 'appname':'study'\n }\n return render(request, 'study.html', context)\n\ndef study_cards(request,pid=None):\n user = request.user\n\n plan = get_or_none(Plan,id=pid)\n trs = []\n for u4 in plan.unit.get_unit4():\n tmp = PlanTrainingRecord.objects.filter(user=user,unit__unit=u4).order_by(\"-id\")[:2]\n trs.append(tmp)\n\n context = {\n 'user': user,\n 'plan':plan,\n 'trs':trs,\n 'appname':'study_cards'\n }\n return render(request, 'study_cards.html', context)\n\ndef study_diagnostic(request,pid=None):\n user = request.user\n\n plan = get_or_none(Plan,id=pid)\n\n context = {\n 'user': user,\n 'plan':plan,\n 'appname':'study_diagnostic'\n }\n return render(request, 'study_diagnostic.html', context)\n\ndef study_question(request,pid=None):\n user = request.user\n\n plan = get_or_none(Plan,id=pid)\n\n chk = None\n group = []\n record = []\n model_name = request.POST.get('model')\n if model_name == 'Diagnostic' :\n for u4 in plan.unit.get_unit4():\n for d in u4.get_diagnostic():\n dr, created = PlanDiagnosticRecord.objects.get_or_create(plan=plan,unit=d)\n if dr :\n record.append(dr)\n group.append(d)\n chk = PlanDiagnosticRecord.objects.filter(plan=plan,unit=d,is_done=False)\n elif model_name == 'Training' :\n for u4 in plan.unit.get_unit4():\n for t in u4.get_training()[:2]:\n tr = PlanTrainingRecord.objects.filter(user=user,unit=t,is_done=True)\n if tr :\n tr = PlanTrainingRecord.objects.filter(user=user,unit=t,is_done=True)[0]\n else:\n tr, created = PlanTrainingRecord.objects.get_or_create(user=user,unit=t,is_done=False)\n if tr :\n record.append(tr)\n group.append(t)\n chk = PlanTrainingRecord.objects.filter(user=user,unit=t,is_done=False).order_by(\"-id\")[:2]\n\n context = {\n 'user': user,\n 'plan':plan,\n 'group':group,\n 'record':record,\n 'model_name':model_name,\n 'appname':'study_solve'\n }\n\n if chk :\n return render(request, 'study_question.html', context)\n return render(request, 'study_result.html', context)\n\ndef study_autosave(request):\n plan = get_or_none(Plan,id=request.POST.get(\"pid\"))\n answer = request.POST.get(\"answer\")\n if request.POST.get(\"mode\") == \"Diagnostic\" :\n diagnostic = get_or_none(PlanDiagnostic,id=request.POST.get(\"gid\"))\n if diagnostic:\n dr, created = PlanDiagnosticRecord.objects.get_or_create(plan=plan,unit=diagnostic,is_done=False)\n if dr :\n dr.answer = answer\n dr.save()\n return HttpResponse(\"Done\")\n elif request.POST.get(\"mode\") == \"Training\" :\n training = get_or_none(PlanTraining,id=request.POST.get(\"gid\"))\n if training:\n tr, created = PlanTrainingRecord.objects.get_or_create(user=request.user,unit=training,is_done=False)\n if tr :\n tr.answer = answer\n tr.save()\n return HttpResponse(\"Done\")\n return HttpResponse(\"Fail\")\n\ndef study_submit(request):\n rids = request.POST.get(\"rids\")\n mode = request.POST.get(\"mode\")\n if rids :\n rids = rids.split(\",\")\n for rid in rids:\n if mode == \"Diagnostic\" :\n dr = get_or_none(PlanDiagnosticRecord,id=rid)\n if dr:\n dr.is_done = True\n dr.save()\n elif mode == \"Training\" :\n tr = get_or_none(PlanTrainingRecord,id=rid)\n if tr:\n tr.is_done = True\n tr.save()\n return HttpResponse(\"Done\")\n return HttpResponse(\"Fail\")\n\ndef study_explain(request):\n user = request.user\n\n drid = request.POST.get('drid')\n trid = request.POST.get('trid')\n mrid = request.POST.get('mrid')\n urid = request.POST.get('urid')\n modal = request.POST.get('modal',1)\n\n dr = None\n\n if drid : dr = get_or_none(PlanDiagnosticRecord,id=drid)\n elif trid : dr = get_or_none(PlanTrainingRecord,id=trid)\n elif urid : dr = get_or_none(PlanUnit4Record,id=urid)\n\n context = {\n 'user': user,\n 'dr':dr,\n 'modal':modal\n }\n return render(request, 'study_explain.html', context)\n\ndef study_video(request,pid=None):\n user = request.user\n\n plan = get_or_none(Plan,id=pid)\n\n context = {\n 'user': user,\n 'plan':plan,\n 'appname':'study_video'\n }\n return render(request, 'study_video.html', context)\n\ndef study_unit(request,pid=None):\n\n unit = int(request.GET.get(\"unit\",0))\n user = request.user\n\n plan = get_or_none(Plan,id=pid)\n\n plan_slice = plan.unit.get_unit4()[unit-1]\n pr, created = PlanUnit4Record.objects.get_or_create(plan=plan,unit=plan_slice)\n\n context = {\n 'user': user,\n 'plan':plan,\n 'uid':unit,\n 'planrecord':pr,\n 'plan_slice':plan_slice,\n 'appname':'study_unit'\n }\n return render(request, 'study_unit.html', context)\n\ndef study_step(request):\n user = request.user\n\n answer = request.POST.get('answer')\n mode = request.POST.get('mode')\n\n pr = get_or_none(PlanUnit4Record,id=request.POST.get('pid'))\n\n if pr :\n if answer :\n pr.answer = answer\n if answer == pr.unit.question.answer :\n pr.is_done = True\n pr.step = 5\n if mode=='next' and len(pr.unit.question.get_explain()) >= pr.step :\n pr.step = pr.step+1\n pr.save()\n\n context = {\n 'user': user,\n 'planrecord':pr,\n 'answer':answer,\n 'appname':'study_unit'\n }\n return render(request, 'study_step.html', context)\n\ndef study_training(request,pid=None):\n user = request.user\n\n plan = get_or_none(Plan,id=pid)\n\n context = {\n 'user': user,\n 'plan':plan,\n 'appname':'study_training'\n }\n return render(request, 'study_training.html', context)\n\ndef study_exit(request,pid=None):\n user = request.user\n\n plan = get_or_none(Plan,id=pid)\n\n trs = []\n for u4 in plan.unit.get_unit4():\n tmp = PlanTrainingRecord.objects.filter(user=user,unit__unit=u4).order_by(\"-id\")[:2]\n trs.append(tmp)\n\n context = {\n 'user': user,\n 'plan':plan,\n 'trs':trs,\n 'appname':'study_exit'\n }\n return render(request, 'study_exit.html', context)","sub_path":"jamifactory/study/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"173957938","text":"\"\"\"\n抓取天气\n\n\"\"\"\n\nfrom lxml import etree\nimport requests\n\ndef requst_temperature():\n # 中国天气网\n url = 'http://www.weather.com.cn/weather1d/101190101.shtml#input'\n # request发起请求\n with requests.get(url) as res:\n content = res.content\n # 使用lxml的extree解析页面\n html = etree.HTML(content)\n # 通过xpath定位周边城市和景区,返回list\n location = html.xpath('//*[@id=\"around\"]//a[@target=\"_blank\"]/span/text()')\n # 温度list\n temperature = html.xpath('//*[@id=\"around\"]/div/ul/li/a/i/text()')\n # 将上述两个list作业key和value合成字典\n dictionary = dict(zip(location, temperature))\n return dictionary\n\nif __name__ == '__main__':\n print(requst_temperature())","sub_path":"语法基础/Day47/抓取天气.py","file_name":"抓取天气.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"609068587","text":"# -*- coding: utf-8 -*-\n#\n# ramstk.controllers.manager.py is part of The RAMSTK Project\n#\n# All rights reserved.\n# Copyright 2007 - 2020 Doyle Rowland doyle.rowland reliaqual com\n\"\"\"Hardware Controller Package analysis manager.\"\"\"\n\n# Standard Library Imports\nimport inspect\nfrom typing import Any, Dict, List\n\n# Third Party Imports\n# noinspection PyPackageRequirements\nimport treelib\nfrom pubsub import pub\n\n# RAMSTK Package Imports\nfrom ramstk.configuration import RAMSTKUserConfiguration\nfrom ramstk.db.base import BaseDatabase\n\n\nclass RAMSTKAnalysisManager:\n \"\"\"Contain the attributes and methods of an analysis manager.\n\n This class manages the analyses for RAMSTK modules. Attributes of the\n analysis manager are:\n\n :ivar dict _attributes: the dict used to hold the aggregate attributes for\n the hardware item being analyzed.\n :ivar tree: the treelib Tree() used to hold a copy of the data manager's\n tree. This do not remain in-sync automatically.\n :type tree: :class:`treelib.Tree`\n :ivar RAMSTK_USER_CONFIGURATION: the instance of the\n RAMSTKUserConfiguration class associated with this analysis manager.\n :type RAMSTK_USER_CONFIGURATION: :class:`ramstk.RAMSTKUserConfiguration`\n \"\"\"\n\n RAMSTK_USER_CONFIGURATION = None\n\n # pylint: disable=unused-argument\n # noinspection PyUnusedLocal\n def __init__(self, configuration: RAMSTKUserConfiguration,\n **kwargs: Dict[str, Any]) -> None:\n \"\"\"Initialize an instance of the hardware analysis manager.\n\n :param configuration: the RAMSTKUserConfiguration instance associated\n with the current instance of the RAMSTK application.\n :type configuration: :class:`ramstk.RAMSTKUserConfiguration`\n \"\"\"\n # Initialize private dictionary attributes.\n self._attributes: Dict[str, Any] = {}\n\n # Initialize private list attributes.\n\n # Initialize private scalar attributes.\n self._tree: treelib.Tree = treelib.Tree()\n\n # Initialize public dictionary attributes.\n\n # Initialize public list attributes.\n\n # Initialize public scalar attributes.\n self.RAMSTK_USER_CONFIGURATION = configuration\n\n def on_get_all_attributes(self, attributes: Dict[str, Any]) -> None:\n \"\"\"Set all the attributes for the analysis manager.\n\n :param attributes: the data manager's attributes dict.\n :return: None\n :rtype: None\n \"\"\"\n self._attributes = attributes\n\n def on_get_tree(self, tree: treelib.Tree) -> None:\n \"\"\"Set the analysis manager's treelib Tree().\n\n :param tree: the data manager's treelib Tree().\n :return: None\n :rtype: None\n \"\"\"\n self._tree = tree\n\n\nclass RAMSTKDataManager:\n \"\"\"The meta-class for all RAMSTK Data Managers.\n\n :ivar tree: the treelib Tree()that will contain the structure of the RAMSTK\n module being modeled.\n :type tree: :class:`treelib.Tree`\n \"\"\"\n\n # Define private dictionary class attributes.\n\n # Define private list class attributes.\n\n # Define private scalar class attributes.\n _root = 0\n _tag = ''\n\n # Define public dictionary class attributes.\n\n # Define public list class attributes.\n\n # Define public scalar class attributes.\n\n # pylint: disable=unused-argument\n # noinspection PyUnusedLocal\n def __init__(self, **kwargs: Dict[str, Any]) -> None:\n \"\"\"Initialize an RAMSTK data model instance.\"\"\"\n # Initialize private dictionary attributes.\n self._pkey: Dict[str, List[str]] = {}\n\n # Initialize private list attributes.\n\n # Initialize private scalar attributes.\n self._parent_id: int = 0\n self._revision_id: int = 0\n\n # Initialize public dictionary attributes.\n\n # Initialize public list attributes.\n\n # Initialize public scalar attributes.\n self.dao: BaseDatabase = BaseDatabase()\n self.last_id: int = 0\n self.tree: treelib.Tree = treelib.Tree()\n\n # Add the root to the Tree(). This is necessary to allow multiple\n # entries at the top level as there can only be one root in a treelib\n # Tree(). Manipulation and viewing of a RAMSTK module tree needs to\n # ignore the root of the tree.\n self.tree.create_node(tag=self._tag, identifier=self._root)\n\n # Subscribe to PyPubSub messages.\n pub.subscribe(self.do_connect, 'succeed_connect_program_database')\n pub.subscribe(self.do_update_all, 'request_save_project')\n pub.subscribe(self.do_set_tree,\n 'succeed_calculate_{0}'.format(self._tag))\n\n pub.subscribe(self._on_select_revision, 'selected_revision')\n\n def do_connect(self, dao: BaseDatabase) -> None:\n \"\"\"Connect data manager to a database.\n\n :param dao: the BaseDatabase() instance (data access object)\n representing the connected RAMSTK Program database.\n :type dao: :class:`ramstk.db.base.BaseDatabase`\n \"\"\"\n self.dao = dao\n\n def do_create_all_codes(self, prefix: str) -> None:\n \"\"\"Create codes for all MODULE data table records.\n\n :param prefix: the string to use as a prefix for each code.\n :return: None\n :rtype: None\n \"\"\"\n for _node in self.tree.all_nodes():\n # noinspection PyUnresolvedReferences\n self.do_create_code(_node.identifier, prefix) # type: ignore\n\n def do_delete(self, node_id: int, table: str) -> None:\n \"\"\"Remove a RAMSTK data table record.\n\n :param node_id: the node ID to be removed from the RAMSTK Program\n database.\n :param table: the key in the module's treelib Tree() data package\n for the RAMSTK data table to remove the record from.\n :return: None\n :rtype: None\n \"\"\"\n return self.dao.do_delete(self.do_select(node_id, table))\n\n def do_get_attributes(self, node_id: int, table: str) -> None:\n \"\"\"Retrieve the RAMSTK data table attributes for node ID.\n\n :param node_id: the node ID in the treelib Tree to get the\n attributes for.\n :param table: the RAMSTK data table to retrieve the attributes from.\n :return: None\n :rtype: None\n \"\"\"\n try:\n pub.sendMessage(\n 'succeed_get_{0}_attributes'.format(table),\n attributes=self.do_select(node_id,\n table=table).get_attributes(),\n )\n except AttributeError:\n _method_name = inspect.currentframe( # type: ignore\n ).f_code.co_name\n _error_msg = ('{0}: No attributes found for record ID {1} in '\n '{2} table.'.format(_method_name, node_id, table))\n pub.sendMessage(\n 'do_log_debug',\n logger_name='DEBUG',\n message=_error_msg,\n )\n pub.sendMessage(\n 'fail_get_{0}_attributes'.format(table),\n error_message=_error_msg,\n )\n\n def do_select(self, node_id: Any, table: str) -> Any:\n \"\"\"Retrieve the RAMSTK data table record for the Node ID passed.\n\n :param node_id: the Node ID of the data package to retrieve.\n :param table: the name of the RAMSTK data table to retrieve the\n attributes from.\n :return: the instance of the RAMSTK data table that was\n requested or None if the requested Node ID does not exist.\n :raise: KeyError if passed the name of a table that isn't managed by\n this manager.\n \"\"\"\n try:\n _entity = self.tree.get_node(node_id).data[table]\n except (AttributeError, treelib.tree.NodeIDAbsentError, TypeError):\n _method_name = inspect.currentframe( # type: ignore\n ).f_code.co_name\n _error_msg: str = (\n '{2}: No data package for node ID {0} in module {1}.'.format(\n node_id, table, _method_name))\n pub.sendMessage(\n 'do_log_debug',\n logger_name='DEBUG',\n message=_error_msg,\n )\n _entity = None\n\n return _entity\n\n def do_set_attributes(self, node_id: List, package: Dict[str,\n Any]) -> None:\n \"\"\"Set the attributes of the record associated with node ID.\n\n :param node_id: the ID of the record in the RAMSTK Program database\n table whose attributes are to be set.\n :param package: the key:value pair of the attribute to set.\n :return: None\n :rtype: None\n \"\"\"\n [[_key, _value]] = package.items()\n\n for _table in self._pkey:\n try:\n _attributes = self.do_select(node_id[0],\n table=_table).get_attributes()\n except (AttributeError, KeyError):\n _method_name = inspect.currentframe( # type: ignore\n ).f_code.co_name\n _error_msg: str = (\n '{2}: No data package for node ID {0} in module {'\n '1}.'.format(node_id[0], _table, _method_name))\n pub.sendMessage(\n 'do_log_debug',\n logger_name='DEBUG',\n message=_error_msg,\n )\n _attributes = {}\n\n for _field in self._pkey[_table]:\n try:\n _attributes.pop(_field)\n except KeyError:\n pass\n\n if _key in _attributes:\n _attributes[_key] = _value\n\n self.do_select(node_id[0],\n table=_table).set_attributes(_attributes)\n\n # noinspection PyUnresolvedReferences\n self.do_get_tree() # type: ignore\n\n def do_set_tree(self, tree: treelib.Tree) -> None:\n \"\"\"Set the MODULE treelib Tree().\n\n This method is generally used to respond to events such as successful\n calculations of the entire system.\n\n :param tree: the treelib Tree() to assign to the tree attribute.\n :return: None\n :rtype: None\n \"\"\"\n self.tree = tree\n\n # noinspection PyUnresolvedReferences\n def do_update_all(self) -> None:\n \"\"\"Update all MODULE data table records in the RAMSTK Program database.\n\n :return: None\n :rtype: None\n \"\"\"\n for _node in self.tree.all_nodes():\n self.do_update(_node.identifier) # type: ignore\n pub.sendMessage('succeed_update_all')\n\n def _on_select_revision(self, attributes: Dict[str, Any]) -> None:\n \"\"\"Set the revision ID for the data manager.\"\"\"\n self._revision_id = attributes['revision_id']\n","sub_path":"src/ramstk/controllers/managers.py","file_name":"managers.py","file_ext":"py","file_size_in_byte":10853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"165900642","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 2 22:38:55 2020\n\n@author: Sajjad\n\"\"\"\n\nimport cv2\nimport sys\n \n#image = cv2.imread(r'E:\\sajjad university\\6th semester\\computer graphics\\jurassic-park-tour-jeep.jpg')\n#gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n \n#cv2.imshow('Original image',image)\n#cv2.imshow('Gray image', gray)\n \n#cv2.waitKey(0)\n#cv2.destroyAllWindows()\n\n\ndef faceDetectAndAlterProps():\n\n # Get user supplied values\n imagePath = r\"E:\\sajjad university\\6th semester\\computer graphics\\abba.png\"\n cascPath = r\"E:\\sajjad university\\6th semester\\computer graphics\\haarcascade_frontalface_default.xml\"\n \n # Create the haar cascade\n faceCascade = cv2.CascadeClassifier(cascPath)\n \n # Read the image\n image = cv2.imread(imagePath)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n \n # Detect faces in the image\n #.detectMultiscale detects the objects on our cascade\n #first option is the grayscale image\n #scaleFactor compensates for difference in distances between faces and camera\n faces = faceCascade.detectMultiScale(\n gray,\n scaleFactor=1.1,\n minNeighbors=5,\n minSize=(30, 30),\n #flags = cv2.cv.CV_HAAR_SCALE_IMAGE\n )\n \n print(\"Found {0} faces!\".format(len(faces)))\n \n # Draw a rectangle around the faces\n for (x, y, w, h) in faces:\n cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)\n \n cv2.imshow(\"Faces found\", image)\n cv2.imwrite(r'E:\\sajjad university\\6th semester\\computer graphics\\try.png', image)\n print(\"---------\")\n cv2.waitKey(0)\n \nfaceDetectAndAlterProps()\n \n \n ","sub_path":"BinaryToGrayScale/binaryToGrayScale.py","file_name":"binaryToGrayScale.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"311584452","text":"#!/usr/bin/python\nfrom optparse import OptionParser\n\nparser = OptionParser()\nparser.add_option(\"-i\", \"--input\", dest=\"infile\", help=\"a file with chr and position of samples that will be used\", metavar=\"FILE\")\nparser.add_option(\"-t\", \"--threads\", dest=\"nthreads\", help=\"Number of threads to used for this analysis\", metavar=\"FILE\")\nparser.add_option(\"-d\", \"--minwin\", dest=\"nminwin\", help=\"Minimum window. For more info, please read OmegaPlus Manual\", metavar=\"FILE\")\nparser.add_option(\"-u\", \"--maxwin\", dest=\"nmaxwin\", help=\"Maximum window. For more info, please read OmegaPlus Manual\", metavar=\"FILE\")\nparser.add_option(\"-s\", \"--minsnps\", dest=\"nminsnps\", help=\"Minimum SNPs. For more info, please read OmegaPlus Manual\", metavar=\"FILE\")\nparser.add_option(\"-m\", \"--memLimit\", dest=\"nmemLimit\", help=\"Limit for memory to be used\", metavar=\"FILE\")\nparser.add_option(\"-g\", \"--grid\", dest=\"ngrid\", help=\"Grid. For more info, please read OmegaPlus ManualIn case there is a grid file used, this option is ignored\", metavar=\"FILE\")\n(options, args) = parser.parse_args()\n\ninputfile=options.infile\ncmdsfile=inputfile+\".OmegaPlus.ctrl.cmd\"\n\n## args\nthreads=options.nthreads\nminwin=options.nminwin\nmaxwin=options.nmaxwin\nminsnps=options.nminsnps\nmemLimit=options.nmemLimit\nrandomseed=str(13129383)\ngrid=options.ngrid\n##\n\n\nfile = open(inputfile, \"r\")\nchr='';pos='';\ncmds=[]\n\nfor line in file:\n newlineSHIET=line.split(\"\\n\")\n values=newlineSHIET[0].split('\\t')\n chr=values[0]\n pos=values[1]\n vcffile=values[2]\n gridfile=\" -gridFile \" +values[3]\n samplefile=\" -sampleList \" +values[4]\n runID = \"chr\" + chr + \".\" + pos+\".at.\"+values[3].split(\"ctrl.\")[1]+\".run\"\n\n cmds.append(\n \"omegaplus/OmegaPlus-G -memLimit \"+memLimit+\" -minsnps \"+minsnps+\" -name \" + runID + \" -input \" + vcffile + gridfile + \" -grid \" + grid + \" -threads \" + threads + \" -minwin \" + minwin + \" -maxwin \" + maxwin + samplefile + \" -seed \" + randomseed)\n\n \nfile.close()\nfile2 = open(cmdsfile, \"w\")\nfor item in cmds:\n file2.write(str(item) + \"\\n\")\nfile2.close()\n\n","sub_path":"OmegaPlusCMDcreator.ctrl.py","file_name":"OmegaPlusCMDcreator.ctrl.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"98887393","text":"#!/usr/bin/env python\n\nfrom os.path import dirname, abspath, join as pjoin\n\nimport pytest\nimport numpy as np\n\nfrom Corrfunc.tests.common import gals_Mr19\nfrom Corrfunc.tests.common import (check_against_reference,\n check_vpf_against_reference)\nfrom Corrfunc.tests.common import generate_isa_and_nthreads_combos\n\n\n@pytest.mark.parametrize('isa,nthreads', generate_isa_and_nthreads_combos())\ndef test_DD(gals_Mr19, isa, nthreads):\n from Corrfunc.theory import DD\n \n boxsize = 420.\n binfile = pjoin(dirname(abspath(__file__)),\n \"../../theory/tests/\", \"bins\")\n autocorr = 1\n periodic = 1\n \n x,y,z,w = gals_Mr19\n results_DD = DD(autocorr, nthreads, binfile, x, y, z,\n weights1=w, weight_type='pair_product',\n periodic=periodic, boxsize=boxsize,\n output_ravg=True, verbose=True,\n isa=isa)\n \n file_ref = pjoin(dirname(abspath(__file__)),\n \"../../theory/tests/\", \"Mr19_DD_periodic\")\n check_against_reference(results_DD, file_ref,\n ravg_name='ravg', ref_cols=(0, 4, 1))\n \n\n@pytest.mark.parametrize('isa,nthreads', generate_isa_and_nthreads_combos())\ndef test_DDrppi(gals_Mr19, isa, nthreads):\n from Corrfunc.theory import DDrppi\n \n boxsize = 420.\n pimax = 40.0\n binfile = pjoin(dirname(abspath(__file__)),\n \"../../theory/tests/\", \"bins\")\n autocorr = 1\n periodic = 1\n \n x,y,z,w = gals_Mr19\n results_DDrppi = DDrppi(autocorr, nthreads, pimax, binfile, x, y, z,\n weights1=w, weight_type='pair_product',\n periodic=periodic, boxsize=boxsize,\n output_rpavg=True, verbose=True,\n isa=isa)\n \n file_ref = pjoin(dirname(abspath(__file__)),\n \"../../theory/tests/\", \"Mr19_DDrppi_periodic\")\n check_against_reference(results_DDrppi, file_ref, ravg_name='rpavg', ref_cols=(0, 4, 1))\n\n \n@pytest.mark.parametrize('isa,nthreads', generate_isa_and_nthreads_combos())\ndef test_DDsmu(gals_Mr19, isa, nthreads):\n from Corrfunc.theory import DDsmu\n \n boxsize = 420.\n binfile = pjoin(dirname(abspath(__file__)),\n \"../../theory/tests/\", \"bins\")\n autocorr = 1\n periodic = 1\n mu_max = 0.5\n nmu_bins = 10\n \n x,y,z,w = gals_Mr19\n results_DDsmu = DDsmu(autocorr, nthreads, binfile,\n mu_max, nmu_bins,\n x, y, z,\n weights1=w, weight_type='pair_product',\n periodic=periodic, boxsize=boxsize,\n output_savg=True, verbose=True,\n isa=isa)\n \n file_ref = pjoin(dirname(abspath(__file__)),\n \"../../theory/tests/\", \"Mr19_DDsmu_periodic\")\n check_against_reference(results_DDsmu, file_ref, ravg_name='savg', ref_cols=(0, 4, 1))\n \n \n@pytest.mark.parametrize('isa,nthreads', generate_isa_and_nthreads_combos(extra_isa=['AVX2']))\ndef test_wp(gals_Mr19, isa, nthreads):\n from Corrfunc.theory import wp\n \n boxsize = 420.\n pimax = 40.\n binfile = pjoin(dirname(abspath(__file__)),\n \"../../theory/tests/\", \"bins\")\n \n x,y,z,w = gals_Mr19\n results_wp = wp(boxsize, pimax, nthreads, binfile,\n x, y, z,\n weights=w, weight_type='pair_product',\n output_rpavg=True, verbose=True,\n isa=isa)\n \n file_ref = pjoin(dirname(abspath(__file__)),\n \"../../theory/tests/\", \"Mr19_wp\")\n check_against_reference(results_wp, file_ref, ravg_name='rpavg', cf_name='wp',\n ref_cols=(4, 5, 1, 0))\n \n\n@pytest.mark.parametrize('isa,nthreads', generate_isa_and_nthreads_combos())\ndef test_xi(gals_Mr19, isa, nthreads):\n from Corrfunc.theory import xi\n \n boxsize = 420.\n binfile = pjoin(dirname(abspath(__file__)),\n \"../../theory/tests/\", \"bins\")\n \n x,y,z,w = gals_Mr19\n results_xi = xi(boxsize, nthreads, binfile,\n x, y, z,\n weights=w, weight_type='pair_product',\n output_ravg=True, verbose=True,\n isa=isa)\n \n file_ref = pjoin(dirname(abspath(__file__)),\n \"../../theory/tests/\", \"Mr19_xi\")\n check_against_reference(results_xi, file_ref, ravg_name='ravg', cf_name='xi', ref_cols=(4, 5, 1, 0))\n \n\n@pytest.mark.parametrize('isa,nthreads', generate_isa_and_nthreads_combos())\ndef test_vpf(gals_Mr19, isa, nthreads):\n from Corrfunc.theory import vpf\n \n boxsize = 420.\n rmax = 10.0\n nbin = 10\n nspheres = 10000\n num_pN = 6\n seed = -1234\n periodic = 1\n \n x,y,z,w = gals_Mr19\n results_vpf = vpf(rmax, nbin, nspheres, num_pN,\n seed, x, y, z, verbose=True, periodic=periodic,\n boxsize=boxsize)\n #results_vpf = results_vpf.view(dtype=np.float64).reshape(nbin,-1) # flatten to same shape as results\n file_ref = pjoin(dirname(abspath(__file__)),\n \"../../theory/tests/\", \"Mr19_vpf_periodic\")\n check_vpf_against_reference(results_vpf, file_ref)\n","sub_path":"Corrfunc/tests/test_theory.py","file_name":"test_theory.py","file_ext":"py","file_size_in_byte":5430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"468277594","text":"#!/usr/bin/env python\n\"\"\"\n\nThis is a convenience script for the generation of 6 hour data block files. \nIt needs the location of a folder with time series and the sampling period as arguments.\n\nThe time series files have to be named in the EDL-ascii output standard, \nwhich codes stationname and start time of the file in the name. \n\nThe data have to be either single column values or in 2-column form.\n\n wrapper for the generation of dayfiles for EDL data.\n\n 2 mandatory arguments: \n - path to files \n - sampling interval (in seconds)\n\n 3 optional arguments:\n - name of the output directory - cannot start with '-' \n - stationname - cannot start with '-' \n - flag '-R (or -r)', if the directory shall be searched for data recursively \n\n\"\"\"\n\n\nimport sys, os\nimport os.path as op\nimport mtpy.utils.exceptions as MTex\n\nimport mtpy.utils.filehandling as MTfh\nreload(MTfh)\n\n\ndef main():\n\n #print '\\n\\tnot working yet - code under development !!\\n'\n #return\n\n if len(sys.argv) < 3:\n sys.exit('\\nNeed at least 4 arguments: \\n\\n '\n ' \\n \\n'\n ' \\n \\n'\n '[optional: ]\\n'\n '(set this option for including all subfolders)\\n\\n')\n\n print() \n\n outdir = None\n stationname = None\n recursive = False\n\n multiple_stations = False\n\n if len(sys.argv) > 3:\n optionals = sys.argv[3:]\n for o in optionals:\n o = o.strip()\n if o[0] == '-':\n if o[1].lower() == 'r':\n recursive = True\n continue\n elif outdir is None:\n outdir = o\n continue\n elif stationname is None:\n stationname = o \n continue\n \n if stationname is not None:\n #check, if it's actually a comma-separated list:\n try:\n stationlist = stationname.split(',')\n if len(stationlist) > 1:\n multiple_stations = True\n stationlist = [i.upper() for i in stationlist]\n except:\n stationlist = [stationname]\n else: stationlist = [None]\n\n print(stationlist) \n\n pathname_raw = sys.argv[1]\n pathname = op.abspath(op.realpath(pathname_raw))\n\n if not op.isdir(pathname):\n sys.exit('Data file(s) path not existing: {0}\\n'.format(pathname))\n\n try:\n sampling = float(sys.argv[2])\n if sampling <= 0 : raise\n except:\n sys.exit('Second argument must be sampling interval in seconds (int/float)')\n\n if recursive is True:\n lo_folders = []\n for i,j,k in os.walk(pathname):\n lof = [op.abspath(op.join(i,f)) for f in j] \n if stationname is not None:\n for stationname in stationlist:\n for curr_folder in lof:\n content_of_folder = os.listdir(curr_folder)\n #print curr_folder\n lof_station = [i for i in content_of_folder if stationname.lower() in i.lower()]\n if len(lof_station) > 0 :\n lo_folders.append(curr_folder)\n pathname = list(set(lo_folders))\n\n if len(pathname) == 0:\n sys.exit('\\n\\tERROR - No (sub-) folders for stations {0} found\\n'.format(stationlist))\n\n\n \n for stationname in stationlist:\n print('....\\n')\n print('processing station ',stationname.upper())\n # if pathname[0] is not None:\n # station_pathname = [i for i in pathname if stationname.lower() in i.lower()]\n # if len(station_pathname) == 0:\n # station_pathname = None\n # else:\n station_pathname = pathname\n \n try:\n MTfh.EDL_make_Nhour_files(6,station_pathname, sampling, stationname.upper(), outdir)\n except MTex.MTpyError_inputarguments:\n if stationname is None:\n sys.exit('\\n\\tERROR - No data found in (sub-)folders\\n')\n else:\n sys.exit('\\n\\tERROR - No data found in (sub-)folders for station {0}\\n'.format(stationname.upper()))\n except MemoryError:\n sys.exit('\\n\\tERROR - Not enough memory to store temporary arrays!\\n')\n except IOError:\n sys.exit('\\n\\tERROR - Not enough space on local disk to store output!\\n')\n\n except:\n sys.exit('\\n\\tERROR - could not process (sub-)folders')\n print('\\n')\n\n\n\nif __name__=='__main__':\n main()\n","sub_path":"mtpy/uofa/EDLmake6hourfiles.py","file_name":"EDLmake6hourfiles.py","file_ext":"py","file_size_in_byte":4574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"401075164","text":"# -*- coding: utf-8 -*-\nimport eyed3\nimport csv\n\n#Remove logs\neyed3.log.setLevel(\"ERROR\")\nwith open('Data/Raw/subset_train.csv', mode='r') as csv_file:\n genreData = csv.DictReader(csv_file)\n line_count = 0\n for row in genreData:\n line_count += 1\n print('Processed {0} lines.'.format(line_count))\n\ndef isMono(filename):\n\taudiofile = eyed3.load(filename)\n\treturn audiofile.info.mode == 'Mono'\n\ndef getGenre(filename):\n\treturn None\n\n\n\t","sub_path":"audioFilesTools.py","file_name":"audioFilesTools.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"342924678","text":"import uuid\n\nfrom django.conf import settings\nfrom django.urls import reverse\n\n\ndef jstags(request):\n return {\n 'mqtt_broker': {\n 'host': settings.MQTT['BROKER_WEBSOCKETS_HOST'],\n 'port': int(settings.MQTT['BROKER_WEBSOCKETS_PORT'])\n },\n 'client_id': 'javascript_client_' + uuid.uuid4().hex,\n 'admin_urls': [reverse('login:list-user'),\n reverse('login:list-group'),\n reverse('equipment:list'),\n reverse('equipment:list-set'),\n reverse('ambulance:location_list'),\n reverse('login:list-client'),\n reverse('login:restart')],\n 'map_provider': {\n 'provider': settings.MAP_PROVIDER,\n 'access_token': settings.MAP_PROVIDER_TOKEN\n },\n }\n\n","sub_path":"mqtt/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"349639308","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# DISMISSAL : All paths, variables, columns and data have been changed in order to keep privacy untouched\n# GOAL : This script returns a XLSX file with the data about how many money in prepayment terms have the salesmen got during a period of time\n# EXTRA NOTE : This script was substitued by an SQL query in MySQL in my workplace to avoid downloading the Excel files each month but still it has proven its worth\n\nimport pandas as pd\n\n# inv is the file where the invoices data is collected, as in SAP or SAGE\ninv = pd.read_excel('C:\\\\ACCOUNTING\\\\2019\\\\Clients\\\\invoices.xlsx')\n# port is the file where the payment portfolio data is collected, where we can see if an invoice has been paid\nport = pd.read_excel('C:\\\\ACCOUNTING\\\\2019\\\\Clients\\\\portfolio.xlsx')\n# com is the file where the data about the salesmen and their corresponding clients is collected\ncom = pd.read_excel('C:\\\\ACCOUNTING\\\\2019\\\\Clients\\\\commercial.xlsx')\n# producc is the file where the production data is collected, how much each commercial has produced during the year\nproducc = pd.read_excel('C:\\\\ACCOUNTING\\\\2019\\\\Clients\\\\production.xlsx')\n\n\n###### We merge all the files into a single DataFrame according to the invoice number, and the company name\n# Please take a look at your df.info() before selecting the columns to match in order to avoid errors\ncompl = pd.merge(left=inv, right=port, how='inner',left_on='Invoice Nº',right_on='Invoice').merge(right=com, how='outer',left_on='Company', right_on='Company_Name')\n\n###### Here we will state the period of time we will take into consideration\nfilt = (compl['Received Date'] >= '07-01-2019') & (compl['Received Date'] < '08-01-2019')\n\n###### I create a dummy column called Check where I put OK if the payment was received before 5 days after the invoice and Not OK if it was received after\ncompl['Payment Days'] = compl['Received Date'] - compl['Invoice Date']\ncompl['Check'] = compl['Payment Days'].dt.days.apply(lambda x: \"OK\" if x<=5 else \"Not OK\")\n\n###### Finally we decide which columns to include in our file in order to avoid giving too much information to our HR department\n\ndefinitive = compl[['Company_Name','Invoice Series','Invoice Nº','Amount','Invoice Date','Received Date','Payment Days','Check','Commercial']]\n\n# path being where to save our excel file\npath = 'C:\\\\ACCOUNTING\\\\2019\\\\Clients\\\\prepayment_file.xlsx'\ndefinitive.to_excel(path)\n\n##### To finish the script, it shows us the total amount for commercial for that month \nprint(definitivo.groupby('Comercial')['Amount'].sum())\n","sub_path":"PrepaymentFiles.py","file_name":"PrepaymentFiles.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"617738597","text":"from django.shortcuts import render\r\n\r\nposts = [\r\n {\r\n 'author': 'Siren',\r\n 'title': 'Blog1',\r\n 'content':'First',\r\n 'date_posted': 'August 27, 2018'\r\n },\r\n {\r\n 'author': 'Smiley',\r\n 'title': 'Blog2',\r\n 'content':'Second',\r\n 'date_posted': 'August 90, 2019',\r\n }\r\n]\r\n\r\n\r\ndef home(request):\r\n\tcontext = {\r\n\t 'posts': posts\r\n\t}\r\n\treturn render(request, 'blog/home.html', context)\r\n #return HttpResponse(\"

    Blog Home

    \") \r\n\r\ndef about(request):\r\n return render(request, 'blog/about.html', {'title': 'About'})\r\n #return HttpResponse(\"

    About

    \") \r\n\r\n\r\n\r\n","sub_path":"Mystore/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"513338544","text":"#!/usr/bin/env python\n\n#Copyright 2011 Tom Galvin\n\n#This is free software: you can redistribute it \n#and/or modify it under the terms of the GNU General Public License \n#as published by the Free Software Foundation, either version 3 of \n#the License, or (at your option) any later version.\n\n#It is distributed in the hope that it will be useful, \n#but WITHOUT ANY WARRANTY; without even the implied warranty of \n#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. \n#See the GNU General Public License for more details.\n\nimport binascii\nimport re\n\ndef _hex_to_ascii(match): \n return binascii.unhexlify(match.group()[1:]) \n\ndef _unhexify(raw_data):\n pattern = re.compile(r'%(\\w{2})')\n return pattern.sub(_hex_to_ascii, raw_data)\n\ndef get_coords(raw_data):\n \"\"\"\n Specifics for parsing the CellAgentSimple txt message\n http://www.gsmesh.com/en/cellagent/simple\n \"\"\"\n ascii_data = _unhexify(raw_data)\n latitude, longitude = None, None\n lat_match = re.search(\"Latitude.*?\\d+.\\d+\" , ascii_data)\n if lat_match:\n latitude = float(re.search(\"-?\\d+.\\d+\", lat_match.group()).group())\n long_match = re.search(\"Longitude.*?\\d+.\\d+\" , ascii_data)\n if long_match:\n longitude = float(re.search(\"-?\\d+.\\d+\", long_match.group()).group())\n return latitude, longitude\n","sub_path":"whereswally/txtlocal/get_coords.py","file_name":"get_coords.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"189022581","text":"import os\n\nimport h5py\nimport numpy as np\nfrom torch.utils.data import Dataset\n\n\nclass PCamLoader(Dataset):\n def __init__(self, data_path='data/', mode='train', transform=None):\n self.data_path = data_path\n self.transform = transform\n self.mode = mode\n\n self.data = []\n self.labels = []\n self._init_loader()\n\n def __len__(self):\n return len(self.labels)\n\n def __getitem__(self, idx):\n sample_train = self.data[idx]\n label_train = self.labels[idx]\n\n if self.transform:\n sample_train = self.transform(sample_train)\n label_train = self.transform(label_train)\n\n return sample_train, label_train\n\n def _init_loader(self):\n if self.mode == 'train':\n batch_list = [\n 'camelyonpatch_level_2_split_train_x.h5',\n 'camelyonpatch_level_2_split_train_y.h5'\n ]\n elif self.mode == 'valid':\n batch_list = [\n 'camelyonpatch_level_2_split_valid_x.h5',\n 'camelyonpatch_level_2_split_valid_y.h5'\n ]\n else:\n batch_list = [\n 'camelyonpatch_level_2_split_test_x.h5',\n 'camelyonpatch_level_2_split_test_y.h5'\n ]\n\n data_file, label_file = batch_list\n\n self.data = np.array(extract_hdf5(\n os.path.join(self.data_path, data_file)\n )['x'][:, 32:64, 32:64, :],\n dtype=np.float32).swapaxes(1, 2).swapaxes(1, 3)\n\n self.labels = np.array(\n extract_hdf5(os.path.join(self.data_path, label_file))['y'],\n ).astype(np.long).reshape(-1)\n\n return 0\n\n\ndef extract_hdf5(filename):\n f = h5py.File(filename, 'r')\n return f\n","sub_path":"PCam - Pretrained - KNN/dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"322529225","text":"from TeamPokerMainApp.PokerGame.Multiplayer.NetworkPacket import *\nfrom TeamPokerMainApp.Common.VariableDefinitions import *\nfrom TeamPokerMainApp.Common.MethodDefinitions import *\nimport threading\nimport socket\n\n\nclass MultiplayerServerClass:\n\n def __init__(self, ip, port):\n self._network_packet = NetworkPacketClass()\n self.server_data_dict = dict.copy(self._network_packet.get_game_data())\n self.mutex = QMutex()\n self.conn_player_number = 0\n self.conn_players_adresses = [0 for x in range(MAX_CLIENTS)]\n self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n self.s.bind((ip, port))\n except socket.error as e:\n str(e)\n self.s.listen(MAX_CLIENTS)\n print(\"Server Started... Waiting for a connection\")\n thread = threading.Thread(target=self.server_listening_for_new_connections_loop, args=())\n thread.start()\n\n def server_listening_for_new_connections_loop(self):\n while True:\n conn, addr = self.s.accept()\n self.conn_players_adresses[self.conn_player_number] = addr # save the connected player info\n print(f'SERVER: New Connection Established. Client (C{self.conn_player_number}) from {self.conn_players_adresses[DEALER]}.')\n thread = threading.Thread(target=self.main_communication_loop, args=(conn, self.conn_player_number))\n thread.start()\n self.conn_player_number += 1\n print(f'SERVER: Active connections: {self.conn_player_number}. ')\n\n def main_communication_loop(self, conn, client_number):\n conn.send(str(client_number).encode(FORMAT))\n while True:\n try:\n # GET Client Data\n client_data = conn.recv(BUFFERSIZE).decode(FORMAT)\n client_data_dict = string_to_dict(client_data)\n\n # GET Server Data (Thread-Safe)\n while True:\n if self.mutex.tryLock():\n # Update server data from client data\n if client_number == DEALER:\n # If i'm the dealer, update everything inside.\n self.server_data_dict[\"Dealer\"] = client_data_dict[\"Dealer\"]\n self.server_data_dict[\"PlayersGame\"] = client_data_dict[\"PlayersGame\"]\n else:\n # If i'm just a player, update only my PlayersInfo\n self.server_data_dict[\"PlayersInfo\"][client_number] = client_data_dict[\"PlayersInfo\"][client_number]\n # Send the updated info back to the client:\n server_data = dict_to_string(self.server_data_dict)\n # Unlock the server_data_dict for other threads.\n self.mutex.unlock()\n break\n print(f'SERVER: Communication update finished for C{client_number}.')\n conn.sendall(server_data.encode(FORMAT))\n except socket.error as e:\n print(f'SERVER: main_communication_loop -> {e}')\n self.conn_player_number -= 1\n conn.close()\n break\n\n","sub_path":"TeamPokerMainApp/PokerGame/Multiplayer/Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":3237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"481595579","text":"import enum\nimport math\n\n\nclass Units(enum.Enum):\n customary = enum.auto()\n metric = enum.auto()\n\nclass GasketFacingSketch(enum.Enum):\n sketch_1a = enum.auto()\n sketch_1b = enum.auto()\n sketch_1c = enum.auto()\n sketch_1d = enum.auto()\n sketch_2 = enum.auto()\n sketch_3 = enum.auto()\n sketch_4 = enum.auto()\n sketch_5 = enum.auto()\n sketch_6 = enum.auto()\n\n\nclass GasketFacingSketchColumn(enum.Enum):\n column_1 = enum.auto()\n column_2 = enum.auto()\n\n\nclass FlangeType(enum.Enum):\n integral = enum.auto()\n loose = enum.auto()\n reverse_integral = enum.auto()\n reverse_loose = enum.auto()\n\n\nclass IntegralType(enum.Enum):\n # Figure 4.16.1\n no_hub = enum.auto()\n straight_hub = enum.auto()\n # Figure 4.16.2\n hub_type_1 = enum.auto()\n hub_type_2 = enum.auto()\n hub_type_3 = enum.auto()\n # Figure 4.16.3\n nut_stop_detail_A = enum.auto()\n nut_stop_detail_B = enum.auto()\n nut_stop_detail_C = enum.auto()\n nut_stop_detail_D = enum.auto()\n # Figure 4.16.4\n nut_stop_large = enum.auto()\n\n\nclass LooseType(enum.Enum):\n # Figure 4.16.5\n with_hub = enum.auto()\n without_hub = enum.auto()\n # Figure 4.16.6\n lap_with_hub = enum.auto()\n lap_no_hub = enum.auto()\n\n\n# GASKETS\nclass Div2FlangeGasketParameters:\n def __init__(\n self,\n units,\n facing_sketch,\n sketch_column,\n inner_diameter,\n outer_diameter,\n factor_m,\n factor_y,\n nubbin_width=-1,\n thickness=-1\n\n ):\n self.units = units\n self.facing_sketch = facing_sketch\n self.sketch_column = sketch_column\n self.inner_diameter = inner_diameter\n self.outer_diameter = outer_diameter\n self.factor_m = factor_m\n self.factor_y = factor_y\n self.nubbin_width = nubbin_width\n self.thickness = thickness\n\n\nclass Div2FlangeGasket:\n def __init__(self, params: Div2FlangeGasketParameters):\n self.p = params\n\n @property\n def outer_diameter(self):\n return self.p.outer_diameter\n\n @property\n def m(self):\n return self.p.factor_m\n\n @property\n def y(self):\n return self.p.factor_y\n\n def N(self):\n return (self.p.outer_diameter - self.p.inner_diameter) / 2\n\n def C_ul(self):\n if self.p.units == Units.customary:\n return 1\n elif self.p.units == Units.metric:\n return 25.4\n else:\n raise ValueError(\"Invalid value passed to units type!\")\n\n def __b_0_lower_bound(self):\n if self.p.units == Units.customary:\n return 0.25\n elif self.p.units == Units.metric:\n return 6\n else:\n raise ValueError(\"Invalid value passed to units type!\")\n\n def b(self):\n if self.b_0() <= self.__b_0_lower_bound():\n return self.b_0()\n else:\n return 0.5 * self.C_ul() * (self.b_0() / self.C_ul()) ** 0.5\n\n def b_0(self):\n if self.p.facing_sketch == GasketFacingSketch.sketch_1a or self.p.facing_sketch == GasketFacingSketch.sketch_1b:\n return self.N() / 2\n elif self.p.facing_sketch == GasketFacingSketch.sketch_1c or self.p.facing_sketch == GasketFacingSketch.sketch_1d:\n return min((self.p.nubbin_width + self.p.thickness) / 2, (self.p.nubbin_width + self.N()) / 4)\n elif self.p.facing_sketch == GasketFacingSketch.sketch_2:\n if self.p.facing_sketch == GasketFacingSketchColumn.column_1:\n return (self.p.nubbin_width + self.N()) / 4\n else:\n return (self.p.nubbin_width + 3 * self.N()) / 8\n elif self.p.facing_sketch == GasketFacingSketch.sketch_3 or self.p.facing_sketch == GasketFacingSketch.sketch_5:\n if self.p.facing_sketch == GasketFacingSketchColumn.column_1:\n return self.N() / 4\n else:\n return 3 * self.N() / 8\n elif self.p.facing_sketch == GasketFacingSketch.sketch_4:\n if self.p.facing_sketch == GasketFacingSketchColumn.column_1:\n return 3 * self.N() / 8\n else:\n return 7 * self.N() / 16\n elif self.p.facing_sketch == GasketFacingSketch.sketch_6:\n if self.p.facing_sketch == GasketFacingSketchColumn.column_1:\n return self.p.nubbin_width / 8\n else:\n raise ValueError(\"No valid value of b_0 for sketch %s and column %s\")\n\n\n# BOLTS\nclass Div2Bolt:\n def __init__(self, nominal_diameter, root_area, allowable_stress_operating, allowable_stress_ambient):\n self.nominal_diameter = nominal_diameter\n self.root_area = root_area\n self.allowable_stress_operating = allowable_stress_operating\n self.allowable_stress_ambient = allowable_stress_ambient\n\n\n\n# FLANGE\nclass Div2FlangeDesignConditions:\n def __init__(\n self,\n internal_pressure,\n allowable_stress,\n axial_load,\n bending_moment,\n units,\n flange_type,\n integral_type,\n loose_type\n ):\n\n self.internal_pressure = internal_pressure\n self.allowable_stress = allowable_stress\n self.axial_load = axial_load\n self.bending_moment = bending_moment\n self.units = units\n self.flange_type = flange_type\n self.integral_type = integral_type\n self.loose_type = loose_type\n\n\nclass Div2FlangeHubGeometry:\n def __init__(\n self,\n length,\n small_end_thickness,\n large_end_thickness\n ):\n self.h = length\n self.g_0 = small_end_thickness\n self.g1 = large_end_thickness\n\n\nclass Div2FlangeGeometry:\n def __init__(\n self,\n outer_diameter,\n bore_diameter,\n bolt_circle_diameter,\n thickness,\n number_of_bolts,\n facing_inner_diameter,\n facing_outer_diameter,\n facing_is_confined,\n number_of_splits = 0,\n hub_geometry=None\n ):\n self.A = outer_diameter\n self.B = bore_diameter\n self.C = bolt_circle_diameter\n self.t = thickness\n self.num_bolts = number_of_bolts\n self.facing_inner_diameter = facing_inner_diameter\n self.facing_outer_diameter = facing_outer_diameter\n self.confined_face = facing_is_confined\n self.fs_num = number_of_splits\n self.hub_geometry = hub_geometry\n\n\nclass Div2Flange:\n def __init__(\n self,\n conditions: Div2FlangeDesignConditions,\n geometry: Div2FlangeGeometry,\n bolts: Div2Bolt,\n gasket: Div2FlangeGasket):\n self.conditions = conditions\n self.geometry = geometry\n self.bolts = bolts\n self.gasket = gasket\n\n def G_c(self):\n return min(self.gasket.outer_diameter, self.geometry.facing_outer_diameter)\n\n def G(self):\n return self.G_c() - self.gasket.b()\n\n def W_o(self):\n load = 0.785 * (self.G() ** 2) * self.conditions.internal_pressure\n if self.gasket.m != 0 and self.gasket.y != 0: # Non self energizing\n load += self.gasket.b() * math.pi * self.G() * self.gasket.m * self.conditions.internal_pressure\n\n return load\n\n def W_g(self):\n return 0.5 * (self.A_m() + self.A_b()) * self.bolts.allowable_stress_ambient\n\n def F_A(self):\n if self.conditions.axial_load < 0:\n return abs(self.conditions.internal_pressure)\n else:\n return self.conditions.axial_load\n\n def M_E(self):\n return abs(self.conditions.bending_moment)\n\n def C_us(self):\n if self.conditions.units == Units.customary:\n return 1\n elif self.conditions.units == Units.metric:\n return 6.894757 * 10 ** -3\n\n def W_gs(self):\n if self.gasket.m == 0 and self.gasket.y == 0:\n return 0\n else:\n return math.pi * self.gasket.b() * self.G() * self.C_us() * self.gasket.y\n\n def __A_m_ambient(self):\n return self.W_gs() / self.bolts.allowable_stress_ambient\n\n def __A_m_operating(self):\n return (self.W_o() + self.F_A() + (4 * self.M_E() / self.G())) / self.bolts.allowable_stress_operating\n\n def ambient_bolt_load_governs(self):\n return self.__A_m_ambient() > self.__A_m_operating()\n\n def A_m(self):\n if self.ambient_bolt_load_governs():\n return self.__A_m_ambient()\n else:\n return self.__A_m_operating()\n\n def A_b(self):\n return self.bolts.root_area * self.geometry.num_bolts\n\n def A_b_ok(self):\n return self.A_b() >= self.A_m()\n\n def H_D(self):\n return 0.785 * (self.geometry.B ** 2) * self.conditions.internal_pressure\n\n def h_D(self):\n if self.conditions.flange_type == FlangeType.integral:\n return (self.geometry.C - self.geometry.B - self.geometry.hub_geometry.g_1) / 2\n elif self.is_loose_flange():\n return 0.5 * (self.geometry.C - self.geometry.B)\n elif self.conditions.flange_type == FlangeType.reverse_integral:\n return 0.5 * (self.geometry.C + self.geometry.hub_geometry.g_1 - 2 * self.geometry.hub_geometry.g_o - self.geometry.B)\n else:\n raise ValueError(\"Invalid configuration given for h_d\")\n\n def H(self):\n return 0.785 * (self.G() ** 2) * self.conditions.internal_pressure\n\n def H_T(self):\n return self.H() - self.H_D()\n\n def h_T(self):\n t = self.conditions.flange_type\n\n if t == FlangeType.integral:\n return 0.5 * (0.5 * (self.geometry.C - self.geometry.B) + self.h_G())\n elif t == FlangeType.loose:\n if self.conditions.loose_type in [LooseType.lap_no_hub, LooseType.lap_with_hub]:\n return (self.geometry.C - self.G()) * 0.5\n elif self.conditions.loose_type in [LooseType.with_hub, LooseType.without_hub]:\n return (self.h_D() + self.h_G()) * 0.5\n else:\n raise ValueError(\"Invalid value for loose type configuration given for h_T\")\n elif self.is_reverse_flange():\n return 0.5 * (self.geometry.C - 0.5 * (self.geometry.B + self.G()))\n\n else:\n raise ValueError(\"Invalid flange type given for value h_T\")\n\n def H_G(self):\n return self.W_o() - self.H()\n\n def h_G(self):\n return 0.5 * (self.geometry.C - self.G())\n\n def B_star(self):\n RuntimeWarning(\"B_star has not been looked at, please implement this; results using this value should be carefully examined\")\n return self.geometry.B\n\n def is_loose_flange(self):\n if self.conditions.flange_type in [FlangeType.loose, FlangeType.reverse_loose]:\n return True\n elif self.conditions.flange_type in [FlangeType.integral, FlangeType.reverse_integral]:\n return False\n else:\n raise ValueError(\"Invalid flange type\")\n\n def is_reverse_flange(self):\n if self.conditions.flange_type in [FlangeType.reverse_integral, FlangeType.reverse_loose]:\n return True\n elif self.conditions.flange_type in [FlangeType.integral, FlangeType.loose]:\n return False\n else:\n raise ValueError(\"Invalid flange type\")\n\n def has_hub(self):\n if self.geometry.hub_geometry is not None:\n return False\n else:\n return True\n\n def __hub_factors_applicable(self, is_reverse):\n if self.conditions.flange_type == FlangeType.integral or (self.is_loose_flange() and self.has_hub()):\n return not is_reverse\n elif self.conditions.flange_type == FlangeType.reverse_integral or self.conditions.loose_type in [LooseType.with_hub, LooseType.lap_with_hub]:\n return is_reverse\n else:\n raise ValueError(\"Invalid configuration used when querying hub factor applicability\")\n\n def K(self):\n if self.__hub_factors_applicable(False):\n return self.geometry.A / self.geometry.B\n elif self.__hub_factors_applicable(True):\n return self.geometry.A / self.B_star()\n else:\n raise ValueError(\"Invalid configuration\")\n\n def Y(self):\n return (1 / (self.K() - 1)) * (0.66845 + 5.71690 * ((self.K()**2) * math.log10(self.K())) / ((self.K() ** 2) - 1))\n\n def T(self):\n num = (self.K() ** 2) * (1 + 8.55246 * math.log10(self.K())) - 1\n den = (1.04720 + 1.9448 * self.K() ** 2) * (self.K() - 1)\n return num / den\n\n def U(self):\n num = (self.K() ** 2) * (1 + 8.55246 * math.log10(self.K())) - 1\n den = 1.36136 * ((self.K() ** 2) - 1) * (self.K() - 1)\n return num / den\n\n def Z(self):\n return ((self.K() ** 2) + 1) / ((self.K() ** 2) - 1)\n\n def h_o(self):\n return math.sqrt(self.geometry.B * self.geometry.hub_geometry.g_o)\n\n def e(self):\n if not self.is_loose_flange():\n return self.F() / self.h_o()\n else:\n if self.has_hub():\n return self.F_L() / self.h_o()\n else:\n raise ValueError(\"Invalid flange configuraation for e\")\n\n def d(self):\n num = self.U() * (self.geometry.hub_geometry.g_o ** 2) * self.h_o()\n\n if not self.is_loose_flange():\n den = self.V()\n else:\n if self.has_hub():\n den = self.V_L()\n else:\n raise ValueError(\"Invalid flange configuraation for d\")\n\n return num / den\n\n def L(self):\n return ((self.geometry.t * self.e() + 1) / self.T()) + ((self.geometry.t ** 3) / (self.d()))\n\n def X_g(self):\n return self.geometry.hub_geometry.g_1 / self.geometry.hub_geometry.g_0\n\n def X_h(self):\n if self.is_reverse_flange():\n return self.geometry.hub_geometry.h / self.h_or()\n else:\n return self.geometry.hub_geometry.h / self.h_o()\n\n def alpha_r(self):\n return (1 / self.K() ** 2) * (1 + ((0.668 * (self.K() + 1)) / (self.Y())))\n\n def Y_r(self):\n return self.Y() * self.alpha_r()\n\n def T_r(self):\n return ((self.Z() + 0.3) / (self.Z() - 0.3)) * self.alpha_r() * self.T()\n\n def U_r(self):\n return self.alpha_r() * self.U()\n\n def h_or(self):\n return math.sqrt(self.geometry.A * self.geometry.hub_geometry.g_o)\n\n def e_r(self):\n if not self.is_loose_flange():\n return self.F() / self.h_or()\n else:\n if self.has_hub():\n return self.F_L() / self.h_or()\n else:\n raise ValueError(\"Invalid flange configuraation for e\")\n\n def d_r(self):\n num = self.U_r() * (self.geometry.hub_geometry.g_o ** 2) * self.h_or()\n\n if not self.is_loose_flange():\n den = self.V()\n else:\n if self.has_hub():\n den = self.V_L()\n else:\n raise ValueError(\"Invalid flange configuraation for d\")\n\n return num / den\n\n def L_r(self):\n return ((self.geometry.t * self.e_r() + 1) / (self.T_r())) + ((self.geometry.t ** 3) / self.d_r())\n\n def F(self):\n ln_xh = math.log(self.X_h(), math.e)\n ln_xg = math.log(self.X_g(), math.e)\n ret = 0.897697\n ret += 9.5257 * (10 ** -3) * ln_xh\n ret += 0.123586 * ln_xg ** 2\n ret += 0.0358580 * ln_xh ** 2\n ret -= 0.194422 * ln_xg * ln_xh\n ret -= 0.0181259 * ln_xg ** 3\n ret += 0.0129360 * ln_xh ** 3\n ret -= 0.0377693 * ln_xg * ln_xh ** 2\n ret += 0.0273791 * ln_xh * ln_xg ** 2\n\n return ret\n\n def F_L(self):\n lnxg = math.log(self.X_g(), math.e)\n lnxh = math.log(self.X_h(), math.e)\n\n num = 0.941074\n num += 0.176139 * lnxg\n num -= 0.188556 * lnxh\n num += 0.0689847 * lnxg ** 2\n num += 0.523798 * lnxg ** 2\n num -= 0.513894 * lnxg * lnxh\n\n den = 1\n den += 0.379392 * lnxg\n den += 0.184520 * lnxh\n den -= 0.00605208 * lnxg ** 2\n den -= 0.00358934 * lnxh ** 2\n den += 0.110179 * lnxg * lnxh\n\n return num / den\n\n def V(self):\n if self.X_h() < 0.1 or self.X_h() > 2:\n raise ValueError(\"X_h is out of range for V\")\n elif 0.1 <= self.X_h() <= 0.5:\n ret = 0.500244\n ret += (0.227914 / self.X_g())\n ret -= 1.87071 * self.X_h()\n ret -= (0.344410 / (self.X_g() ** 2))\n ret += 2.49189 * self.X_h() ** 2\n ret += 0.873446 * (self.X_h() / self.X_g())\n ret += 0.189953 / (self.X_g() ** 3)\n ret -= 1.06082 * self.X_h() ** 3\n ret -= 1.49970 * ((self.X_h() ** 2) / self.X_g())\n ret += 0.719413 * (self.X_h() / (self.X_g() ** 2))\n\n elif 0.5 < self.X_h() <= 2:\n xg_inv = 1 / self.X_g()\n xh_inv = 1/ self.X_h()\n ret = 0.0144868\n ret -= 0.135977 * xg_inv\n ret -= 0.0461919 * xh_inv\n ret += 0.560718 * xg_inv ** 2\n ret += 0.0529829 * xh_inv ** 2\n ret += 0.244313 * xg_inv * xh_inv\n ret += 0.113929 * xg_inv ** 3\n ret -= 0.00928265 * xh_inv ** 3\n ret -= 0.0266293 * xg_inv * xh_inv ** 2\n ret -= 0.217008 * xh_inv * xg_inv ** 2\n else:\n raise ValueError(\"Invalid value for X_h\")\n\n return ret\n\n def V_L(self):\n xh = self.X_h()\n\n if xh < 0.1 or xh > 2.0:\n raise ValueError(\"X_h is out of range\")\n\n xg = self.X_g()\n lnxh = math.log(xh, math.e)\n lnxg = math.log(xg, math.e)\n xh_inv = 1 / xh\n xg_inv = 1 / xg\n\n if 0.1 <= xh <= 0.25:\n ret = 6.57683\n ret -= 0.115516 * xg\n ret += 1.39499 * (xg ** 0.5) * lnxg\n ret += 0.307340 * lnxg ** 2\n ret -= 8.30849 * xg ** 0.5\n ret += 2.62307 * lnxg\n ret += 0.239498 * xh * lnxh\n ret -= 2.96125 * lnxh\n ret += (7.035052 * 10 ** -4) * xh_inv\n\n ret = math.e ** ret\n\n elif 0.25 < xh <= 0.5:\n ret = 1.56323\n ret -= 1.80696 * lnxg\n ret -= 1.33458 * xh_inv\n ret += 0.276415 * lnxg ** 2\n ret += 0.417135 * xh_inv ** 2\n ret += 1.39511 * lnxg * xh_inv\n ret += 0.0137129 * lnxg ** 3\n ret += 0.0943597 * xh_inv ** 3\n ret -= 0.402096 * lnxg * xh_inv ** 2\n ret -= 0.101619 * xh_inv * lnxg ** 2\n\n elif 0.5 < xh <= 1.0:\n\n ret = -0.0213643\n ret -= 0.0763597 * xg_inv\n ret += 0.1029900 * xh_inv\n ret += 0.725776 * xg_inv ** 2\n ret -= 0.160603 * xh_inv ** 2\n ret -= 0.0918061 * xg_inv * xh_inv\n ret += 0.472277 * xg_inv ** 3\n ret += 0.0873530 * xh_inv ** 3\n ret += 0.527487 * xg_inv * xh_inv ** 2\n ret -= 0.980209 * xh_inv * xg_inv ** 2\n\n elif 1.0 < xh <= 2.0:\n ret = 7.96687 * (10 ** -3)\n ret -= 0.220518 * xg_inv\n ret += 0.0602652 * xh_inv\n ret += 0.619818 * xg_inv ** 2\n ret -= 0.223212 * xh_inv ** 2\n ret += 0.421920 * xg_inv * xh_inv\n ret += 0.0950195 * xg_inv ** 3\n ret += 0.209813 * xh_inv ** 3\n ret -= 0.158821 * xg_inv * xh_inv ** 2\n ret -= 0.242056 * xh_inv * xg_inv ** 2\n else:\n raise ValueError(\"Invalid value for X_h\")\n\n return ret\n\n def f(self):\n if self.is_loose_flange():\n return 1\n\n num = 0.0927779\n num -= 0.0336633 * self.X_g()\n num += 0.964176 * self.X_g() ** 2\n num += 0.0566286 * self.X_h()\n num += 0.347074 * self.X_h() ** 2\n num -= 4.18699 * self.X_h() ** 3\n\n den = 1\n den -= 5.96093 * (10 ** -3) * self.X_g()\n den += 1.62904 * self.X_h()\n den += 3.49329 * self.X_h() ** 2\n den += 1.39052 * self.X_h() ** 3\n\n return max(1.0, num / den)\n\n def I(self):\n if self.conditions.flange_type == FlangeType.integral:\n if self.conditions.integral_type == IntegralType.no_hub:\n raise ValueError(\"Table 4.16.7 does not provide calculations for integral flanges with no hub\")\n elif self.conditions.integral_type in []:\n return (0.0874 * self.L() * (self.geometry.hub_geometry.g_o ** 2) * self.h_o() * self.geometry.B) / self.V()\n else:\n raise ValueError(\"Invalid value set for flange integral type in I\")\n elif self.conditions.flange_type == FlangeType.loose:\n if self.conditions.loose_type in [LooseType.with_hub, LooseType.lap_with_hub]:\n return (0.0874 * self.L() * (self.geometry.hub_geometry.g_o ** 2) * self.h_o() * self.geometry.B) / self.V_L()\n elif self.conditions.loose_type in [LooseType.without_hub, LooseType.lap_no_hub]:\n return (1/6) * (self.geometry.B * (self.geometry.t ** 3) * math.log(self.K(), math.e))\n else:\n raise ValueError(\"Invalid value for loose type in value I()\")\n else:\n raise ValueError(\"Invalid value for flange type in I()\")\n\n def A_R(self):\n return 0.5 * (self.geometry.A - self.geometry.B)\n\n def G_avg(self):\n return 0.5 * (self.geometry.hub_geometry.g_0 + self.geometry.hub_geometry.g_1)\n\n def A_A(self):\n if self.geometry.t >= self.G_avg():\n return self.A_R()\n else:\n return self.geometry.hub_geometry.h + self.geometry.t\n\n def B_B(self):\n if self.geometry.t >= self.G_avg():\n return self.geometry.t\n else:\n return self.G_avg()\n\n def C_C(self):\n if self.geometry.t >= self.G_avg():\n return self.geometry.hub_geometry.h\n else:\n return self.A_R() - self.G_avg()\n\n def D_DG(self):\n if self.geometry.t >= self.G_avg():\n return self.G_avg()\n else:\n return self.geometry.t\n\n def K_AB(self):\n return (self.A_A() * self.B_B() ** 3) * ((1/3) - 0.21 * (self.B_B() / self.A_A()) * (1 - (1/12) * (self.B_B() / self.A_A()) ** 4))\n\n def K_CD(self):\n return (self.C_C() * self.D_DG() ** 3) * ((1/3) - 0.105 * (self.D_DG()/self.C_C()) * (1 - (1 / 192) * (self.D_DG() / self.C_C()) ** 4))\n\n def I_p(self):\n if self.has_hub():\n return self.K_AB() + self.K_CD()\n else:\n return self.A_R() * self.geometry.t ** 3 * ((1/3) - 0.21 * (self.geometry.t / self.A_R()) * (1 - (1/12) * (self.geometry.t / self.A_R()) ** 4))\n\n def M_oe(self):\n t1 = 4 * self.M_E()\n t2 = self.I() / (0.3846 * self.I_p() + self.I())\n t3 = self.h_D() / (self.geometry.C - 2 * self.h_D())\n\n return t1 * t2 * t3 + self.F_A() * self.h_D()\n\n def F_S(self):\n if self.geometry.fs_num == 0:\n return 1.0\n elif self.geometry.fs_num == 1:\n return 2.0\n elif self.geometry.fs_num == 2:\n return 0.75\n else:\n raise ValueError(\"invalid number of splits specified for flange\")\n\n def B_s(self):\n return (0.25 * math.pi * self.geometry.B ** 2) / self.geometry.num_bolts\n\n def B_sc(self):\n return max(1.0, math.sqrt(self.B_s() / (2 * self.bolts.nominal_diameter + self.geometry.t)))\n\n def B_s_max(self):\n return 2 * self.bolts.nominal_diameter + ((6 * self.geometry.t) / (self.gasket.m + 0.5))\n\n def __M_o_int(self):\n return abs(((self.H_D() * self.h_D() + self.H_T() * self.h_T() + self.H_G() * self.h_G()) * self.B_sc() + self.M_oe()) * self.F_S())\n\n def __M_o_ext(self):\n return abs((self.H_D() * (self.h_D() - self.h_G()) + self.H_T() * (self.h_T() - self.h_G()) + self.M_oe()) * self.F_S())\n\n def M_o(self):\n if self.conditions.internal_pressure >=0:\n return self.__M_o_int()\n else:\n return self.__M_o_ext()\n\n def __M_g_ext(self):\n return self.W_g() * self.h_G() * self.F_S()\n\n def __M_g_int(self):\n return 0.5 * (self.W_g() * (self.geometry.C - self.G()) * self.B_sc() * self.F_S())\n\n def M_g(self):\n if self.conditions.internal_pressure >=0:\n return self.__M_g_int()\n else:\n return self.__M_g_ext()\n\n def S_H_operating(self):\n if self.is_loose_flange() and not self.has_hub():\n return None\n\n if self.is_reverse_flange():\n return self.f() * self.M_o() / (self.L_r() * self.B_star() * self.geometry.hub_geometry.g_1 ** 2)\n else:\n return self.f() * self.M_o() / (self.L() * self.B() * self.geometry.hub_geometry.g_1 ** 2)\n\n def S_H_seating(self):\n if self.is_loose_flange() and not self.has_hub():\n return None\n\n if self.is_reverse_flange():\n return self.f() * self.M_g() / (self.L_r() * self.B_star() * self.geometry.hub_geometry.g_1 ** 2)\n else:\n return self.f() * self.M_g() / (self.L() * self.geometry.B * self.geometry.hub_geometry.g_1 ** 2)\n\n def S_R_operating(self):\n if self.is_loose_flange() and not self.has_hub():\n return None\n\n if self.is_reverse_flange():\n return (1.33 * self.geometry.t * self.e_r() + 1) * self.M_o() / (self.L_r() * self.B_star() * self.geometry.t ** 2)\n else:\n return (1.33 * self.geometry.t * self.e() + 1) * self.M_o() / (self.L() * self.geometry.B * self.geometry.t ** 2)\n\n def S_R_seating(self):\n if self.is_loose_flange() and not self.has_hub():\n return None\n\n if self.is_reverse_flange():\n return (1.33 * self.geometry.t * self.e_r() + 1) * self.M_g() / (self.L_r() * self.B_star() * self.geometry.t ** 2)\n else:\n return (1.33 * self.geometry.t * self.e() + 1) * self.M_g() / (self.L() * self.geometry.B * self.geometry.t ** 2)\n\n def S_T_operating(self):\n\n if self.is_reverse_flange():\n if self.is_loose_flange() and not self.has_hub():\n return self.Y() * self.M_o() / (self.B_star() * self.geometry.t ** 2)\n else:\n if (self.is_loose_flange() and self.has_hub()) or not self.is_loose_flange():\n return (self.Y() * self.M_o() / (self.geometry.B * self.geometry.t ** 2)) - self.Z() * self.S_R_operating()\n elif self.is_loose_flange() and not self.has_hub():\n return self.Y() * self.M_o() / (self.geometry.B * self.geometry.t ** 2)\n else:\n raise ValueError(\"What configuration do you have?\")\n\n def S_T_seating(self):\n\n if self.is_reverse_flange():\n if self.is_loose_flange() and not self.has_hub():\n return self.Y() * self.M_g() / (self.B_star() * self.geometry.t ** 2)\n else:\n if (self.is_loose_flange() and self.has_hub()) or not self.is_loose_flange():\n return (self.Y() * self.M_g() / (self.geometry.B * self.geometry.t ** 2)) - self.Z() * self.S_R_seating()\n elif self.is_loose_flange() and not self.has_hub():\n return self.Y() * self.M_g() / (self.geometry.B * self.geometry.t ** 2)\n else:\n raise ValueError(\"What configuration do you have?\")\n\n def S_T_1_operating(self):\n if self.is_reverse_flange() and self.has_hub():\n t1 = (self.Y_r() * self.M_o()) / (self.B_star() * self.geometry.t ** 2)\n t2 = (self.Z() * self.S_R_operating() * (0.67 * self.geometry.t * self.e_r() + 1)) / (1.33 * self.geometry.t * self.e_r() + 1)\n return t1 - t2\n\n def S_T_1_seating(self):\n if self.is_reverse_flange() and self.has_hub():\n t1 = (self.Y_r() * self.M_g()) / (self.B_star() * self.geometry.t ** 2)\n t2 = (self.Z() * self.S_R_seating() * (0.67 * self.geometry.t * self.e_r() + 1)) / (1.33 * self.geometry.t * self.e_r() + 1)\n return t1 - t2\n\n def S_T_2_operating(self):\n if self.is_reverse_flange() and self.has_hub():\n num = ((0.67 * self.geometry.t * self.e_r() + 1) * 2 * self.K() ** 2)\n den = (((self.K() ** 2) - 1) * self.L_r())\n term1 = (self.Y() - (num / den))\n term2 = (self.M_o() / self.B_star() * self.geometry.t ** 2)\n return term1 * term2\n\n def S_T_2_seating(self):\n if self.is_reverse_flange() and self.has_hub():\n num = ((0.67 * self.geometry.t * self.e_r() + 1) * 2 * self.K() ** 2)\n den = (((self.K() ** 2) - 1) * self.L_r())\n term1 = (self.Y() - (num / den))\n term2 = (self.M_g() / self.B_star() * self.geometry.t ** 2)\n return term1 * term2\n\n def check_S_H_operating(self):\n pass\n\n\n\n def getResult(self):\n return {\n \"bolt_loads\": {\n \"b\": self.gasket.b(),\n \"G\": self.G(),\n \"W_0\": self.W_o(),\n \"W_gs\": self.W_gs(),\n \"ambient_bolt_load_governs\": self.ambient_bolt_load_governs(),\n \"A_m\": self.A_m(),\n \"A_b\": self.A_b(),\n \"A_b_ok\": self.A_b_ok()\n },\n\n \"factors\": {\n\n },\n\n \"forces\": {\n \"H_D\": self.H_D(),\n \"H\": self.H(),\n \"H_T\": self.H_T(),\n \"H_G\": self.H_G()\n },\n\n \"moments\": {\n\n },\n\n \"stresses\": {\n\n },\n\n \"acceptance\": {\n\n },\n\n \"rigidity\": {\n\n }\n\n }\n\n\n\n","sub_path":"src/Flange/Calculations/Div2Flange.py","file_name":"Div2Flange.py","file_ext":"py","file_size_in_byte":29625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"34472817","text":"import random\nfrom core.utils import Generator\n\n\nclass Main(Generator):\n name = 'Fast addition in one minute'\n years = [5, 6]\n directions = 'Afla cat de multe operatiuni poti rezolva in maxim 1 minut.'\n template = 'generators/math.html'\n\n def generate_data(self):\n numbers = list(range(0, 10))\n results = []\n for i in range(self.count):\n row = []\n while not len(row) == 48:\n left_number = random.choice(numbers)\n righ_possible = numbers.copy()\n righ_possible.remove(left_number)\n right_number = random.choice(righ_possible)\n if (left_number, right_number) not in row:\n row.append((left_number, right_number))\n results.append(row)\n self.data = results\n return results\n\n def get_context_data(self, iteration):\n context = super(Main, self).get_context_data(iteration)\n context['items'] = context['items'][iteration]\n context['operation'] = '+'\n return context\n","sub_path":"application/core/generators/math_add_easy.py","file_name":"math_add_easy.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"214779796","text":"import os \nimport json\nfrom pprint import pprint\nimport requests\ntoken=os.environ['token']\n\n\n\ndef getUpdate_text():\n url=f'https://api.telegram.org/bot{token}/getUpdates'\n r=requests.get(url)\n data=r.json()['result']\n \n text=data[-1]['message']['text']\n \n return text\n\n\ndef getchat_id():\n url=f'https://api.telegram.org/bot{token}/getUpdates'\n r=requests.get(url)\n\n data=r.json()['result']\n chat_id=data[-1]['message']['chat']['id']\n return chat_id\n\n\ndef weather():\n api_key='f9716fd07196bb4a858f3d8cddfec94d'\n url=f'http://api.openweathermap.org/data/2.5/forecast'\n text=getUpdate_text()\n payload={\n 'q':text,\n 'appid':api_key\n }\n r=requests.get(url,params=payload)\n\n data=r.json()\n if r.status_code==200:\n\n text=text.title()\n inform=data['list'][-1]\n temp=int(inform['main']['temp']-273.15)\n description=inform['weather'][0]['description']\n wind=inform['wind']['speed']\n weather=f\"from:{text}\\nTemp:{temp}\\ndescription:{description}\\nwind:{wind}m/s\" \n else:\n weather='city not found'\n \n\n return weather\n\n\ndef sendMsg():\n url=f'https://api.telegram.org/bot{token}/sendMessage'\n chat_id=getchat_id()\n text=weather()\n print(text)\n payload={\n 'chat_id':chat_id,\n 'text':text,\n }\n r=requests.get(url,payload)\n\ndef updateId():\n url=f'https://api.telegram.org/bot{token}/getUpdates'\n r=requests.get(url)\n\n data=r.json()['result']\n update_id=data[-1]['update_id']\n return update_id\n\n\nlast_update_id=None\nwhile True:\n new_update_id=updateId()\n if last_update_id!=new_update_id:\n sendMsg()\n \n last_update_id=new_update_id\n \n\n\n \n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"645265188","text":"from flask import Blueprint, render_template, session, flash, redirect,request,url_for\nfrom src.extension import db\nfrom src.Models.Users import User\nfrom src.Models.Houses import House\nfrom src.Utility import enumMachine\nfrom src.Models.Target import Target\nimport datetime\nfrom src.Models.Targets import Targets\nfrom datetime import datetime\n\ncenter=Blueprint('center',__name__)\n\n# #4.1 获取收藏列表\n# @center.route(\"/center/collection/getCollectionList\",methods=[\"POST\"])\n# def get_collection():\n# userId = request.json.get('userId')\n# current_user=User.query.filter(User.id==userId).first()\n#\n# houses=current_user.houses\n# houseList=[]\n# for item in houses:\n# info={}\n# info[\"sold\"]=True\n# info[\"imgUrl\"]=item.imgUrl\n# info[\"title\"]=item.title\n# info[\"date\"]=item.PublishTime\n# info[\"seller\"]=current_user.username\n# info[\"price\"]=item.price\n# info[\"collectDate\"]='collectDate'\n# houseList.append(info)\n# return {\n# \"success\": 1,\n# \"data\": {\n# \"collectionList\":houseList\n# },\n# \"error\":None\n# }\n\n#添加已经发布\n# @collection.route(\"/addCollection\",methods=['GET','POST'])\n# def addCollection():\n# #db\n# userId=request.json.get('userId')\n# houseId=request.json.get('houseId')\n# collected=request.json.get('collected')\n# if collected == \"true\":\n# user=User.query.filter(User.id==userId).first()\n# house=House.query.filter(House.id==houseId).first()\n# user.collections.append(house)\n# house.setCollected(\"true\")\n# db.session.add(user)\n# db.session.add(house)\n# db.session.commit()\n# return {\n# \"success\": 1,\n# \"data\": {\n# },\n# \"error\":\"None\"\n# }\n# if collected == \"false\":\n# user = User.query.filter(User.id == userId).first()\n# house = House.query.filter(House.id == houseId).first()\n# user.collections.remove(house)\n# house.setCollected(\"false\")\n# db.session.add(user)\n# db.session.add(house)\n# db.session.commit()\n# return {\n# \"success\": 1,\n# \"data\": {\n# },\n# \"error\": \"None\"\n# }\n# return {\n# \"success\": 0,\n# \"data\": {\n# },\n# \"error\": \"Error\"\n# }\n\n#添加已经发布\n@center.route(\"/addPublishlist\",methods=[\"POST\"])\ndef publish():\n arg={}\n arg['userId'] = request.json.get('userId')\n arg['bathroom'] = request.json.get('bathroom')\n arg['hall'] = request.json.get('hall')\n arg['kitchen'] = request.json.get('kitchen')\n arg['room'] = request.json.get('room')\n arg['area'] = request.json.get('area')\n arg['floors'] = request.json.get('floors')\n arg['buildingStructure'] = request.json.get('buildingStructure')\n arg['buildingType'] = request.json.get('buildingType')\n arg['elevator'] = request.json.get('elevator')\n arg['floorType'] = request.json.get('floorType')\n arg['heating'] = request.json.get('heating')\n arg['houseStructure'] = request.json.get('houseStructure')\n arg['property'] = request.json.get('property')\n arg['region'] =int(request.json.get('region'))\n arg['decoration'] = request.json.get('decoration')\n arg['district'] = request.json.get('district')\n arg['coordinate'] = request.json.get('coordinate')\n arg['direction'] = request.json.get('direction')\n arg['elevatorNum'] = int(request.json.get('elevatorNum'))\n arg['houseNum'] = int(request.json.get('houseNum'))\n arg['community'] = request.json.get('community')\n arg['title'] = request.json.get('title')\n arg['describe'] = request.json.get('describe')\n arg['unitPrice'] = int(request.json.get('unitPrice'))\n arg['totalPrice'] = int(request.json.get('totalPrice'))\n arg['imgUrlList'] = request.json.get('imgUrlList')\n\n print(arg)\n house=House()\n user=User.query.filter(User.id == arg['userId']).first()\n print(user)\n\n\n\n house.toilet=arg['bathroom']\n house.hall=arg['hall']\n house.kitchen=arg['kitchen']\n house.room=arg['room']\n house.floor_area=arg['area']\n house.total_floors=arg['floors']\n house.Architectural_structure=enumMachine.Building_structrue.enum2field(arg['buildingStructure'])\n house.Building_Type=enumMachine.Building_type.enum2field(arg['buildingType'])\n house.elevator=enumMachine.Elevator.enum2field(arg['elevator'])\n house.Floor_type=enumMachine.Floor_type.enum2field(arg['floorType'])\n house.heating=enumMachine.Heating.enum2field(arg['heating'])\n house.House_structure=enumMachine.House_structrue.enum2field(arg['houseStructure'])\n house.Property_information=enumMachine.PropertyInfo.enum2field(arg['property'])\n house.Specific_area=enumMachine.Region.enum2field(arg['region'])\n house.Interior_design=enumMachine.Ddecoration.enum2field(arg['decoration'])\n house.District=enumMachine.District.enum2field(arg['district'])\n house.Longitude=int(arg['coordinate'][0])\n house.Latitude=int(arg['coordinate'][1])\n house.title=arg['title']\n house._unit_price=arg['unitPrice']\n house.price=arg['totalPrice']/10000\n house.saled=\"FALSE\"\n utc_time = datetime.utcnow()\n house.PublishTime=utc_time\n house.imgUrl=','.join(arg['imgUrlList'])\n house.collected=\"FALSE\"\n\n\n direction_list=[]\n for i in arg['direction']:\n direction_list.append(enumMachine.Direction.enum2field(i))\n\n direction = {\n \"west\": \"west\" if \"west\" in direction_list else \"no\",\n \"east\": \"east\" if \"east\" in direction_list else \"no\",\n \"south\": \"south\" if \"south\" in direction_list else \"no\",\n \"north\": \"north\" if \"north\" in direction_list else \"no\",\n \"southwest\": \"southwest\" if \"southwest\" in direction_list else \"no\",\n \"southeast\": \"southeast\" if \"southeast\" in direction_list else \"no\",\n \"northeast\": \"northeast\" if \"northeast\" in direction_list else \"no\",\n \"northwest\": \"northwest\" if \"northwest\" in direction_list else \"no\"\n }\n house.west=direction['west']\n house.east=direction['east']\n house.north=direction[\"north\"]\n house.south=direction[\"south\"]\n house.east_north=direction['northeast']\n house.east_south=direction['southeast']\n house.west_north=direction['northwest']\n house.west_south=direction['southwest']\n\n elvatorNum=arg['elevatorNum']\n houseNum=arg['houseNum']\n ratio=elvatorNum/houseNum\n house.ladder_ratio=ratio\n user.publishments.append(house)\n db.session.add(house)\n db.session.add(user)\n db.session.commit()\n\n\n return {\n \"success\": 1,\n \"data\":{\n \"houseId\":house.id\n },\n \"error\":\"None\"\n }\n\n\n\n#4.2 获取发布列表\n@center.route(\"/center/published/getPublishedList\",methods=[\"POST\"])\ndef getPublish():\n userId = request.json.get('userId')\n current_user = User.query.filter(User.id == userId).first()\n\n houses = current_user.publishments\n houseList = []\n for item in houses:\n info = {}\n info[\"houseId\"]=item.id\n info[\"sold\"] = item.saled\n info[\"imgUrl\"] = item.imgUrl\n info[\"Title\"] = item.title\n info[\"Date\"] = item.PublishTime\n info[\"seller\"] = current_user.username\n info[\"price\"] = item.price\n houseList.append(info)\n return {\n \"success\": 1,\n \"data\": {\n \"publishList\": houseList\n },\n \"error\": None\n }\n\n\n#4.6 删除已发布\n@center.route(\"/center/published/delPublished\",methods=[\"GET\",\"POST\"])\ndef del_publish():\n if request.method==\"POST\":\n userId = request.json.get('userId')\n houseId = request.json.get('houseId')\n if houseId is not None and userId is not None:\n user = User.query.filter(User.id == userId).first()\n house = House.query.filter(House.id == houseId).first()\n if house in user.publishments:\n user.publishments.remove(house)\n db.session.delete(house)\n db.session.add(user)\n db.session.commit()\n return {\n \"success\": 1,\n \"data\": {\n },\n \"error\": \"Delete successfully\"\n }\n else:\n return {\n \"success\": 0,\n \"data\": {\n },\n \"error\": \"The house is not in publish list\"\n }\n\n return {\n \"success\": 0,\n \"data\": {\n },\n \"error\": \"No such house or user\"\n }\n else:\n return {\n \"success\": 0,\n \"data\": {\n },\n \"error\": \"No such user or house\"\n }\n else:\n return {\n \"success\": 0,\n \"data\": {\n },\n \"error\": \"Error\"\n }\n\n\n# #4.4 更新兴趣信息(target)\n#\n# @center.route(\"/center/target/updateTargetInfo\",methods=[\"POST\"])\n# def get_profile():\n# #db\n# if request.method==\"POST\":\n# print(request.form)\n# print(request.json)\n# print(request.data)\n# priceRange=request.json.get('priceRange')\n# layout=request.json.get('layout')\n# measure=request.json.get('measure')\n# orientation=request.json.get('orientation')\n# floor=request.json.get('floor')\n# decoration=request.json.get('decoration')\n#\n# return {\n# \"success\":1,\n# \"data\":{\n# \"priceRange\":priceRange,\n# \"layout\":layout,\n# \"measure\":measure,\n# \"orientation\":orientation,\n# \"floor\":floor,\n# \"decoration\":decoration\n# },\n# \"error\":None\n# }\n\n# #4.5 删除收藏(不支持批量删除)\n# @center.route(\"/center/collection/delCollection\", methods=[\"POST\"])\n# def update_profile():\n# # db\n# if request.method == \"POST\":\n# print(request.form)\n# print(request.json)\n# print(request.data)\n# priceRange = request.json.get('priceRange')\n# layout = request.json.get('layout')\n# measure = request.json.get('measure')\n# orientation = request.json.get('orientation')\n# floor = request.json.get('floor')\n# decoration = request.json.get('decoration')\n#\n# return {\n# \"success\": 1,\n# \"data\": {\n# \"priceRange\": priceRange,\n# \"layout\": layout,\n# \"measure\": measure,\n# \"orientation\": orientation,\n# \"floor\": floor,\n# \"decoration\": decoration\n# },\n# \"error\":None\n# }\n\n\n#4.3 获取兴趣信息\n@center.route(\"/center/target/getTargetInfo\",methods=[\"POST\"])\ndef getTartgetInfo():\n if request.method == \"POST\":\n user = User.query.filter(User.id == request.json.get(\"userId\")).first()\n if user is None:\n return {\n \"success\": 0,\n \"data\":{\n },\n \"error\":\"User not found\"\n }\n else:\n\n t_str=user.target\n\n ts=user.targets.all()\n # list=[]\n # for i in ts:\n # list.append(i.toEnum())\n return {\n \"success\":1,\n \"data\":ts[0].toEnum(),\n \"error\":None\n }\n return \"0\"\n\n\n#4.4 更新兴趣信息\n@center.route(\"/center/target/updateTargetInfo\",methods=[\"POST\"])\ndef updateTartget():\n if request.method==\"POST\":\n user = User.query.filter(User.id == request.json.get(\"userId\")).first()\n print(user)\n if not user:\n return {\n \"success\": 0,\n \"data\":{\n },\n \"error\":\"User not found\"\n }\n else:\n print(request.data)\n print(type(request.json))\n target=Target.loadJson(d=request.data)\n print(type(target))\n j=Target.convertJson(target=target)\n user.saveTarget(target=j)\n tars=user.targets.all()\n if len(tars) != 0:\n tar = user.targets.all()[0]\n print(tar)\n t=Targets.saveTarget(tar,target=target.toDict())\n else:\n t = Targets.saveTarget(Targets(), target=target.toDict())\n user.targets.append(t)\n db.session.add(user)\n db.session.commit()\n\n\n return {\n \"success\": 1,\n \"data\":{\n },\n \"error\":None\n }\n\n return {\n \"success\": 0,\n \"data\":{\n },\n \"error\":\"No this method\"\n }\n","sub_path":"backend/src/blueprints/center.py","file_name":"center.py","file_ext":"py","file_size_in_byte":12891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"95948524","text":"import requests\nimport json\nlist=[]\ntoken=\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6InNoYXJtYWthbmNoYW4zNDRAZ21haWwuY29tIiwicm9sZSI6IlVzZXIiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9zaWQiOiI0MTUzIiwiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93cy8yMDA4LzA2L2lkZW50aXR5L2NsYWltcy92ZXJzaW9uIjoiMTA5IiwiaHR0cDovL2V4YW1wbGUub3JnL2NsYWltcy9saW1pdCI6IjEwMCIsImh0dHA6Ly9leGFtcGxlLm9yZy9jbGFpbXMvbWVtYmVyc2hpcCI6IkJhc2ljIiwiaHR0cDovL2V4YW1wbGUub3JnL2NsYWltcy9sYW5ndWFnZSI6ImVuLWdiIiwiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93cy8yMDA4LzA2L2lkZW50aXR5L2NsYWltcy9leHBpcmF0aW9uIjoiMjA5OS0xMi0zMSIsImh0dHA6Ly9leGFtcGxlLm9yZy9jbGFpbXMvbWVtYmVyc2hpcHN0YXJ0IjoiMjAyMC0wNC0xMyIsImlzcyI6Imh0dHBzOi8vYXV0aHNlcnZpY2UucHJpYWlkLmNoIiwiYXVkIjoiaHR0cHM6Ly9oZWFsdGhzZXJ2aWNlLnByaWFpZC5jaCIsImV4cCI6MTU4ODg2NjE2MCwibmJmIjoxNTg4ODU4OTYwfQ.v5tYtSEEzpLiyqMOE6og9OOw93JTYHWXpC9hDbwzGRM&format=json&language=en-gb\"\n\ndef bodylocation():\n urllocation=\"https://healthservice.priaid.ch/body/locations?token=\"+token\n\n\n diag=requests.get(urllocation)\n x=json.loads(diag.text)\n print(x)\n return x\nbodylocation()\nlist=[]\ndef bodysubloaction():\n x=bodylocation()\n for i in x:\n y=i['ID']\n list.append(y)\n print(list)\n k=int(input(\"enter any number from above list:\"))\n\n urlsublocation=\"https://healthservice.priaid.ch/body/locations/\"+str(k)+\"?token=\"+token\n\n diag=requests.get(urlsublocation)\n y=json.loads(diag.text)\n print(y)\n return y\ndef bodysymptoms():\n k=bodysubloaction()\n\n z=int(input(\"enter no from above list\"))\n x=int(input(\"enter 0 for male and 1 for female:\"))\n\n urlbodysymptom=\"https://healthservice.priaid.ch/symptoms/\"+str(z)+\"/\"+str(x)+\"?token=\"+token\n diag=requests.get(urlbodysymptom)\n z=json.loads(diag.text)\n print(z)\n for i in range(len(z)):\n print(z[i]['ID'])\n return z\nbodysymptoms()\ndef diagnosis():\n m=bodysymptoms()\n print(m)\n k=int(input(\"enter your symptom:\"))\n urldiag=\"https://healthservice.priaid.ch/diagnosis?symptoms=[\"+str(k)+\"]&gender=female&year_of_birth=1999&token=\"+token\n diag=requests.get(urldiag)\n a=json.loads(diag.text)\n return a\ndef issuesdata():\n l=diagnosis()\n print(l)\n n=int(input(\"enter number:\"))\n url2 = \"https://healthservice.priaid.ch/issues/\"+str(n)+\"/info?&token=\"+token\n\n#\"https://healthservice.priaid.ch/issues/105/info?\n\n response2 = requests.get(url2)\n z=json.loads(response2.text)\n print(z[\"TreatmentDescription\"])\n\n\n\n#bodylocation()\n#bodysubloaction()\n#bodysymptoms()\ndiagnosis()\n#issuesdata()\n","sub_path":"project1/symptom/bodyloc.py","file_name":"bodyloc.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"565238401","text":"import sqlalchemy as sa\nfrom sqlalchemy.sql.expression import nullsfirst, nullslast\n\nfrom webservices.exceptions import ApiError\n\n\ndef parse_option(option, model=None, nulls_large=True):\n \"\"\"Parse sort option to SQLAlchemy order expression.\n\n :param str option: Column name, possibly prefixed with \"-\"\n :param model: Optional SQLAlchemy model to sort on\n :param nulls_large: Treat null values as large\n :raises: ApiError if column not found on model\n \"\"\"\n order = sa.desc if option.startswith('-') else sa.asc\n nulls = nullsfirst if (nulls_large ^ (not option.startswith('-'))) else nullslast\n column = option.lstrip('-')\n if model:\n try:\n column = getattr(model, column)\n except AttributeError:\n raise ApiError('Field \"{0}\" not found'.format(column))\n return column, order, nulls\n\n\ndef ensure_list(value):\n if isinstance(value, list):\n return value\n if value:\n return [value]\n return []\n\n\ndef sort(query, options, model, clear=False, hide_null=False, nulls_large=True):\n \"\"\"Sort query using string-formatted columns.\n\n :param query: Original query\n :param options: String or list of strings of column names; prepend with \"-\"\n for descending sort\n :param model: SQLAlchemy model\n :param clear: Clear existing sort conditions\n :param hide_null: Exclude null values on sorted column(s)\n :param nulls_large: Treat null values as large on sorted column(s)\n \"\"\"\n if clear:\n query = query.order_by(False)\n options = ensure_list(options)\n columns = []\n for option in options:\n column, order, nulls = parse_option(option, model=model, nulls_large=nulls_large)\n query = query.order_by(nulls(order(column)))\n if hide_null:\n query = query.filter(column != None) # noqa\n columns.append((column, order))\n return query, columns\n","sub_path":"webservices/sorting.py","file_name":"sorting.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"288558723","text":"from datetime import datetime, timedelta\nimport os\nfrom airflow import DAG\nfrom airflow.operators.dummy_operator import DummyOperator\nfrom airflow.operators import (StageToRedshiftOperator, LoadFactOperator, LoadDimensionOperator, DataQualityOperator)\nfrom helpers import SqlQueries\n\n# AWS_KEY = os.environ.get('AWS_KEY')\n# AWS_SECRET = os.environ.get('AWS_SECRET')\n\ndefault_args = {\n 'owner': 'udacity',\n 'start_date': datetime(2019, 1, 12),\n 'depends_on_past': False,\n 'retries': 3,\n 'retry_delay': timedelta(minutes=5),\n 'catch': False,\n 'email_on_retry': False\n}\n\ndag = DAG('udac_example_dag',\n default_args=default_args,\n description='Load and transform data in Redshift with Airflow',\n schedule_interval='0 * * * *',\n max_active_runs=1\n )\n\n#start_operator = DummyOperator(task_id='Begin_execution', dag=dag)\n\n\nstage_songs_to_redshift = StageToRedshiftOperator(\n task_id='Stage_songs',\n dag=dag,\n redshift_conn_id=\"redshift\",\n aws_credentials_id=\"aws_credentials\",\n target_table=\"staging_songs\",\n s3_bucket=\"udacity-dend\",\n s3_key=\"song_data\",\n copy_format=\"'auto'\",\n provide_context=True\n)\n\n\n#end_operator = DummyOperator(task_id='Stop_execution', dag=dag)\n\nstage_songs_to_redshift\n","sub_path":"udac_example_dag.py","file_name":"udac_example_dag.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"380934139","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@file : student_interface.py\n@author : Andy Zhang\n@time : 2020/10/15 15:22\n@Desc : \n\"\"\"\nfrom db.models import Student\nfrom db import models\nfrom lib import common\n\n\ndef stu_register(name, pwd):\n if Student.select(name):\n return False, '学生已存在'\n stu_obj = Student(name, pwd)\n stu_obj.save()\n return True, f'学生{name}注册成功'\n\n\ndef add_campus_control(campus_name, stu_name):\n stu_obj = models.Student.select(stu_name)\n if stu_obj.campus:\n return f'学生已有学校:{campus_name}'\n stu_obj.add_campus(campus_name)\n return f'学校{campus_name}添加成功'\n\n\ndef get_course_list(name):\n '''\n 获取学生课程列表\n :param name:学生名称\n :return: 课程列表\n '''\n stu_obj = models.Student.select(name)\n stu_school = stu_obj.campus\n if not stu_school:\n return False, '你还没有校区,请先添加校区'\n campus_obj = models.Campus.select(stu_school)\n if not campus_obj.course_list:\n return False, f'你所在校区【{stu_school}】还没有课程。'\n return True, campus_obj.course_list # 返回课程列表\n\n\ndef add_course_control(course, user):\n '''\n 添加课程接口\n :param course: 课程名\n :param user: 需要添加课程的学生\n :return:\n '''\n stu_obj = models.Student.select(user)\n if course in stu_obj.stu_course:\n return False, f'课程{course}已存在'\n stu_obj.add_course(course)\n return True, f'恭喜,你所在的校区{stu_obj.campus}添加课程{course}成功'\n\n\ndef stu_score_control(user,course_name=''):\n stu_obj = models.Student.select(user)\n if not stu_obj.score: return False, '学生课程还没有分数'\n if not course_name:\n return True,stu_obj.score\n if course_name not in stu_obj.score: return False, '学生没有该课程分数信息'\n return True, stu_obj.score.get(course_name)\n","sub_path":"interface/student_interface.py","file_name":"student_interface.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"448554063","text":"\"\"\"\nGiven an integer array nums that may contain duplicates, return all possible subsets (the power set).\n\nThe solution set must not contain duplicate subsets. Return the solution in any order.\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:\n nums.sort()\n self.res = []\n self.dfs(nums, [])\n return list(self.res)\n\n def dfs(self, nums, prefix):\n print(nums, prefix, self.res)\n if prefix not in self.res:\n self.res.extend([prefix])\n if nums not in self.res:\n self.res.extend([nums])\n for i, num in enumerate(nums):\n self.dfs(nums[i+1:], prefix+[num])\n\n\ns = Solution()\nprint(s.subsetsWithDup([1,2,2]))","sub_path":"Subsets II.py","file_name":"Subsets II.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"541050261","text":"# from pip import main\n\n\nclass Pessoa:\n \n olhos = 2\n\n def __init__(self, *filhos, nome=None, idade=44) -> None:\n self.nome = nome\n self.idade = idade\n self.filhos = list(filhos)\n\n\n def cumprimentar(self):\n return 'Olá'\n\n @staticmethod\n def metodo_estatico():\n return 42\n\n @classmethod\n def metodo_e_atributo_estatico(cls):\n return f'Classe: {cls} - olhos: {cls.olhos}'\n\n\nif __name__ == '__main__':\n luiz = Pessoa(nome='Luiz', idade=22)\n fernando = Pessoa(luiz, nome='Fernando')\n print(fernando.cumprimentar())\n print(fernando.nome)\n print(fernando.idade)\n\n for filho in fernando.filhos:\n print(filho.nome)\n print(filho.idade)\n \n print(fernando.__dict__)\n fernando.olhos = 1\n print(fernando.__dict__)\n del fernando.olhos\n print(fernando.__dict__)\n print(luiz.__dict__)\n print(Pessoa.olhos)\n print(Pessoa.metodo_estatico(), fernando.metodo_estatico())\n print(Pessoa.metodo_e_atributo_estatico(), fernando.metodo_e_atributo_estatico())","sub_path":"oo/pessoa.py","file_name":"pessoa.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"558374575","text":"class Solution(object):\n def maxProfit1(self, prices):\n return sum(max(prices[i + 1] - prices[i], 0) for i in range(len(prices) - 1))\n\n def maxProfit2(self, prices):\n maxprofit = 0\n if len(prices) < 2:\n return maxprofit\n for i in range(1, len(prices)):\n maxprofit += (prices[i] - prices[i - 1]) if prices[i] > prices[i - 1] else 0\n return maxprofit\n\n def maxProfit(self, prices):\n maxprofit = 0\n for i in range(1, len(prices)):\n if prices[i] > prices[i - 1]:\n maxprofit += prices[i] - prices[i - 1]\n return maxprofit\n\n\nif __name__ == '__main__':\n sol = Solution()\n\n print(sol.maxProfit([]))\n print(sol.maxProfit([7, 1, 5, 3, 6, 4]))\n print(sol.maxProfit([7, 6, 4, 3, 1]))\n","sub_path":"Solutions/122. Best Time to Buy and Sell Stock II/122.py","file_name":"122.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"372026880","text":"\"\"\"\nGiven two binary trees and imagine that when you put one \nof them to cover the other, some nodes of the two trees are \noverlapped while the others are not.\n\nYou need to merge them into a new binary tree. The merge rule \nis that if two nodes overlap, then sum node values up as the new \nvalue of the merged node. Otherwise, the NOT null node will be used \nas the node of new tree.\n\nExample 1:\nInput: \n\tTree 1 Tree 2 \n 1 2 \n / \\ / \\ \n 3 2 1 3 \n / \\ \\ \n 5 4 7 \nOutput: \nMerged tree:\n\t 3\n\t / \\\n\t 4 5\n\t / \\ \\ \n\t 5 4 7\n\nNote: The merging process must start from the root nodes of both trees.\n\"\"\"\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:\n def traversal(node1, node2):\n if node1 is None and node2 is None:\n return None\n elif node1 is None:\n return node2\n elif node2 is None:\n return node1\n node = TreeNode(node1.val + node2.val)\n node.left = traversal(node1.left, node2.left)\n node.right = traversal(node1.right, node2.right)\n return node\n node = traversal(t1, t2)\n return node\n","sub_path":"trees/617_merge_two_bts.py","file_name":"617_merge_two_bts.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"585785565","text":"\n\n#calss header\nclass _SOFTWOOD():\n\tdef __init__(self,): \n\t\tself.name = \"SOFTWOOD\"\n\t\tself.definitions = [u'wood from fast-growing evergreen trees (= ones that never lose their leaves) like pine, or a tree of this type: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_softwood.py","file_name":"_softwood.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"103840127","text":"from random import choice\n\nfrom django.core.management.base import BaseCommand\n\nfrom friprosveta.models import Activity, Teacher\nfrom friprosveta.studis import Osebe\nfrom timetable.models import Allocation\n\n\nclass Command(BaseCommand):\n def add_arguments(self, parser):\n parser.add_argument(\"ids\", nargs=\"+\", type=int, help=\"durations of splits\")\n\n def handle(self, *args, **options):\n # if len(args) < 2:\n # print(\"Razporedi pedagoge na diplome. Sprejme id-je realizacij.\")\n # print(\"./manage.py razporedi_pedagoge_na_diplome #id_realization_1 ...\")\n # print(\"Za te realizacije morajo biti ustvarjene alokacije, \"\n # \"vse realizacije morajo imeti isto aktivnost.\")\n # print(\"Primer uporabe: razporedi_pedagoge_na_diplome \"\n # \"1234 5678 9874 ...\")\n # return\n\n realizacije_ids = options[\"ids\"]\n print(realizacije_ids)\n osebe = Osebe()\n titles = osebe.get_nazivi()\n teachers = osebe.get_teachers()\n teachers = [\n teacher\n for teacher in teachers\n if (\n teacher[\"sifra_predavatelja\"] is not None\n and teacher[\"sifra_predavatelja\"].startswith(\"630\")\n )\n ]\n\n teacher_titles = [\n \"docent\",\n \"izredni profesor\",\n \"predavatelj\",\n \"redni profesor\",\n \"višji predavatelj\",\n ]\n teacher_titles_ids = [\n title[\"id\"]\n for title in titles\n if title[\"full_title\"][\"sl\"] in teacher_titles\n ]\n teacher_codes = [\n teacher[\"sifra_predavatelja\"]\n for teacher in teachers\n if len(set(teacher[\"habilitacija\"]) & set(teacher_titles_ids)) > 0\n and teacher[\"status_kadrovska\"] == 2\n ]\n\n fri_teachers = Teacher.objects.filter(code__in=teacher_codes)\n allocations = Allocation.objects.filter(\n activityRealization__id__in=realizacije_ids\n )\n self.razporedi(fri_teachers, allocations)\n activity = (\n Activity.objects.filter(realizations__id__in=realizacije_ids)\n .distinct()\n .get()\n )\n for teacher in fri_teachers:\n activity.teachers.add(teacher)\n\n def razporedi(self, teachers, allocations):\n def je_prost(ucitelj, alokacija, proste_ure):\n return all(\n hour in proste_ure[ucitelj][alokacija.day] for hour in alokacija.hours\n )\n\n tt = allocations[0].timetable\n proste_ure = {ucitelj: ucitelj.free_hours(tt, 0.5) for ucitelj in teachers}\n\n alokacije_mozni_ucitelji = {\n alokacija: [\n ucitelj\n for ucitelj in teachers\n if je_prost(ucitelj, alokacija, proste_ure)\n ]\n for alokacija in allocations\n }\n ucitelji_mozne_alokacije = {\n ucitelj: [\n alokacija\n for alokacija in allocations\n if ucitelj in alokacije_mozni_ucitelji[alokacija]\n ]\n for ucitelj in teachers\n }\n\n teachers = sorted(\n teachers, key=lambda ucitelj: len(ucitelji_mozne_alokacije[ucitelj])\n )\n\n alokacija_ucitelj = {alokacija: [] for alokacija in allocations}\n naeno = len(teachers) / len(allocations)\n for teacher in teachers:\n teacher_allocations = ucitelji_mozne_alokacije[teacher]\n found_allocation = None\n for allocation in teacher_allocations:\n if len(alokacija_ucitelj[allocation]) < naeno:\n found_allocation = allocation\n break\n if found_allocation is None:\n found_allocation = choice(teacher_allocations)\n alokacija_ucitelj[found_allocation].append(teacher)\n\n for alokacija in alokacija_ucitelj:\n print(\n alokacija,\n \",\".join(\n [\n \"{0} {1}\".format(\n ucitelj.user.first_name, ucitelj.user.last_name\n )\n for ucitelj in alokacija_ucitelj[alokacija]\n ]\n ),\n )\n alokacija.teachers.clear()\n for ucitelj in alokacija_ucitelj[alokacija]:\n alokacija.teachers.add(ucitelj)\n","sub_path":"friprosveta/management/commands/razporedi_pedagoge_na_diplome.py","file_name":"razporedi_pedagoge_na_diplome.py","file_ext":"py","file_size_in_byte":4533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"47682285","text":"import sys\nsys.path.append('../../')\nfrom tanuki import *\nimport numpy as np\nimport scipy as sp\nimport scipy.optimize as spo\nimport random\nfrom colorama import Fore, Back, Style\nimport math\n\n\n\n# test backward trunc houteisiki is correct\ndef test0210():\n b = 3\n n = b**b\n chi = b-1\n\n H = random_tensor((b,b,n),[\"kl\",\"kr\",\"extraction\"])\n V = H * H.adjoint([\"kl\",\"kr\"],style=\"aster\")\n A = random_tensor((b,b),[\"kl\",\"kr\"])\n ENV = bondenv.UnbridgeBondEnv(V, [\"kl\"], [\"kr\"])\n\n memo = {}\n M,S,N = ENV.optimal_truncate(A, chi=chi, memo=memo)\n B = M*S*N\n D = A - B\n\n ph = tensor_svd(B,\"kl\",svd_labels = \"a\")[2].truncate_index(\"a\",2,3).remove_dummy_indices(\"a\")\n p = ph.conjugate()\n assert B*p==zeros_tensor_like(B*p)\n\n u = A*p\n assert u==D*p\n\n pph = p.replace_labels(\"kr\",\"pphout\",inplace=False)[[]]*ph.replace_labels(\"kr\",\"pphin\",inplace=False)[[]]\n anti_pph = identity_tensor_like(pph) - pph\n\n def functor(G):\n return (G[\"kr\"] * anti_pph[\"pphout\"]).replace_labels(\"pphin\", \"kr\", inplace=False) + u * ph\n\n assert A == functor(A)\n assert D == functor(D)\n assert B+u*ph == functor(B)\n\n def cost(G):\n return (H * functor(G)).norm()\n\n for _ in range(100):\n G = random_tensor_like(D)\n assert cost(G) > cost(D)\n\n niseu = random_tensor_like(u)\n assert abs(cost(u*ph) - cost(niseu*ph)) < 1e-5\n assert cost(niseu*ph) > cost(D)\n assert abs(cost(D) - cost(D+niseu*ph)) < 1e-5\n\n assert cost(A) > cost(D)\n assert cost(B) > cost(D)\n\n\n HETA = H\n HETAh = H.adjoint([\"kl\",\"kr\"],style=\"aster\")\n ETA = V\n HZETA = (anti_pph[\"pphin\"]*H[\"kr\"]).replace_labels(\"pphout\",\"kr\",inplace=False)\n HZETAh = HZETA.adjoint([\"kl\",\"kr\"],style=\"aster\")\n ZETA = HZETA * HZETAh\n HCV = HETA*u*ph\n\n assert np.linalg.matrix_rank(ZETA.to_matrix([\"kl\",\"kr\"])) == b*b-b\n\n def costVector(G):\n return HZETA*G + HCV\n\n for _ in range(10):\n G = random_tensor_like(D)\n assert abs( costVector(G).norm() - cost(G) ) < 1e-5\n\n assert abs(costVector(D).norm() - cost(D)) < 1e-5\n\n def tensor_to_real_vector(G):\n G = G.to_vector([\"kl\",\"kr\"])\n G = np.concatenate([np.real(G), np.imag(G)])\n return G\n\n def real_vector_to_tensor(G):\n G = G[:b*b] + 1.0j*G[b*b:]\n G = vector_to_tensor(G, (b,b), [\"kl\",\"kr\"])\n return G\n\n def tensor_to_real_costVector(CV):\n CV = CV.to_vector([\"extraction\"])\n CV = np.concatenate([np.real(CV), np.imag(CV)])\n return CV\n\n\n\n\n\n def wrapped_costVector(G):\n G = real_vector_to_tensor(G)\n CV = costVector(G)\n return tensor_to_real_costVector(CV)\n\n #print(wrapped_costVector(D.to_vector([\"kl\",\"kr\"])))\n\n\n G = random_tensor_like(D)\n G = tensor_to_real_vector(G)\n optG = spo.leastsq(wrapped_costVector, G)[0]\n optG = real_vector_to_tensor(optG)\n fnctOptG = functor(optG)\n assert abs(cost(optG) - cost(fnctOptG)) < 1e-5\n assert abs(cost(fnctOptG) - cost(D)) < 1e-5\n assert fnctOptG == D\n\n\n assert optG * ZETA + HCV*HZETAh \n print(fnctOptG * ZETA + HCV*HZETAh)\n print(fnctOptG * HZETA * HETAh + HCV*HETAh)\n\n\n\n# test backward opttrunc repeating doesn't give correct optimal_trunc\ndef test0211():\n b = 7\n n = b**b\n\n H = random_tensor((b,b,n),[\"kl\",\"kr\",\"extraction\"])\n V = H * H.adjoint([\"kl\",\"kr\"],style=\"aster\")\n A = random_tensor((b,b),[\"kl\",\"kr\"])\n ENV = bondenv.UnbridgeBondEnv(V, [\"kl\"], [\"kr\"])\n\n memo = {}\n M,S,N = ENV.optimal_truncate(A, chi=b-1, memo=memo)\n A1 = M*S*N\n print(memo[\"iter_times\"])\n memo = {}\n M,S,N = ENV.optimal_truncate(A1, chi=b-2, memo=memo)\n A11 = M*S*N\n print(memo[\"iter_times\"])\n memo = {}\n M,S,N = ENV.optimal_truncate(A, chi=b-2, memo=memo)\n A2 = M*S*N\n print(memo[\"iter_times\"])\n\n print(A11-A2)\n\n\n\ntest0211()\n\n","sub_path":"experiments/day02/epm021.py","file_name":"epm021.py","file_ext":"py","file_size_in_byte":3854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"615157649","text":"\"\"\"\nIn this script, only a list of string is defined.\nThis is supposed to be the full list of activities in service mode that will be done in factory.\nAdd more or delete as your interesting to save calculation time.\n\"\"\"\n\nStringFunctionTables = [\n # \"Adj_PHS\", # 0\n # \"Adj_RSA\", # 1\n # \"Adj_FAD\", # 2\n # \"Adj_GET\", # 3\n # \"Adj_ZAD\", # 4\n # \"Tbg_DefChan\", # 5\n # \"Adj_FAL\", # 6\n # \"Adj_GAD\",\n # \"Adj_DSC\",\n # \"Tbg_AirCal\",\n \"Tbg_ChanCorr\",\n # \"Tbg_Spacing\",\n # \"Tbg_WaterBeamHardCorrection\",\n # \"Tbg_WaterScaling\",\n # \"Qua_Slice_IEC\",\n # \"Qua_Slice_ConstRef\",\n # \"Qua_Contrast_IEC\",\n # \"Qua_Contrast_ConstRef\",\n # \"Qua_Noise_ConstRef\",\n # \"Qua_Homogeneity_ConstRef\",\n # \"Qua_MTF_IEC\",\n # \"Qua_MTF_ConstRef\",\n # \"Qua_TubeVoltage_ConstRef\",\n # \"Qua_TubeVoltage_IEC\",\n # \"Qua_TubePowerLevel_DHHS\",\n # \"Qua_TubePowerLevel_IEC\",\n # \"Qua_ScanDuration_DHHS\",\n # \"Tbg_AirCal_BascalOnly\",\n \"Qua_Homogeneity_IEC\",\n # \"Qua_Noise_IEC\",\n # \"QuaSlice\",\n # \"QuaHomogeneity\",\n # \"QuaNoise\",\n # \"QuaMTF\",\n # \"QuaContrast\",\n # \"Qua_SagCorLightmarker_IEC\",\n # \"Qua_SagCorLightmarker_ConstRef\",\n # \"Qua_Lightmarker_IEC\",\n # \"Qua_TopoPos_IEC\",\n # \"Qua_TablePos_IEC\",\n # \"Qua_Lightmarker_ConstRef\",\n # \"Qua_TopoPos_ConstRef\",\n # \"Qua_TablePos_ConstRef\",\n # \"Qua_LowContrast_IEC\",\n # \"Qua_LowContrast_ConstRef\",\n # \"Qua_CTDIDose_IEC\",\n # \"Qua_TopoDose_IEC\",\n # \"Qua_CTDIDose_ConstRef\",\n # \"Qua_BeamQuality_DHHS\",\n # \"Qua_IECCTDIHEADID_IEC\",\n # \"Qua_IECCTDIHEADID_ConstRef\",\n # \"Qua_CTDIHEADID_DHHS\",\n # \"QuaIECCTDIBODYID\",\n # \"Qua_IECCTDIBODYID_IEC\",\n # \"Qua_IECCTDIBODYID_ConstRef\",\n # \"Qua_CTDIBODYID_DHHS\",\n # \"Qua_DoseProfile_IEC\",\n # \"Adj_FAD_Check\",\n # \"Tbg_AirCal_CusCalib_BascalOnly\",\n \"Tst_BAT_Factory\",\n]\n\nStringResultTable = [\n \"Success\",\n \"NotOkError\",\n # \"Cancel\",\n]\n##############################################\n\nif __name__ == '__main__':\n print(\"please do not use it individually.\")\n","sub_path":"EnumFunctionTable.py","file_name":"EnumFunctionTable.py","file_ext":"py","file_size_in_byte":2266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"487907547","text":"\"\"\"\nDjango settings for notify project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.6/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.6/ref/settings/\n\"\"\"\n\n#Django suit imports\n#________________________________\nfrom django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP\nTEMPLATE_CONTEXT_PROCESSORS = TCP + (\n 'django.core.context_processors.request',\n)\n#________________________________\n\n#Django Registration Settings\n#________________________________\n\nACCOUNT_ACTIVATION_DAYS=7\n# EMAIL_HOST = 'amninder@narota.com'\n# EMAIL_PORT = 1025\n# EMAIL_HOST_USER = \"\"\n# EMAIL_HOST_PASSWORD = \"\"\n# EMAIL_USE_TLS = False\n# DEFAULT_FROM_EMAIL = 'amninder@narota.com'\n\n#________________________________\n\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\nIOS_NOTIFICATIONS_AUTHENTICATION = \"AuthBasicIsStaff\" #`AuthBasic`, `AuthBasicIsStaff` or `AuthNone`\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = '8m1h!$64otr*g52%&xq5#&4f6rickuq&e+b!7-mz-be2+9wb(u'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nTEMPLATE_DEBUG = True\n\nALLOWED_HOSTS = [\"0.0.0.0\", \"127.0.0.1\"]\n\n\n# Application definition\n\n\nINSTALLED_APPS = (\n # Django_Admin_Bootstrapped 3\n #___________________________\n\n #'django_admin_bootstrapped.bootstrap3',\n #'django_admin_bootstrapped',\n\n #___________________________\n\n # Django_Admin_Suit\n #___________________________\n \n 'suit', \n \n #___________________________\n\n\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.humanize',\n 'ios_notifications',\n 'registration',\n 'rest_framework',\n 'test_module',\n 'device',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'notify.urls'\n\nWSGI_APPLICATION = 'notify.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.6/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.6/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.6/howto/static-files/\nSTATIC_ROOT = os.path.join(BASE_DIR, 'static')\nSTATIC_URL = '/static/'\n\nTEMPLATE_DIRS = (\n os.path.join(BASE_DIR, 'templates/'),\n)\n\n# REST_FRAMEWORK\nREST_FRAMEWORK = {\n # Use hyperlinked styles by default.\n # Only used if the `serializer_class` attribute is not set on a view.\n 'DEFAULT_MODEL_SERIALIZER_CLASS':\n 'rest_framework.serializers.HyperlinkedModelSerializer',\n\n # Use Django's standard `django.contrib.auth` permissions,\n # or allow read-only access for unauthenticated users.\n 'DEFAULT_PERMISSION_CLASSES': [\n 'rest_framework.permissions.IsAuthenticated' #AllowAny\n ]\n}\n\n\n","sub_path":"notify/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"311487443","text":"'''\nAuthors: Donnie Marino, Kostas Stamatiou\nContact: dmarino@digitalglobe.com\n\nUnit tests for the gbdxtools.Catalog class\n'''\n\nfrom gbdxtools import Interface\nfrom gbdxtools.catalog import Catalog\nimport vcr\nfrom auth_mock import get_mock_gbdx_session\n\n# How to use the mock_gbdx_session and vcr to create unit tests:\n# 1. Add a new test that is dependent upon actually hitting GBDX APIs.\n# 2. Decorate the test with @vcr appropriately\n# 3. replace \"dummytoken\" with a real gbdx token\n# 4. Run the tests (existing test shouldn't be affected by use of a real token). This will record a \"cassette\".\n# 5. replace the real gbdx token with \"dummytoken\" again\n# 6. Edit the cassette to remove any possibly sensitive information (s3 creds for example)\nmock_gbdx_session = get_mock_gbdx_session(token=\"dummytoken\")\ngbdx = Interface(gbdx_connection = mock_gbdx_session)\n\ndef test_init():\n c = Catalog(gbdx)\n assert isinstance(c, Catalog)\n\n@vcr.use_cassette('tests/unit/cassettes/test_catalog_get_address_coords.yaml',filter_headers=['authorization'])\ndef test_catalog_get_address_coords():\n\tc = Catalog(gbdx)\n\tlat, lng = c.get_address_coords('Boulder, CO')\n\tassert lat == 40.0149856\n\tassert lng == -105.2705456\n\n@vcr.use_cassette('tests/unit/cassettes/test_catalog_search_point.yaml',filter_headers=['authorization'])\ndef test_catalog_search_point():\n\tc = Catalog(gbdx)\n\tlat = 40.0149856\n\tlng = -105.2705456\n\tresults = c.search_point(lat,lng)\n\n\tassert results['stats']['totalRecords'] == 310\n\n@vcr.use_cassette('tests/unit/cassettes/test_catalog_search_address.yaml',filter_headers=['authorization'])\ndef test_catalog_search_address():\n\tc = Catalog(gbdx)\n\tresults = c.search_address('Boulder, CO')\n\n\tassert results['stats']['totalRecords'] == 310\n\n@vcr.use_cassette('tests/unit/cassettes/test_catalog_search_wkt_only.yaml',filter_headers=['authorization'])\ndef test_catalog_search_wkt_only():\n\tc = Catalog(gbdx)\n\tresults = c.search(searchAreaWkt=\"POLYGON ((30.1 9.9, 30.1 10.1, 29.9 10.1, 29.9 9.9, 30.1 9.9))\")\n\tassert len(results) == 395\n\n@vcr.use_cassette('tests/unit/cassettes/test_catalog_search_wkt_and_startDate.yaml',filter_headers=['authorization'])\ndef test_catalog_search_wkt_and_startDate():\n\tc = Catalog(gbdx)\n\tresults = c.search(searchAreaWkt=\"POLYGON ((30.1 9.9, 30.1 10.1, 29.9 10.1, 29.9 9.9, 30.1 9.9))\",\n\t\t startDate='2012-01-01T00:00:00.000Z')\n\tassert len(results) == 317\n\n@vcr.use_cassette('tests/unit/cassettes/test_catalog_search_wkt_and_endDate.yaml',filter_headers=['authorization'])\ndef test_catalog_search_wkt_and_endDate():\n\tc = Catalog(gbdx)\n\tresults = c.search(searchAreaWkt=\"POLYGON ((30.1 9.9, 30.1 10.1, 29.9 10.1, 29.9 9.9, 30.1 9.9))\",\n\t\t endDate='2012-01-01T00:00:00.000Z')\n\tassert len(results) == 78\n\n@vcr.use_cassette('tests/unit/cassettes/test_catalog_search_startDate_and_endDate_only_more_than_one_week_apart.yaml',filter_headers=['authorization'])\ndef test_catalog_search_startDate_and_endDate_only_more_than_one_week_apart():\n\tc = Catalog(gbdx)\n\n\ttry:\n\t\tresults = c.search(startDate='2004-01-01T00:00:00.000Z',\n\t\t\t\t\t \tendDate='2012-01-01T00:00:00.000Z')\n\texcept Exception as e:\n\t\tpass\n\telse:\n\t\traise Exception('failed test')\n\n\n@vcr.use_cassette('tests/unit/cassettes/test_catalog_search_startDate_and_endDate_only_less_than_one_week_apart.yaml',filter_headers=['authorization'])\ndef test_catalog_search_startDate_and_endDate_only_less_than_one_week_apart():\n\tc = Catalog(gbdx)\n\n\tresults = c.search(startDate='2008-01-01T00:00:00.000Z',\n\t\t\t\t\t \tendDate='2008-01-03T00:00:00.000Z')\n\n\tassert len(results) == 759\n\n\n@vcr.use_cassette('tests/unit/cassettes/test_catalog_search_filters1.yaml',filter_headers=['authorization'])\ndef test_catalog_search_filters1():\n\tc = Catalog(gbdx)\n\n\tfilters = [ \n \"(sensorPlatformName = 'WORLDVIEW01' OR sensorPlatformName ='QUICKBIRD02')\",\n \"cloudCover < 10\",\n \"offNadirAngle < 10\"\n ]\n\n\tresults = c.search(startDate='2008-01-01T00:00:00.000Z',\n\t\t\t\t\t \tendDate='2012-01-03T00:00:00.000Z',\n\t\t\t\t\t \tfilters=filters,\n\t\t\t\t\t \tsearchAreaWkt=\"POLYGON ((30.1 9.9, 30.1 10.1, 29.9 10.1, 29.9 9.9, 30.1 9.9))\")\n\n\tfor result in results:\n\t\tassert result['properties']['sensorPlatformName'] in ['WORLDVIEW01','QUICKBIRD02']\n\t\tassert float(result['properties']['cloudCover']) < 10\n\t\tassert float(result['properties']['offNadirAngle']) < 10\n\n@vcr.use_cassette('tests/unit/cassettes/test_catalog_search_filters2.yaml',filter_headers=['authorization'])\ndef test_catalog_search_filters2():\n\tc = Catalog(gbdx)\n\n\tfilters = [ \n \"sensorPlatformName = 'WORLDVIEW03'\"\n ]\n\n\tresults = c.search(filters=filters,\n\t\t\t\t\t searchAreaWkt=\"POLYGON ((30.1 9.9, 30.1 10.1, 29.9 10.1, 29.9 9.9, 30.1 9.9))\")\n\n\tfor result in results:\n\t\tassert result['properties']['sensorPlatformName'] in ['WORLDVIEW03']\n\n@vcr.use_cassette('tests/unit/cassettes/test_catalog_search_types1.yaml',filter_headers=['authorization'])\ndef test_catalog_search_types1():\n\tc = Catalog(gbdx)\n\n\ttypes = [ \"LandsatAcquisition\" ]\n\n\tresults = c.search(types=types,\n\t\t\t\t\t searchAreaWkt=\"POLYGON ((30.1 9.9, 30.1 10.1, 29.9 10.1, 29.9 9.9, 30.1 9.9))\")\n\n\tfor result in results:\n\t\tassert result['type'] == 'LandsatAcquisition'\n\n@vcr.use_cassette('tests/unit/cassettes/test_catalog_search_huge_aoi.yaml',filter_headers=['authorization'])\ndef test_catalog_search_huge_aoi():\n\t\"\"\"\n\tSearch an AOI the size of utah, broken into multiple smaller searches\n\t\"\"\"\n\tc = Catalog(gbdx)\n\n\tresults = c.search(searchAreaWkt = \"POLYGON((-113.88427734375 40.36642741921034,-110.28076171875 40.36642741921034,-110.28076171875 37.565262680889965,-113.88427734375 37.565262680889965,-113.88427734375 40.36642741921034))\")\n\t\n\tassert len(results) == 2736\n\n@vcr.use_cassette('tests/unit/cassettes/test_catalog_get_data_location_DG.yaml',filter_headers=['authorization'])\ndef test_catalog_get_data_location_DG():\n\tc = Catalog(gbdx)\n\ts3path = c.get_data_location(catalog_id='1030010045539700')\n\tassert s3path == 's3://receiving-dgcs-tdgplatform-com/055158926010_01_003/055158926010_01'\n\n@vcr.use_cassette('tests/unit/cassettes/test_catalog_get_data_location_Landsat.yaml',filter_headers=['authorization'])\ndef test_catalog_get_data_location_Landsat():\n\tc = Catalog(gbdx)\n\ts3path = c.get_data_location(catalog_id='LC81740532014364LGN00')\n\tassert s3path == 's3://landsat-pds/L8/174/053/LC81740532014364LGN00'\n\n@vcr.use_cassette('tests/unit/cassettes/test_catalog_get_data_location_nonexistent_catid.yaml',filter_headers=['authorization'])\ndef test_catalog_get_data_location_nonexistent_catid():\n\tc = Catalog(gbdx)\n\ts3path = c.get_data_location(catalog_id='nonexistent_asdfasdfasdfdfasffds')\n\tassert s3path == None\n\n@vcr.use_cassette('tests/unit/cassettes/test_catalog_get_data_location_catid_with_no_data.yaml',filter_headers=['authorization'])\ndef test_catalog_get_data_location_catid_with_no_data():\n\tc = Catalog(gbdx)\n\ts3path = c.get_data_location(catalog_id='1010010011AD6E00')\n\tassert s3path == None\n\n","sub_path":"tests/unit/test_catalog.py","file_name":"test_catalog.py","file_ext":"py","file_size_in_byte":7023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"381587170","text":"\n\nstring = \"4-'3evh?'c)7%t#e-r,g6u#.9uv#%tg2v#7g'w6gA\"\nfirst=ord('p')-ord('4')\nprint(\"hahahah\\n\"+str(first)) \ntext =[]\nflag=''\nfor i in string:\n k = (ord(i)+first)%126\n if k<65:\n k+=32\n text.append(k)\n flag+=chr((k))\n\nprint(text)\nprint(flag)\n","sub_path":"Cryptography/caesar cipher 2/files/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"285265669","text":"from flask import Flask, render_template, redirect, url_for, request\nimport func\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return render_template('intro.html')\n\n@app.route('/vaccination-sites', methods=[\"POST\", \"GET\"])\ndef findVaccinationSites():\n if request.method == \"POST\":\n\n state = request.form[\"state\"]\n zip_code = request.form[\"zip_code\"]\n\n result = func.findVacinationSiteFunc(state, zip_code)\n\n if (result==\"\"): # if no info is found\n noResult = True\n showSites = False\n else: # information found\n noResult = False\n showSites = True\n\n return render_template(\"vaccination-sites.html\", message=result, showSites=showSites, noResult=noResult)\n\n return render_template(\"vaccination-sites.html\")\n\n@app.route('/covid-stat', methods=[\"POST\", \"GET\"])\ndef getCovidStat():\n if request.method == \"POST\":\n\n state = request.form[\"state\"]\n print(\"in app, state = \" + state)\n total, new, date = func.getCovidStatusFunc(state)\n\n if (total==\"\"): # if no info is found\n noResult = True\n showStat = False\n else: # information found\n noResult = False\n showStat = True\n\n return render_template(\"covid-stat.html\", totalCases=total, newCases=new, date=date, showStat=showStat, noResult=noResult) \n\n return render_template(\"covid-stat.html\")\n\n\n@app.route('/flights', methods=[\"POST\", \"GET\"])\ndef getFlights():\n\n if request.method == \"POST\":\n\n # input = request.form[\"input\"]\n \n departCity = request.form[\"depart\"]\n destCity = request.form[\"dest\"]\n \n departCityCode = func.getCityCode(departCity)\n destCityCode = func.getCityCode(destCity)\n \n\n result = func.getCheapestFlight(departCityCode, destCityCode)\n \n if (result==\"\"): # if no info is found\n noResult = True\n showFlights = False\n else: # information found\n noResult = False\n showFlights = True\n message = \"Status: \" + str(result)\n\n return render_template(\"flights.html\", flights=result, showFlights=True)\n return render_template(\"flights.html\")\n\n@app.route('/hotels', methods=[\"POST\", \"GET\"])\ndef findPlaces():\n if request.method == \"POST\":\n \n theCity = request.form[\"city\"]\n thePostalCode = request.form[\"zip_code\"]\n\n # to display when no hotel is found\n input = theCity + \" city at zip code\" + thePostalCode\n \n # if ((not theCity) or (not thePostalCode)):\n # return render_template(\"places.html\")\n \n result = func.getHotelsFunc(theCity, thePostalCode)\n\n if (result==\"\"): # if no info is found\n noResult = True\n showHotels = False\n else: # information found\n noResult = False\n showHotels = True\n\n return render_template(\"hotels.html\", hotels=result, showHotels=showHotels, noResult=noResult, input=input)\n \n return render_template(\"hotels.html\")\n\n@app.route('/restaurants', methods=[\"POST\", \"GET\"])\ndef findRest():\n if request.method == \"POST\":\n thePostalCode = request.form[\"zip_code\"]\n\n # to display when no hotel is found\n input = \"zip code\" + thePostalCode\n \n # if ((not theCity) or (not thePostalCode)):\n # return render_template(\"places.html\")\n\n print(\"hello\")\n \n result = func.getRestaurants(thePostalCode)\n print(result)\n\n if (result==\"\"): # if no info is found\n noResult = True\n showRes = False\n else: # information found\n noResult = False\n showRes = True\n\n return render_template(\"restaurants.html\", res=result, showRes=showRes, noResult=noResult, input=input)\n \n return render_template(\"restaurants.html\")\n\n\nif __name__ == '__main__':\n app.run(debug = True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"489379598","text":"'''\nYour function should take in a single parameter (a string `word`)\nYour function should return a count of how many occurrences of ***\"th\"*** occur within `word`. Case matters.\nYour function must utilize recursion. It cannot contain any loops.\n'''\nstart = 0\ncount = 0\n\ndef count_th(word):\n global count, start \n # TBC\n if start + 2 > len(word):\n index_count = count\n count = 0 \n start = 0\n return index_count\n if word[start:start+2] == \"th\":\n count += 1\n start += 1\n return count_th(word)\n","sub_path":"recursive_count_th/count_th.py","file_name":"count_th.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"563875316","text":"import hashlib\n\nfrom flask import request, json\nfrom flask_jwt_extended import create_access_token, create_refresh_token, jwt_refresh_token_required, \\\n get_jwt_identity, fresh_jwt_required, jwt_required\nimport decimal\n\nfrom src.models import DID, User\nfrom app import db, app\nfrom . import constants\nfrom .permissions import manager_required\n\n\n@manager_required\ndef add_did():\n print(request.json.get('monthyPrice', 0.00))\n value = request.json.get('value', None)\n monthyPrice = request.json.get('monthyPrice', 0.00)\n setupPrice = request.json.get('setupPrice', 0.00)\n currency = request.json.get('currency', \"R$\")\n if not value:\n response = app.response_class(\n response=json.dumps({'error': 'Submit a valid DID'}),\n status=500,\n mimetype='application/json'\n )\n return response\n if not isinstance(monthyPrice, float) and not isinstance(setupPrice, float):\n response = app.response_class(\n response=json.dumps({'error': 'Monetary values must be greater than or equal to 0.00.'}),\n status=500,\n mimetype='application/json'\n )\n return response\n if monthyPrice < 0 or setupPrice < 0:\n response = app.response_class(\n response=json.dumps({'error': 'Monetary values must be greater than or equal to 0.00.'}),\n status=500,\n mimetype='application/json'\n )\n return response\n try:\n number = DID(\n value=value,\n monthyPrice=monthyPrice,\n setupPrice=setupPrice,\n currency=currency\n )\n number.save_to_db()\n data = json.dumps(number.serialize())\n response = app.response_class(\n response=data,\n status=201,\n mimetype='application/json'\n )\n return response\n except Exception as e:\n response = app.response_class(\n response=json.dumps({'error': e.__str__()}),\n status=500,\n mimetype='application/json'\n )\n return response\n\n\n@jwt_required\ndef get_all():\n print(dict(request.headers))\n try:\n page = int(request.args.get('page', 1))\n page_size = int(request.args.get('page_size', 10))\n if not page > 0 or not page_size > 0:\n return app.response_class(\n response=json.dumps({'error': 'Using only positive integer value in pagination'}),\n status=400,\n mimetype='application/json'\n )\n numbers = DID.query.filter_by(active=True).order_by('id').offset((page - 1) * page_size).limit(page_size)\n data = json.dumps([e.serialize() for e in numbers])\n response = app.response_class(\n response=data,\n status=200,\n mimetype='application/json'\n )\n return response\n except Exception as e:\n response = app.response_class(\n response=json.dumps({'error': e.__str__()}),\n status=500,\n mimetype='application/json'\n )\n return response\n\n\n@fresh_jwt_required\ndef get_by_id(id_):\n try:\n number = DID.query.filter_by(id=id_, active=True).first()\n if number:\n data = json.dumps(number.serialize())\n response = app.response_class(\n response=data,\n status=200,\n mimetype='application/json'\n )\n return response\n response = app.response_class(\n response=json.dumps({'error': 'DID not exist'}),\n status=404,\n mimetype='application/json'\n )\n return response\n except Exception as e:\n response = app.response_class(\n response=json.dumps({'error': e.__str__()}),\n status=500,\n mimetype='application/json'\n )\n return response\n\n\n@manager_required\ndef delete_did(id_):\n try:\n number = DID.query.filter_by(id=id_, active=True).first()\n if number:\n number.active = False\n db.session.commit()\n response = app.response_class(\n response=json.dumps({'msg': 'Deleted'}),\n status=200,\n mimetype='application/json'\n )\n return response\n response = app.response_class(\n response=json.dumps({'error': 'DID not exist'}),\n status=404,\n mimetype='application/json'\n )\n return response\n except Exception as e:\n response = app.response_class(\n response=json.dumps({'error': e.__str__()}),\n status=500,\n mimetype='application/json'\n )\n return response\n\n\n@manager_required\ndef update_did(id_):\n update_labels = ['value', 'monthyPrice', 'setupPrice', 'currency']\n update = {}\n for label in update_labels:\n item = request.json.get(label, None)\n if item:\n if label in ['monthyPrice', 'setupPrice']:\n if not isinstance(item, float):\n response = app.response_class(\n response=json.dumps({'error': 'Monetary values must be greater than or equal to 0.00.'}),\n status=500,\n mimetype='application/json'\n )\n return response\n update[label] = item\n try:\n number = DID.query.filter_by(id=id_, active=True).first()\n if number:\n for label, item in update.items():\n setattr(number, label, item)\n db.session.commit()\n data = json.dumps(number.serialize())\n response = app.response_class(\n response=data,\n status=200,\n mimetype='application/json'\n )\n return response\n response = app.response_class(\n response=json.dumps({'error': 'Number not exist'}),\n status=404,\n mimetype='application/json'\n )\n return response\n except Exception as e:\n response = app.response_class(\n response=json.dumps({'error': e.__str__()}),\n status=500,\n mimetype='application/json'\n )\n return response\n\n\ndef register_user():\n username = request.json.get('username', None)\n password = request.json.get('password', None)\n role = request.json.get('role', None)\n if not role:\n role = constants.ROLES_TYPE[constants.USER]\n if not username or not password or role not in constants.ROLES_TYPE.values():\n response = app.response_class(\n response=json.dumps({'error': 'validation error'}),\n status=500,\n mimetype='application/json'\n )\n return response\n if bool(User.query.filter_by(username=username).first()):\n response = app.response_class(\n response=json.dumps({'error': 'User already exists'}),\n status=500,\n mimetype='application/json'\n )\n return response\n try:\n user = User(username=username, password=hashlib.sha256(password.encode(\"utf-8\")).hexdigest(), role=role)\n user.save_to_db()\n data = json.dumps(user.serialize())\n response = app.response_class(\n response=data,\n status=201,\n mimetype='application/json'\n )\n return response\n except Exception as e:\n response = app.response_class(\n response=json.dumps({'error': e.__str__()}),\n status=500,\n mimetype='application/json'\n )\n return response\n\n\ndef login_user():\n username = request.json.get('username', None)\n password = request.json.get('password', None)\n if not username or not password:\n response = app.response_class(\n response=json.dumps({'error': 'Send username and password.'}),\n status=500,\n mimetype='application/json'\n )\n return response\n user = User.query.filter_by(username=username).first()\n if user and user.password == hashlib.sha256(password.encode(\"utf-8\")).hexdigest():\n access_token = create_access_token(identity=user.id, fresh=True) # Puts User ID as Identity in JWT\n refresh_token = create_refresh_token(identity=user.id)\n data = json.dumps({\n 'access_token': access_token,\n 'refresh_token': refresh_token,\n 'user': user.serialize()\n })\n response = app.response_class(\n response=data,\n status=200,\n mimetype='application/json'\n )\n return response\n response = app.response_class(\n response=json.dumps({'error': 'The password entered is incorrect.'}),\n status=500,\n mimetype='application/json'\n )\n return response\n\n\n@jwt_refresh_token_required\ndef refresh():\n current_user_id = get_jwt_identity() # Gets Identity from JWT\n new_token = create_access_token(identity=current_user_id, fresh=False)\n data = json.dumps({\n 'access_token': new_token,\n })\n response = app.response_class(\n response=data,\n status=200,\n mimetype='application/json'\n )\n return response\n","sub_path":"src/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":9226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"647667936","text":"from flask import Flask, render_template, request, redirect, url_for,flash\nfrom flask_mysqldb import MySQL\n\n\n#MySQL conexion\napp = Flask(__name__)\n# app.config['MYSQL_HOST'] = 'localhost'\n# app.config['MYSQL_USER'] = 'root'\n# app.config['MYSQL_PASSWORD'] = 'joel1010'\n# app.config['MYSQL_DB'] = 'proyecto'\n\n\n##\napp.config['MYSQL_HOST'] = 'klbcedmmqp7w17ik.cbetxkdyhwsb.us-east-1.rds.amazonaws.com'\napp.config['MYSQL_USER'] = 'opjxwks2duq0zzvn'\napp.config['MYSQL_PASSWORD'] = 'svvy3izki2iy091o'\napp.config['MYSQL_DB'] = 'g3wb78wfphr3lb7z' \n\n##\n\n#Configuraciones\napp.secret_key='mysecretkey'\n\nmysql = MySQL(app)\n\n\n@app.route('/')\ndef Index():\n conn = mysql.connection.cursor() \n conn.execute('SELECT * FROM contactos')\n data = conn.fetchall()\n \n return render_template('Index.html', contact=data)\n\n@app.route('/Agregar_Contacto', methods=['POST'])\ndef Agregar_Contacto():\n if request.method =='POST' :\n Nombre = request.form['txtNombre']\n Telefono = request.form['txtTelefono']\n Email = request.form['txtEmail'] \n conn = mysql.connection.cursor() \n conn.execute('INSERT INTO contactos (Nombre,Telefono,Email) VALUES (%s, %s, %s)', (Nombre.upper(),Telefono,Email))\n mysql.connection.commit()\n \n flash('Se Agregó correctamente')\n return redirect(url_for('Index'))\n\n@app.route('/Editar_Contacto/')\ndef Editar_Contacto(ContactoId):\n conn = mysql.connection.cursor() \n conn.execute('SELECT * FROM contactos WHERE ContactoId = %s',(ContactoId) )\n data = conn.fetchall()\n return render_template('Editar.html', contact=data[0])\n\n@app.route('/Actualizar/', methods=['POST'])\ndef Actualizar_Contacto(Id):\n if request.method =='POST' :\n Nombre = request.form['txtNombre']\n Telefono = request.form['txtTelefono']\n Email = request.form['txtEmail'] \n conn = mysql.connection.cursor() \n conn.execute('''UPDATE contactos SET \n Nombre = %s,\n Telefono = %s,\n Email=%s\n WHERE ContactoId=%s''', (Nombre,Telefono,Email,Id))\n mysql.connection.commit()\n flash('Contacto Actualizado')\n return redirect(url_for('Index'))\n\n@app.route('/Eliminar_Contacto/')\ndef Eliminar_Contacto(ContactoId):\n conn = mysql.connection.cursor() \n conn.execute('DELETE FROM contactos WHERE ContactoId={0}'.format(ContactoId))\n mysql.connection.commit()\n flash('Contacto Eliminado')\n return redirect(url_for('Index'))\n\n\n\nif __name__ == '__main__':\n app.run(port=3000,debug=True)\n\n\n","sub_path":"App.py","file_name":"App.py","file_ext":"py","file_size_in_byte":2563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"589218388","text":"import LevelBuilder\nfrom sprites import *\ndef render(name,bg):\n # HERO AND SOME PICKUPS\n lb = LevelBuilder.LevelBuilder(name+\".plist\",background=bg)\n lb.addObject(Hero.HeroSprite(x=16, y=16,width=32,height=32)) \n lb.addObject(Crate.CrateSprite(x=500,y=100,width=32, height=32, static='false',angle=45))\n lb.addObject(Crate.CrateSprite(x=500,y=100,width=32, height=32, static='false',angle=45))\n lb.addObject(Crate.CrateSprite(x=500,y=100,width=32, height=32, static='false',angle=45))\n lb.addObject(Pickup.PickupSprite(x=500,y=100,width=32, height=32, static='false',angle=45))\n lb.addObject(BulletTimePickup.BulletTimePickupSprite(x=500,y=200,width=32, height=32, static='false',angle=0))\n #################################################################################################\n lb.addObject(Enemy.EnemySprite(x=1200, y=150,width=199,height=199,angle='0',restitution=0.2,static='false',friction=0.5,density=5 , classname='BlobSprite',firstframe='monsterblob.png'))\n lb.addObject(Enemy.EnemySprite(x=1500, y=150,width=199,height=199,angle='0',restitution=0.2,static='false',friction=0.5,density=5 , classname='BlobSprite',firstframe='monsterblob.png'))\n lb.addObject(Enemy.EnemySprite(x=1845, y=150,width=199,height=199,angle='0',restitution=0.2,static='false',friction=0.5,density=5 , classname='BlobSprite',firstframe='monsterblob.png'))\n ##################################################################################################\n #BULLETS WATCHTOWER TELEPORTER#\n lb.addObject(ZoomTrigger.ZoomTriggerSprite(x=300-115-50,y=250,width=100,height=500,zoom_fact=1.0))\n lb.addObject(ZoomTrigger.ZoomTriggerSprite(x=300,y=320-60,width=128,height=100,zoom_fact=0.16666))\n lb.addObject(ZoomTrigger.ZoomTriggerSprite(x=300+115+50,y=250,width=100,height=500,zoom_fact=1.0))\n lb.addObject(WatchtowerVisual.WatchtowerVisualSprite(x=300, y=92,width=128,height=235-50,angle='0',restitution=0.2,static='true',friction=0.5,density=20,firstframe='watchtower.png' ))\n lb.addObject(Bullet.BulletSprite(x=0, y=0,width=10,height=10,angle='0',restitution=0.5,static='false',friction=0.5,density=3,spawnEvent='onShoot' ))\n lb.addObject(Teleporter.TeleporterSprite(level_id='leveldata/menu'))\n lb.render()","sub_path":"utils/scripts/OOOlevelGen/src/level_backup/level_4_3.py","file_name":"level_4_3.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"109031930","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Standard library imports.\nimport logging\n\n#Related third party imports.\nimport osi3.osi_lane_pb2\n\n#Local application specific imports.\nimport validation.common\n\nfrom validation.osi_utility import is_set\nfrom validation.osi_utility import is_iterable_set\nfrom validation.osi_utility import get_enum_name\nfrom validation.osi_utility import get_enum_value\n\n\n# Names of loggers in the module\nMODULE_LOGGER_NAME = 'v_osi.lane'\nLANE_VALIDATOR_LOGGER_NAME = 'v_osi.lane.LaneValidator'\nROADCONDITION_VALIDATOR_LOGGER_NAME = 'v_osi.lane.RoadConditionValidator'\nLANEPAIR_VALIDATOR_LOGGER_NAME = 'v_osi.lane.LanePairValidator'\n\nLANEBOUNDARY_VALIDATOR_LOGGER_NAME = 'v_osi.lane.LaneBoundaryValidator'\nBOUNDARYPOINT_VALIDATOR_LOGGER_NAME = 'v_osi.lane.LaneBoundary.BoundaryPointValidator'\nBOUNDARYCLASSIFICATION_VALIDATOR_LOGGER_NAME = 'v_osi.lane.LaneBoundary.ClassificationValidator'\n\n# Configure logger for the module\nmodule_logger = logging.getLogger(MODULE_LOGGER_NAME)\n\n# CONSTANTS\nMINIMUM_SURFACE_TEMPERATUE = 0.\n\n\n\nclass LaneValidator:\n \n def __init__(self):\n self.log = logging.getLogger(LANE_VALIDATOR_LOGGER_NAME)\n self._data = None\n self.context = None\n\n def load_data(self, data=None):\n \"\"\"Load decoded data \n By decodaed it is understood as already parsed \"\"\"\n if self._data is None: \n self._data = data\n else:\n self.log.error('Tring to reload data to LaneValidator')\n\n def load_encoded_data(self, encoded_data):\n \"\"\" Load protobuf encoded data \"\"\"\n data = osi3.osi_lane_pb2.Lane()\n data.ParseFromString(encoded_data) \n self.load_data(data)\n\n def validate(self):\n self.log.debug(f'Cheking osi3::Lane object in context \"{self.context}\"')\n\n self._checkID()\n\n # Without field classification present further checks are not possible\n if self._check_classification() is True:\n\n # Check fields within classification\n self._check_is_host_vehicle_lane()\n self._check_centerline_is_driving_direction()\n self._check_road_conditions()\n self._check_lane_pairing()\n\n lane_type = self._check_classificiation_type()\n\n # checks only if classification type is 'TYPE_DRIVING'\n if lane_type == 'TYPE_DRIVING':\n self._check_centerline()\n\n # Perform there checkes only if current lane is not 'TYPE_INTERSECTION'\n if lane_type is not 'TYPE_INTERSECTION':\n self._check_right_adjacent_lane_id()\n self._check_left_adjacent_lane_id()\n self._check_right_lane_boundary_id()\n self._check_left_lane_boundary_id()\n\n # Perform there checkes only if current lane is of 'TYPE_INTERSECTION'\n if lane_type is 'TYPE_INTERSECTION':\n self._check_free_lane_boundary_id()\n\n def _check_right_adjacent_lane_id(self):\n \"\"\" Check if the field is set and all the values are present\"\"\"\n\n if is_iterable_set(self._data.classification, 'right_adjacent_lane_id') is False:\n self.log.warning(f'Field lane.classification.right_adjacent_lane_id is not set in Lane')\n return False\n\n ids = self._data.classification.right_adjacent_lane_id\n is_every_id_valid = True\n\n for one_id in ids:\n id_validator = validation.common.IdentifierValidator()\n id_validator.load_data(one_id)\n result = id_validator.validate()\n is_every_id_valid = is_every_id_valid and result\n\n return is_every_id_valid\n\n def _check_left_adjacent_lane_id(self):\n \"\"\" Check if the field is set and all the values are present\"\"\"\n\n if is_iterable_set(self._data.classification, 'left_adjacent_lane_id') is False:\n self.log.warning(f'Field lane.classification.left_adjacent_lane_id is not set in Lane')\n return False\n\n ids = self._data.classification.left_adjacent_lane_id\n is_every_id_valid = True\n\n for one_id in ids:\n id_validator = validation.common.IdentifierValidator()\n id_validator.load_data(one_id)\n result = id_validator.validate()\n is_every_id_valid = is_every_id_valid and result\n\n return is_every_id_valid\n\n def _check_right_lane_boundary_id(self):\n \"\"\" Check if the field is set and all the values are present\"\"\"\n\n if is_iterable_set(self._data.classification, 'right_lane_boundary_id') is False:\n self.log.warning(f'Field lane.classification.right_lane_boundary_id is not set in Lane')\n return False\n\n ids = self._data.classification.right_lane_boundary_id\n is_every_id_valid = True\n\n for one_id in ids:\n id_validator = validation.common.IdentifierValidator()\n id_validator.load_data(one_id)\n result = id_validator.validate()\n is_every_id_valid = is_every_id_valid and result\n\n return is_every_id_valid\n\n def _check_left_lane_boundary_id(self):\n \"\"\" Check if the field is set and all the values are present\"\"\"\n\n if is_iterable_set(self._data.classification, 'left_lane_boundary_id') is False:\n self.log.warning(f'Field lane.classification.left_lane_boundary_id is not set in Lane')\n return False\n\n ids = self._data.classification.left_lane_boundary_id\n is_every_id_valid = True\n\n for one_id in ids:\n id_validator = validation.common.IdentifierValidator()\n id_validator.load_data(one_id)\n result = id_validator.validate()\n is_every_id_valid = is_every_id_valid and result\n\n return is_every_id_valid\n\n def _check_free_lane_boundary_id(self):\n \"\"\" Check if the field is set and all the values are present\"\"\"\n\n if is_iterable_set(self._data.classification, 'free_lane_boundary_id') is False:\n self.log.warning(f'Field lane.classification.free_lane_boundary_id is not set in Lane')\n return False\n\n ids = self._data.classification.free_lane_boundary_id\n is_every_id_valid = True\n\n for one_id in ids:\n id_validator = validation.common.IdentifierValidator()\n id_validator.load_data(one_id)\n result = id_validator.validate()\n is_every_id_valid = is_every_id_valid and result\n\n return is_every_id_valid\n\n def _check_lane_pairing(self):\n if is_iterable_set(self._data.classification, 'lane_pairing') is False:\n self.log.warning(f'Field lane.classification.lane_pairing is not set in Lane')\n return False\n\n pairs = self._data.classification.lane_pairing\n is_every_pair_valid = True\n\n for pair in pairs:\n pair_validator = LanePairValidator()\n pair_validator.load_data(pair)\n result = pair_validator.validate()\n is_every_pair_valid = is_every_pair_valid and result\n return is_every_pair_valid\n\n def _checkID(self): \n \"\"\" Check ID recives decoded data \"\"\"\n if not is_set(self._data.classification, 'road_condition'):\n self.log.warning(f'Field id is not set in Lane')\n return False\n\n id_validator = validation.common.IdentifierValidator()\n id_validator.load_data(self._data.id)\n id_validator.validate()\n return True\n\n def _check_classification(self):\n \"\"\" Check if field classification is present in Lane object\n If the field is not present return False\n If the field is present return True \"\"\"\n if not is_set(self._data, 'classification'):\n self.log.warning(f'Field classification is not set in Lane object')\n return False\n else:\n return True\n\n def _check_classificiation_type(self):\n \"\"\" Check for presence of classification.type field \n If the field is not present return False\n If the field is present return True \"\"\"\n if not is_set(self._data.classification, 'type'):\n self.log.warning('The field \"type\" is not present in Lane.classification')\n return False\n else:\n self.log.debug(f'Field classification has valeu of '\n f'({self._data.classification.type})')\n\n # Here I need additional information about OSI-protobuf \n enum_wrapper = osi3.osi_lane_pb2.Lane.Classification.Type\n type_name = get_enum_name(enum_wrapper, self._data.classification.type)\n self.log.debug(f'Lane.Classification.type name is set to \"{type_name}\"')\n return str(type_name) \n\n def _check_centerline(self):\n \"\"\" Check if centerline is valid \"\"\"\n cl = self._data.classification.centerline\n\n is_every_vertex_valid = True\n\n for index,vertex in enumerate(cl):\n v3D_validator = validation.common.Vector3dValidator()\n v3D_validator.load_data(vertex)\n result = v3D_validator.validate()\n is_every_vertex_valid = is_every_vertex_valid and result\n\n if is_every_vertex_valid is True:\n self.log.debug('line.classification.centerline is valid.')\n return False\n\n if is_every_vertex_valid is False:\n self.log.warning('line.classification.centerline is not valid')\n return True\n\n def _check_is_host_vehicle_lane(self):\n \"\"\" Check if field is_host_vehicle_lane is set and valid \"\"\"\n if not is_set(self._data.classification,'is_host_vehicle_lane'):\n self.log.warning('Field classification.is_host_vehicle is not set in Lane object')\n return False\n self.log.debug(f'Lane.classification.is_host_vehicle_lane field is set'\n f' to {self._data.classification.is_host_vehicle_lane}')\n return True \n\n def _check_road_conditions(self):\n \"\"\" Checking RoadConditions validity \"\"\"\n if not is_set(self._data.classification, 'road_condition'):\n self.log.warning(f'Field road_condition is not set in Lane.classification')\n return False\n\n rc = RoadConditionValidator()\n rc.load_data(self._data.classification.road_condition)\n rc.validate()\n return True\n\n def _check_centerline_is_driving_direction(self):\n \"\"\" Check if centerline is sorted ascending or descending \"\"\"\n if not is_set(self._data.classification, 'centerline_is_driving_direction'):\n self.log.warning('Boolean field \"centerline_is_driving_direction\" has not been set')\n return False\n self.log.debug(f'Field Lane.classification.centerline_is_driving_direction'\n f'is set to {self._data.classification.centerline_is_driving_direction}')\n return True\n\nclass RoadConditionValidator:\n\n def __init__(self):\n self.log = logging.getLogger(ROADCONDITION_VALIDATOR_LOGGER_NAME)\n self._data = None\n\n def load_data(self, data=None):\n \"\"\"Load decoded data \n By decodaed it is understood as already parsed \"\"\"\n if self._data is None: \n self._data = data\n else:\n self.log.error('Tring to reload data to RoadConditions') \n\n def validate(self):\n self.log.debug(f'Cheking osi3::Lane::RoadConditions object')\n\n self._check_surface_temperature()\n self._check_water_film()\n self._check_surface_freezing_point()\n self._check_surface_ice()\n self._check_surface_roughness()\n self._check_surface_texture()\n\n def _check_surface_temperature(self):\n \"\"\"Checking if Road Suftace temparature is higher the minimum value \"\"\"\n if not is_set(self._data,'surface_temperature'):\n self._log.warning(f'Road surface temperature is not set')\n return False\n\n st = self._data.surface_temperature\n \n if st < MINIMUM_SURFACE_TEMPERATUE:\n self.log.warning(f'Surface temperature ({st} Kelvins) outside permitd range')\n return False\n else:\n self.log.info(f'Surface temperature ({st} Kelvins) is valid')\n return True\n\n def _check_water_film(self):\n \"\"\"Checking the depth of water film on the road surface\n The value is in milimiters [mm]\n \"\"\"\n if not is_set(self._data,'surface_water_film'):\n self._log.warning(f'Road Surface water film is not set')\n return False\n\n wf = self._data.surface_water_film\n \n if wf < 0:\n self.log.warning(f'Depth of water film on road surface can not be negative')\n return False\n else:\n self.log.info(f'Surface water film ({wf} [mm]) is valid')\n return True \n\n def _check_surface_freezing_point(self):\n \"\"\" Check freezing point \n The value is in Kelvins [K]\n \"\"\"\n if not is_set(self._data,'surface_freezing_point'):\n self._log.warning(f'Road Surface freezing point is not set')\n return False\n\n fp = self._data.surface_freezing_point\n \n if fp < 0:\n self.log.warning(f'Road Surface freezing point can not be negative')\n return False\n else:\n self.log.info(f'Surface frezzing point ({fp} [K]) is valid')\n return True\n\n def _check_surface_ice(self):\n \"\"\" Check ice depth of the surface\"\"\"\n if not is_set(self._data,'surface_ice'):\n self._log.warning(f'Road Surface ice is not set')\n return False\n\n ice = self._data.surface_ice\n\n if ice < 0:\n self.log.warning(f'Depth of ice film on road surface can not be negative')\n return False\n else:\n self.log.info(f'Surface ice film ({ice} [mm]) is valid')\n return True\n\n def _check_surface_roughness(self):\n \"\"\" Check ice depth of the surface\"\"\"\n if not is_set(self._data,'surface_roughness'):\n self._log.warning(f'Road Surface roughness is not set')\n return False\n\n roughness = self._data.surface_roughness\n\n if roughness < 0:\n self.log.warning(f'Road surface roughness can not be negative')\n return False\n else:\n self.log.info(f'Surface roughness ({roughness} [mm/m]) is valid')\n return True\n\n def _check_surface_texture(self):\n \"\"\" Check ice depth of the surface\"\"\"\n if not is_set(self._data,'surface_texture'):\n self._log.warning(f'Road Surface texture is not set')\n return False\n\n texture = self._data.surface_texture\n\n if texture < 0:\n self.log.warning(f'Road surface texture can not be negative')\n return False\n else:\n self.log.info(f'Surface texture ({texture} [m]) is valid')\n return True\n\nclass LanePairValidator:\n\n def __init__(self):\n self.log = logging.getLogger(LANEPAIR_VALIDATOR_LOGGER_NAME)\n self._data = None\n\n def load_data(self, data=None):\n \"\"\"Load decoded data \n By decodaed it is understood as already parsed \"\"\"\n if self._data is None: \n self._data = data\n else:\n self.log.error('Tring to reload data to LanePair') \n\n def validate(self):\n self.log.debug(f'Cheking osi3::Lane.classification.lane_pairing object')\n\n result_a = self._check_antecessor()\n result_b = self._check_successor()\n return result_a and result_b\n\n def _check_antecessor(self):\n id_validator = validation.common.IdentifierValidator()\n id_validator.load_data(self._data.antecessor_lane_id)\n result = id_validator.validate()\n\n def _check_successor(self):\n id_validator = validation.common.IdentifierValidator()\n id_validator.load_data(self._data.successor_lane_id)\n result = id_validator.validate()\n\nclass LaneBoundaryValidator:\n def __init__(self):\n self.log = logging.getLogger(LANEBOUNDARY_VALIDATOR_LOGGER_NAME)\n self._data = None\n self.context = None\n\n def load_data(self, data=None):\n \"\"\"Load decoded data \n By decodaed it is understood as already parsed \"\"\"\n if self._data is None: \n self._data = data\n else:\n self.log.error('Tring to reload data to LaneBoundaryValidator')\n\n def load_encoded_data(self, encoded_data):\n \"\"\" Load protobuf encoded data \"\"\"\n data = osi3.osi_lane_pb2.LaneBoundary()\n data.ParseFromString(encoded_data) \n self.load_data(data)\n\n def validate(self):\n self.log.debug(f'Cheking osi3::LaneBoundary object in context \"{self.context}\"')\n \n result_a = self._check_id()\n result_b = self._check_boundary_line()\n result_c = self._check_classification()\n\n is_object_valid = result_a and result_b and result_c\n\n if is_object_valid:\n self.log.info('LaneBoundary object was found to be valid')\n else:\n self.log.warning('LaneBoundary object is not valid')\n\n return is_object_valid\n\n def _check_id(self):\n id_validator = validation.common.IdentifierValidator()\n id_validator.load_data(self._data.id)\n result = id_validator.validate()\n return result \n\n def _check_boundary_line(self):\n \"\"\" Field boundary_line iterable containging BoudaryPoint objects \"\"\"\n if is_iterable_set(self._data, 'boundary_line') is False:\n self.log.warning(f'Field boundary_line is not set in LaneBoundary')\n return False\n\n points = self._data.boundary_line\n is_every_point_valid = True\n\n for point in points:\n bp_validator = BoundaryPointValidator()\n bp_validator.load_data(point)\n result = bp_validator.validate()\n is_every_point_valid = is_every_point_valid and result\n\n return is_every_point_valid\n\n def _check_classification(self):\n cl_validator = BoundaryLineClassificationValidator(self._data.classification)\n result = cl_validator.validate()\n return result\n\nclass BoundaryPointValidator:\n\n def __init__(self):\n self.log = logging.getLogger(BOUNDARYPOINT_VALIDATOR_LOGGER_NAME)\n self._data = None\n\n def load_data(self, data=None):\n \"\"\"Load decoded data \n By decodaed it is understood as already parsed \"\"\"\n if self._data is None: \n self._data = data\n else:\n self.log.error('Tring to reload data to BoundaryPoint') \n\n def validate(self):\n self.log.debug(f'Cheking osi3.LaneBoundary.BoundaryPoint object')\n\n result_a = self._check_position()\n result_b = self._check_width()\n result_c = self._check_height()\n \n is_point_valid = result_a and result_b and result_c\n\n return is_point_valid\n\n def _check_position(self):\n v3D_validator = validation.common.Vector3dValidator()\n v3D_validator.load_data(self._data.position)\n result = v3D_validator.validate()\n return result\n\n def _check_width(self):\n is_present = is_set(self._data, 'width')\n if is_present:\n self.log.debug(f'Width of the point is {self._data.width}')\n else:\n self.log.warning(f'Width of the point is not set')\n return is_present\n\n def _check_height(self):\n is_present = is_set(self._data, 'height')\n if is_present:\n self.log.debug(f'Height of the point is {self._data.height}')\n else:\n self.log.warning(f'Height of the point is not set')\n return is_present\n \n\nclass BoundaryLineClassificationValidator:\n def __init__(self, data):\n self.log = logging.getLogger(BOUNDARYCLASSIFICATION_VALIDATOR_LOGGER_NAME)\n self._data = data\n \n def validate(self):\n self.log.debug(f'Cheking osi3.LaneBoundary.BoundaryPoint object')\n\n result_a = self._check_type()\n result_b = self._check_color()\n result_c = self._check_limiting_structure_id()\n \n is_point_valid = result_a and result_b and result_c\n\n return is_point_valid\n\n def _check_type(self):\n \"\"\"Enum value of type\"\"\"\n\n # Here I need additional information about OSI-protobuf \n enum_wrapper = osi3.osi_lane_pb2.LaneBoundary.Classification.Type\n type_name = get_enum_name(enum_wrapper, self._data.type)\n self.log.debug(f'LaneBoundry.Classification.type name is set to \"{type_name}\"')\n if len(type_name):\n return True\n else:\n return False \n\n def _check_color(self):\n \"\"\" Enum value of color\"\"\"\n enum_wrapper = osi3.osi_lane_pb2.LaneBoundary.Classification.Type\n type_name = get_enum_name(enum_wrapper, self._data.color)\n self.log.debug(f'LaneBoundry.Classification.type name is set to \"{type_name}\"')\n if len(type_name):\n return True\n else:\n return False \n\n def _check_limiting_structure_id(self):\n \"\"\" Repeated field idicating structure ID\"\"\"\n if is_iterable_set(self._data, 'limiting_structure_id') is False:\n self.log.warning(f'Field LaneBoundary.Classification.limiting_structure_id is not set in LaneBoundary')\n return False\n\n ids = self._data.limiting_structure_id\n is_every_id_valid = True\n\n for one_id in ids:\n id_validator = validation.common.IdentifierValidator()\n id_validator.load_data(one_id)\n result = id_validator.validate()\n is_every_id_valid = is_every_id_valid and result\n\n return is_every_id_valid\n","sub_path":"code/validation/lane.py","file_name":"lane.py","file_ext":"py","file_size_in_byte":21779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"173833454","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nclass Solution(object):\n def solveSudoku(self, board):\n \"\"\"\n :type board: List[List[str]]\n :rtype: void Do not return anything, modify board in-place instead.\n \"\"\"\n self.solve(0, board)\n\n def solve(self, cur, board):\n if cur == 81:\n return True\n row, col = cur / 9, cur % 9\n\n # Recursive: check the next cell\n if board[row][col] != '.':\n return self.solve(cur+1, board)\n\n # Current cell is '.', put one possible num here and do the recursive\n # If no succeed in this num, just backtracking.\n available_nums = self.getAvailableNums(\n board,\n row,\n col)\n\n if not available_nums:\n return False\n\n for val in available_nums:\n row_list = list(board[row])\n row_list[col] = val\n board[row] = ''.join(row_list)\n if self.solve(cur + 1, board):\n return True\n\n # None of the val in available_nums can be put here.\n # And before backtracking, change the current position to '.'\n row_list[col] = '.'\n board[row] = ''.join(row_list)\n\n return False\n\n # Get the available numbers in (row, col)\n def getAvailableNums(self, matrix, row, col):\n used_num = \"\"\n for row_num in matrix[row]:\n if row_num != \".\":\n used_num += row_num\n for col_num in matrix:\n if col_num[col] != \".\":\n used_num += col_num[col]\n block_row = row / 3 * 3\n block_col = col / 3 * 3\n for r in range(block_row, 3 + block_row):\n for c in range(block_col, block_col + 3):\n if matrix[r][c] != \".\":\n used_num += matrix[r][c]\n\n available_nums = \"\"\n for num in \"123456789\":\n if num not in used_num:\n available_nums += num\n\n return available_nums\n\n\"\"\"\nif __name__ == '__main__':\n sol = Solution()\n sudo = [\"..9748...\",\n \"7........\",\n \".2.1.9...\",\n \"..7...24.\",\n \".64.1.59.\",\n \".98...3..\",\n \"...8.3.2.\",\n \"........6\",\n \"...2759..\"]\n sol.solveSudoku(sudo)\n print sudo\n\"\"\"\n","sub_path":"Week06/37.py","file_name":"37.py","file_ext":"py","file_size_in_byte":2366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"34034237","text":"import matplotlib.pyplot as plt # pip install matplotlib\nimport matplotlib.image as mping\n\nplt.suptitle(\"Image Processing\", fontsize=18)\nplt.subplot(1, 2, 1)\nplt.title(\"Original Image\")\nplt.imshow(mping.imread('src.png'))\n\nplt.subplot(122)\nplt.title(\"Pseudo Color Image\")\ndst_img = mping.imread('dst.png')\npseudo_img = dst_img[:, :, 0]\nplt.imshow(pseudo_img)\n\nplt.show()","sub_path":"Chp02/test020805.py","file_name":"test020805.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"4491201","text":"# 1 导入库\nimport cv2\nimport argparse\n\n# 2 获取参数\nparser = argparse.ArgumentParser()\n\n# 3 添加参数\nparser.add_argument(\"video_output\",help=\"the path to the output video\")\n\n# 4 解析参数\nargs = parser.parse_args()\n\n# 5 启动摄像头 (捕获摄像头)\ncapture = cv2.VideoCapture(0) # 0 1 2...共有几个摄像头\n\n# 6 是否打开了摄像头\nif capture.isOpened() is False:\n print(\"Camera Error\")\n\n# 7 获取帧的属性:宽,高,fps\nframe_width = capture.get(cv2.CAP_PROP_FRAME_WIDTH)\nframe_height = capture.get(cv2.CAP_PROP_FRAME_HEIGHT)\nfps = capture.get(cv2.CAP_PROP_FPS)\n\n# 8 对视频进行编码\nfourcc = cv2.VideoWriter_fourcc(*\"XIVD\")\n# 1.路径 2.编码方式 3.帧 4.帧的属性 5.保存形式False 灰 True 彩\noutput_gray = cv2.VideoWriter(args.video_output,fourcc,int(fps),(int(frame_width),int(frame_height)),False)\n\n# 9 读取摄像头\nwhile capture.isOpened():\n ret, frame = capture.read()\n if ret is True:\n # 10 转成灰度保存\n gray_frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\n # 11 写入视频文件中\n output_gray.write(gray_frame)\n # 12 imshow显示\n cv2.imshow(\"gray\",gray_frame)\n # 13\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n else:\n break\n# 14\ncapture.release()\noutput_gray.release()\ncv2.destroyAllWindows()","sub_path":"OpenCV/7read_camera_save_video.py","file_name":"7read_camera_save_video.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"554171969","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\nfrom math import sqrt\nfrom tslearn.preprocessing import TimeSeriesScalerMeanVariance\ndate_parser = pd.to_datetime\n\nclass SeriesSupp:\n \"\"\"Premet d'organiser et de manipuler les données.\n\n Parameters:\n * cwd: String\n chemin d'acces ou le main est excecute\n * factory: Factory\n Instance de la factory\n * dataset_name: String\n Definie le type de donnees a recuperer\n\n Variables:\n * dataset: {Dict}\n Le dataset original sans modification\n * tmp_dataset: {Dict}\n Le dataset actuel avec les modification\n * years: [ARRAY]\n Setup de decoupage par annees\n * months: [ARRAY]\n Setup de decoupage par mois\n * days: [ARRAY]\n Setup de decoupage par annees | [BOOL] decoupage semaines\n * factory: DataFactory\n Instance de la Factory\n * dataset_name: String\n Permet de connaitre la source souhaite e.g import_dataset()\n\n \"\"\"\n def __init__(self, cwd, factory, dataset_name):\n self.cwd = cwd\n self.dataset = {}\n self.tmp_dataset = {}\n self.years = []\n self.months = []\n self.days = False\n self.factory = factory\n self.norm = False\n self.rounded = False\n self.smoothed = False\n self.dataset_name = dataset_name\n self.reset_years()\n\n def __repr__(self):\n \"\"\" Representation de l'instance \"\"\"\n return str(\"Dataset: \" + str(self.dataset_name) + \". De taille source: \" + str(len(self.dataset)) + \". et de taille current: \" + str(len(self.tmp_dataset)))\n\n def reset_years(self):\n \"\"\"Par defaut decoupe les TS dans la granularite maximale\"\"\"\n self.years = [2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015]\n def reset_months(self):\n \"\"\"Par defaut decoupe les TS dans la granularite maximale\"\"\"\n self.months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n def reset_days(self):\n \"\"\"Par defaut decoupe les TS dans la granularite maximale\"\"\"\n self.days = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]\n\n def reset_dataset(self):\n \"\"\" Retourne aux donnees importes avant modifications \"\"\"\n reset = self.dataset.copy()\n self.tmp_dataset = reset\n self.norm = False\n self.days = False\n\n def reset_setup(self):\n \"\"\" Full reset des variables de granularites \"\"\"\n self.reset_years()\n self.reset_months()\n self.reset_days()\n\n def info(self):\n \"\"\" Permet d'avoir une idees des donnees du dataset en prenant une TS au hasard\"\"\"\n k, v = next(iter(self.dataset.items()))\n print(\"Taille du dataset dictionnaire: \" + str(len(self.dataset)))\n print(\"Capteur: \" + k)\n print(v.info())\n print(v.head())\n print(v.tail())\n\n def get_data(self):\n \"\"\" Getter du dataset modifie \"\"\"\n return self.tmp_dataset.copy()\n\n def import_dataset(self):\n \"\"\" Appel a la factory pour recuperer les donnees \"\"\"\n self.dataset = self.factory.get_data(self.dataset_name)\n self.reset_dataset()\n\n def smooth(self, data, wind, col):\n \"\"\"\n Smooth via rolling window\n\n Parameters:\n * data: DataFrame\n La DF a smooth, attention a bien choisir la colonne voulu\n * wind: int\n Taille de fentre\n * col: String\n La colonne de la DF a smooth\n\n Returns:\n data: DataFrame\n La DF remanie\n \"\"\"\n data[col] = data[col].rolling(window = wind, center = True).mean()\n data = data.drop(list(range(len(data) - wind,len(data))))\n data = data.drop(list(range(wind)))\n data.reset_index()\n return data\n\n def dict_smooth(self, wind = 24, col = \"Valeur\"):\n \"\"\"\n Dictionnaire full smooth\n\n Parameters:\n * wind: int\n Taille de la fenetre 24 pour smooth journalier\n * col: str (DEFAUlT = \"Valeur\")\n Colonne cible de l'action\n Returns:\n NA\n \"\"\"\n res = {}\n tampon = self.tmp_dataset.copy()\n for k, v in tampon.items():\n tampon_v = v.copy()\n res[k] = self.smooth(data = tampon_v, wind = wind, col = col)\n self.tmp_dataset = res\n self.smoothed = True\n\n def normalize(self, data):\n \"\"\"\n Normalisation des TS, moyenne: 0 et ecart type: 1\n Data: dataframe\n \"\"\"\n # prepare data for standardization\n values = data.loc[:,(\"Valeur\")]\n values_r = values.values.reshape((len(values), 1))\n # train the standardization\n scaler = StandardScaler()\n scaler = scaler.fit(values_r)\n tr_v = scaler.transform(values_r)\n data[\"Valeur\"] = tr_v\n return data\n\n def standardize(self, data):\n \"\"\"\n Standardize des TS, moyenne: 0 et ecart type: 1\n Data: dataframe\n \"\"\"\n # prepare data for standardization\n values = data[\"Valeur\"]\n values = values.values.reshape((len(values), 1))\n # train the standardization\n t = TimeSeriesScalerMeanVariance().fit_transform(values)\n print(t)\n data[\"valeur\"] = TimeSeriesScalerMeanVariance().fit_transform(values)\n return data\n\n def dict_round(self):\n \"\"\" Normalise un dictionnaire de TS \"\"\"\n for k, v in self.tmp_dataset.items():\n #print(v.shape)\n v = self.rounding(v)\n self.rounded = True\n\n def dict_norm(self):\n \"\"\" Normalise un dictionnaire de TS \"\"\"\n for k, v in self.tmp_dataset.items():\n #print(v.shape)\n v = self.normalize(v)\n self.norm = True\n\n def dict_stand(self):\n \"\"\" Normalise un dictionnaire de TS \"\"\"\n for k, v in self.tmp_dataset.items():\n #print(v.shape)\n v = self.standardize(v)\n self.norm = True\n\n def split_data_years(self):\n \"\"\" Decoupage des TS selon la variable d'annees \"\"\"\n res = {}\n for y in self.years:\n for k, v in self.tmp_dataset.items():\n v = v.set_index(\"Date\")\n try:\n tmp = v[v.index.year == y]\n v = v.reset_index()\n tmp = tmp.reset_index()\n if tmp.shape[0] != 0:\n res[str(k) + \"_\" + str(y) ] = tmp\n except KeyError:\n print(k + \": pas de données en \" + str(y))\n if len(res) != 0:\n self.tmp_dataset = res\n\n def split_data_months(self):\n \"\"\" Decoupage des TS selon la variable de mois \"\"\"\n res = {}\n for m in self.months:\n for k, v in self.tmp_dataset.items():\n v = v.set_index(\"Date\")\n try:\n tmp = v[v.index.month == m]\n v = v.reset_index()\n tmp = tmp.reset_index()\n if tmp.shape[0] != 0:\n if len(str(m)) == 1:\n ret_m = \"0\"+str(m)\n else:\n ret_m = m\n res[str(k) + \"_\" + str(ret_m) ] = tmp\n except KeyError:\n print(k + \": pas de données en \" + str(m))\n if len(res) != 0:\n self.tmp_dataset = res\n\n def split_data_weeks(self):\n \"\"\" Decoupage des TS selon les semaines\"\"\"\n res = {}\n for k, v in self.tmp_dataset.items():\n tmp = v.groupby(pd.Grouper(key='Date', freq='W'))\n for i in tmp:\n if i[1].shape[0] != 0:\n if len(str(i[0].week)) == 1:\n ret_d = \"0\"+str(i[0].week)\n else:\n ret_d = i[0].week\n res[str(k) + \"_\" + str(ret_d) ] = i[1]\n if len(res) != 0:\n self.tmp_dataset = res\n self.days = True\n\n def split_all(self):\n self.split_data_years()\n self.split_data_months()\n if self.days:\n self.split_data_weeks()\n\n def get_data_from_captor(self, cpt):\n \"\"\"\n Retourne toutes les series temporelles liees a un nom de capteur\n\n Parameters:\n * cpt: String\n Nom du capteur desire\n\n Returns:\n res: {Dict}\n Sous dataset du capteur associe, les clefs sont les differente declinaisons en series temporelles du capteur, varie en longueur selon la granularite\n \"\"\"\n res = {}\n for k, v in self.tmp_dataset.items():\n if cpt in k:\n res[k] = v\n return res\n\n ################################################# For precise split where each captor don't compare to itself #################################################\n def split_year_multi_month(self):\n res = {}\n for k, v in self.tmp_dataset.items():\n v = v.set_index(\"Date\")\n tmp = pd.DataFrame({'A' : []})\n try:\n for m in self.months:\n if tmp.empty:\n tmp = v[self.year +\"-\"+ m]\n else:\n tmp = pd.concat([tmp, v[self.year +\"-\"+ m]])\n tmp = tmp.reset_index()\n res[k] = tmp\n except KeyError:\n print(k + \": pas de données en \" + self.year +\"-\"+ str(m))\n self.tmp_dataset = res\n\n def split_year_month_multi_day(self, dataset, month):\n res = {}\n for k, v in dataset.items():\n v = v.set_index(\"Date\")\n tmp = pd.DataFrame({'A' : []})\n try:\n for d in self.days:\n if tmp.empty:\n tmp = v[self.year +\"-\"+ month + \"-\" + d]\n else:\n tmp = pd.concat([tmp, v[self.year +\"-\"+ month + \"-\" + d]])\n tmp = tmp.reset_index()\n res[k] = tmp\n except KeyError:\n print(k + \": pas de données en \" + self.year +\"-\"+ month + \"-\" + d)\n return res\n\n def split_year_multi_month_multi_day(self):\n res = {}\n for k, v in self.tmp_dataset.items():\n v = v.set_index(\"Date\")\n tmp = pd.DataFrame({'A' : []})\n for m in self.months:\n for d in self.days:\n if tmp.empty:\n try:\n tmp = v[str(self.year) +\"-\"+ m + \"-\" + d]\n except KeyError:\n print(k + \": pas de données en \" + self.year +\"-\"+ m +\"-\"+ d)\n else:\n try:\n tmp = pd.concat([tmp, v[str(self.year) +\"-\"+ m +\"-\"+ d]])\n except KeyError:\n print(k + \": pas de données en \" + self.year +\"-\"+ m +\"-\"+ d)\n tmp = tmp.reset_index()\n res[k] = tmp\n self.tmp_dataset = res\n\n def split_each_steps(self):\n res = {}\n if not self.months:\n self.reset_months()\n if not self.days:\n self.reset_days()\n\n for k, v in self.tmp_dataset.items():\n v = v.set_index(\"Date\")\n tmp = pd.DataFrame({'A' : []})\n for y in self.years:\n for m in self.months:\n for d in self.days:\n pass\n","sub_path":"utils/series_supp.py","file_name":"series_supp.py","file_ext":"py","file_size_in_byte":11704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"218371182","text":"import rclpy\nfrom rclpy.node import Node\nfrom geometry_msgs.msg import PoseStamped, Pose\nfrom squaternion import Quaternion\nfrom nav_msgs.msg import Odometry,Path\nfrom math import pi,cos,sin,sqrt\nfrom std_msgs.msg import Bool, String\nfrom nav_msgs.msg import Odometry,Path,OccupancyGrid,MapMetaData\nimport numpy as np\nfrom collections import deque\nimport threading\nfrom heapq import heappop, heappush\nfrom ssafy_msgs.msg import TurtlebotStatus, HandControl\n\n# a_star_local_path 노드는 a_star 노드에서 나오는 전역경로(/global_path)를 받아서, 로봇이 실제 주행하는 지역경로(/local_path)를 publish 하는 노드입니다.\n# path_pub 노드와 하는 역할은 비슷하나, path_pub은 텍스트를 읽어서 global_path를 지역경로를 생성하는 반면, a_star_local_path는 global_path를 다른 노드(a_star)에서 받아서 지역경로를 생성합니다.\n\n\n# 노드 로직 순서\n# 1. publisher, subscriber 만들기\n# 2. global_path 데이터 수신 후 저장\n# 3. 주기마다 실행되는 타이머함수 생성, local_path_size 설정\n# 4. global_path 중 로봇과 가장 가까운 포인트 계산\n# 5. local_path 예외 처리\n\n\nclass astarLocalpath(Node):\n\n def __init__(self):\n super().__init__('a_star_local_path')\n # 로직 1. publisher, subscriber 만들기\n self.local_path_pub = self.create_publisher(Path, 'local_path', 10)\n self.subscription = self.create_subscription(Path,'global_path',self.path_callback,10)\n self.subscription = self.create_subscription(Odometry,'odom',self.listener_callback,10)\n self.subscription = self.create_subscription(OccupancyGrid,'local_map',self.local_map_callback,10)\n self.weed_pub = self.create_publisher(Bool, 'weed', 10)\n self.hand_control_pub = self.create_publisher(HandControl, '/hand_control', 10) \n self.turtlebot_status_sub = self.create_subscription(TurtlebotStatus,'/turtlebot_status',self.turtlebot_status_callback,10)\n\n self.subscription = self.create_subscription(String,'object_distance', self.weed_callback, 10)\n\n self.map_size_x = 350 \n self.map_size_y = 350\n self.map_resolution = 0.05\n\n self.map_offset_x = -50 - 8.75 #-8 - 8.75\n self.map_offset_y = -50 - 8.75 # -4 - 8.75\n self.weed_msg = Bool()\n self.odom_msg=Odometry()\n self.is_odom=False\n self.is_path=False\n self.loadLocalMap = False\n self.global_path_msg = Path()\n\n # 로직 3. 주기마다 실행되는 타이머함수 생성, local_path_size 설정\n time_period = 0.05\n self.timer = self.create_timer(time_period, self.timer_callback)\n self.local_path_size = 15\n self.map_resolution = 0.05\n self.map_offset_x = -50 - 8.75\n self.map_offset_y = -50 - 8.75\n self.GRIDSIZE = 350 \n self.dx = [-1, 0, 0, 1, -1, -1, 1, 1]\n self.dy = [0, 1, -1, 0, -1, 1, -1, 1]\n self.dCost = [1, 1, 1, 1, 1.414, 1.414, 1.414, 1.414]\n self.weed = False\n\n self.hand_control_msg = HandControl() \n self.turtlebot_status_msg = TurtlebotStatus()\n self.is_turtlebot_status = False\n self.hand_control_msg.put_distance = 0.0\n self.hand_control_msg.put_height = 1.5\n\n\n def weed_callback (self, msg) :\n if self.weed == True :\n self.weed_msg.data = True\n self.weed_pub.publish(self.weed_msg)\n return\n object_list = msg.data.split('/')\n if object_list:\n detection = []\n for obj in object_list:\n info = obj.split('-')\n if info[0] == 'weed':\n for dist in info[1:]:\n detection.append([float(dist), info[0]])\n \n detection.sort()\n\n print(detection)\n if detection :\n print(detection[0])\n if detection[0][0] <= 0.2 :\n self.weed_msg.data = True\n self.weed_pub.publish(self.weed_msg)\n self.weed = True\n self.hand_control_pick_up()\n # self.hand_control_put_down()\n self.weed = False\n self.weed_msg.data = False\n self.weed_pub.publish(self.weed_msg)\n\n def hand_control_preview(self):\n while self.turtlebot_status_msg.can_lift == False and self.turtlebot_status_msg.can_put == False and self.turtlebot_status_msg.can_use_hand == True:\n self.hand_control_msg.control_mode = 1\n self.hand_control_pub.publish(self.hand_control_msg)\n\n def hand_control_pick_up(self):\n\n for i in range(100) :\n self.hand_control_msg.control_mode = 2\n self.hand_control_pub.publish(self.hand_control_msg)\n print(self.turtlebot_status_msg.can_put)\n print('up while')\n print(\"pick_up 완료\")\n # self.hand_control_preview()\n \n def hand_control_put_down(self): \n while self.turtlebot_status_msg.can_put == True:\n self.hand_control_msg.control_mode = 3\n self.hand_control_pub.publish(self.hand_control_msg)\n \n print('up while')\n print(\"pick_down 완료\")\n\n def turtlebot_status_callback(self,msg):\n self.is_turtlebot_status = True\n if self.weed == True :\n print('터틀봇 : ', self.turtlebot_status_msg.can_put)\n \n self.turtlebot_status_msg = msg\n\n\n def local_map_callback(self, msg) :\n m = np.array(msg.data)\n self.grid = m.reshape(350, 350, order = 'F')\n self.msg = msg \n self.loadLocalMap = True\n\n\n def listener_callback(self,msg):\n self.is_odom=True\n self.odom_msg=msg\n\n\n def path_callback(self,msg):\n self.is_path = True\n self.global_path_msg = msg\n self.last_current_point = 0\n\n def findLocalPath(self, current_waypoint, collision_point) :\n # self.collision_msg.data = True\n # self.collision_pub.publish(self.collision_msg)\n is_dis_num = 0\n is_cost_num = 0\n min_dis = float('inf')\n min_cost = float('inf')\n is_goal_cost = False\n lenth = len(self.global_path_msg.poses)\n for num in range(collision_point, len(self.global_path_msg.poses)):\n next_x = self.global_path_msg.poses[num].pose.position.x\n next_y = self.global_path_msg.poses[num].pose.position.y\n pose_to_grid = self.pose_to_grid_cell(next_x, next_y)\n cost = self.grid[pose_to_grid[0]][pose_to_grid[1]]\n if cost < 100 :\n if cost < min_cost :\n min_cost = cost\n self.goal_cost = pose_to_grid\n is_goal_cost = True\n\n \n # if cost < 100:\n # x = self.odom_msg.pose.pose.position.x\n # y = self.odom_msg.pose.pose.position.y\n # dis = sqrt(pow(next_x - x, 2) + pow(next_y - y, 2))\n # if dis < min_dis:\n # min_dis = dis\n # self.goal_dis = pose_to_grid\n # is_goal_dis = True\n\n if self.loadLocalMap == False: \n print('더이상 갈 곳이 없다')\n return\n\n\n if is_goal_cost == True :\n self.goal = self.goal_cost\n # elif is_goal_dis == True :\n # self.goal = self.goal_dis\n # else :\n # self.goal = self.pose_to_grid_cell(self.global_path_msg.poses[lenth - 1].pose.position.x, self.global_path_msg.poses[lenth - 1].pose.position.y)\n\n \n\n # print('로컬패스 생성!!! 다익스트라!!! 빠크')\n # local_path_msg = Path()\n # local_path_msg.header.frame_id='/map'\n # self.path = [[0 for col in range(self.GRIDSIZE)] for row in range(self.GRIDSIZE)]\n # self.cost = np.array([[self.GRIDSIZE * self.GRIDSIZE for col in range(self.GRIDSIZE)] for row in range(self.GRIDSIZE)])\n # self.final_path=[]\n # x = self.odom_msg.pose.pose.position.x\n # y = self.odom_msg.pose.pose.position.y\n # start = self.pose_to_grid_cell(x, y)\n # Q = deque()\n # print('start : ', start)\n # print('goal : ', self.goal)\n # Q.append(start)\n # self.cost[start[0]][start[1]] = 1\n # found = False\n # cnt = 0\n # visited = dict()\n # visited[(start[0], start[1])] = True\n\n # while Q : # while Q:\n # current = Q.popleft()\n # cnt += 1\n # if found :\n # break\n # for i in range(8) :\n # next = [current[0] + self.dx[i], current[1] + self.dy[i]]\n # if visited.get((next[0], next[1]), False) : \n # continue\n # if next[0] >= 0 and next[1] >= 0 and next[0] < self.GRIDSIZE and next[1] < self.GRIDSIZE :\n # if self.grid[next[0]][next[1]] < 100 :\n # if self.cost[next[0]][next[1]] > self.cost[current[0]][current[1]] + self.dCost[i]:\n # Q.append(next)\n # self.path[next[0]][next[1]] = current\n # self.cost[next[0]][next[1]] = self.cost[current[0]][current[1]] + self.dCost[i]\n # visited[(next[0], next[1])] = True\n # if next[0] == self.goal[0] and next[1] == self.goal[1]:\n # found = True\n \n # print(found)\n # if found == False :\n # print('들어왔다고 펄스!')\n # print(self.grid[self.goal[0]][self.goal[1]])\n # return\n # node = self.goal\n \n # while node != start :\n # nextNode = node\n # self.final_path.append(nextNode)\n # node = self.path[nextNode[0]][nextNode[1]]\n # print('다익스트라 cnt : ', cnt)\n\n # cnt = 0\n # local_path_msg = Path()\n # local_path_msg.header.frame_id = '/map'\n # size = 0\n # for grid_cell in reversed(self.final_path) :\n # waypoint_x, waypoint_y = self.grid_cell_to_pose(grid_cell)\n # tmp_pose = PoseStamped()\n # tmp_pose.pose.position.x = waypoint_x\n # tmp_pose.pose.position.y = waypoint_y\n # tmp_pose.pose.orientation.w = 1.0\n # local_path_msg.poses.append(tmp_pose)\n\n # self.collision_msg.data = False\n # self.collision_pub.publish(self.collision_msg)\n # self.local_path_pub.publish(local_path_msg)\n\n x = self.odom_msg.pose.pose.position.x\n y = self.odom_msg.pose.pose.position.y\n start = self.pose_to_grid_cell(x, y)\n cost_so_far = { (start[0], start[1]): 0, }\n self.path = [[0 for col in range(self.GRIDSIZE)] for row in range(self.GRIDSIZE)]\n self.final_path=[]\n openlist = []\n cnt = 0\n found = False\n heappush(openlist, [0, start[0], start[1]])\n while openlist:\n current = heappop(openlist)\n cnt += 1\n if current[1] == self.goal[0] and current[2] == self.goal[1]:\n found = True\n break\n\n for i in range(8):\n nx = current[1] + self.dx[i]\n ny = current[2] + self.dy[i]\n\n if 0 <= nx < self.GRIDSIZE and 0 <= ny < self.GRIDSIZE and self.grid[nx][ny] < 100:\n heuristic = int(sqrt(pow(self.goal[0] - nx, 2) + pow(self.goal[1] - ny, 2))) * 2\n cur_cost = cost_so_far[(current[1], current[2])]\n new_cost = cur_cost + self.dCost[i]\n new_f = new_cost + heuristic\n next = (nx, ny)\n if next not in cost_so_far or new_cost < cost_so_far[next]:\n cost_so_far[next] = new_cost\n heuristic = int(sqrt(pow(self.goal[0] - nx, 2) + pow(self.goal[1] - ny, 2))) * 2\n self.path[nx][ny] = [current[1], current[2]]\n heappush(openlist, [new_f, nx, ny])\n if found == False : \n # print('못찾겠다')\n return\n node = [self.goal[0], self.goal[1]]\n while node != start :\n nextNode = node\n self.final_path.append(nextNode)\n node = self.path[nextNode[0]][nextNode[1]]\n\n\n local_path_msg = Path()\n local_path_msg.header.frame_id = '/map'\n size = 0\n for grid_cell in reversed(self.final_path) :\n waypoint_x, waypoint_y = self.grid_cell_to_pose(grid_cell)\n tmp_pose = PoseStamped()\n tmp_pose.pose.position.x = waypoint_x\n tmp_pose.pose.position.y = waypoint_y\n tmp_pose.pose.orientation.w = 1.0\n local_path_msg.poses.append(tmp_pose)\n\n # self.collision_msg.data = False\n # self.collision_pub.publish(self.collision_msg)\n self.local_path_pub.publish(local_path_msg)\n def timer_callback(self):\n if self.weed == True :\n print('잡초제거중')\n return\n if self.loadLocalMap == False: \n print('더이상 갈 곳이 없다')\n return\n\n if self.is_odom and self.is_path == True :\n local_path_msg = Path()\n local_path_msg.header.frame_id = '/map'\n \n x=self.odom_msg.pose.pose.position.x\n y=self.odom_msg.pose.pose.position.y\n\n current_waypoint = -1\n min_dis= float('inf')\n for i, waypoint in enumerate(self.global_path_msg.poses):\n if not (self.last_current_point <= i <= self.last_current_point + 30): continue\n distance = sqrt(pow(x - waypoint.pose.position.x, 2) + pow(y - waypoint.pose.position.y, 2))\n if distance < min_dis :\n min_dis = distance\n current_waypoint = i\n \n '''\n 로직 5. local_path 예외 처리\n '''\n if current_waypoint != -1:\n self.last_current_point = current_waypoint\n if current_waypoint + self.local_path_size < len(self.global_path_msg.poses):\n for num in range(current_waypoint, current_waypoint + self.local_path_size):\n tmp_pose = PoseStamped()\n tmp_pose.pose.position.x = self.global_path_msg.poses[num].pose.position.x\n tmp_pose.pose.position.y = self.global_path_msg.poses[num].pose.position.y\n tmp_pose.pose.orientation.w = 1.0\n temp_pose_to_grid = self.pose_to_grid_cell(tmp_pose.pose.position.x, tmp_pose.pose.position.y)\n \n if self.grid[temp_pose_to_grid[0]][temp_pose_to_grid[1]] >= 50 :\n self.findLocalPath(current_waypoint, num)\n return\n local_path_msg.poses.append(tmp_pose)\n\n else :\n for num in range(current_waypoint, len(self.global_path_msg.poses)):\n tmp_pose = PoseStamped()\n tmp_pose.pose.position.x = self.global_path_msg.poses[num].pose.position.x\n tmp_pose.pose.position.y = self.global_path_msg.poses[num].pose.position.y\n tmp_pose.pose.orientation.w = 1.0\n temp_pose_to_grid = self.pose_to_grid_cell(tmp_pose.pose.position.x, tmp_pose.pose.position.y)\n if self.grid[temp_pose_to_grid[0]][temp_pose_to_grid[1]] >= 50 :\n self.findLocalPath(current_waypoint, num)\n return\n local_path_msg.poses.append(tmp_pose) \n\n self.local_path_pub.publish(local_path_msg)\n\n\n def pose_to_grid_cell(self, x, y):\n map_point_x = int((x - self.map_offset_x) / self.map_resolution)\n map_point_y = int((y - self.map_offset_y) / self.map_resolution)\n return [map_point_x, map_point_y]\n\n\n def grid_cell_to_pose(self,grid_cell):\n x = (grid_cell[0] * self.map_resolution) + self.map_offset_x\n y = (grid_cell[1] * self.map_resolution) + self.map_offset_y \n return [x, y]\n \ndef main(args=None):\n rclpy.init(args=args)\n\n a_star_local = astarLocalpath()\n\n rclpy.spin(a_star_local)\n\n a_star_local.destroy_node()\n rclpy.shutdown()\n\n\nif __name__ == '__main__':\n main()","sub_path":"src/sub2/sub2/a_star_local_path.py","file_name":"a_star_local_path.py","file_ext":"py","file_size_in_byte":16590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"81096134","text":"import os\nimport time\nimport random\nimport pycurl\nimport certifi\n\nfrom tiler import SlippyTiler\nfrom threading import Thread\n\nfrom osgeo import gdal\n\n\nclass TileScraper( Thread ):\n\n def __init__(self, idx, tasks, config ):\n\n \"\"\"\n constructor\n \"\"\"\n\n # init base\n Thread.__init__(self)\n\n # copy arguments \n self._idx = idx\n self._tasks = tasks\n self._tiler = config[ 'tiler' ]\n self._options = config[ 'options' ]\n self._tiles = []\n return\n\n\n def run( self ):\n\n \"\"\"\n constructor\n \"\"\"\n\n # for each task\n for task in self._tasks:\n\n # download tile\n self.getTile( task[ 'url' ], task[ 'pathname'] )\n if os.path.exists ( task[ 'pathname' ] ):\n\n # open newly created tile with gdal\n ds = gdal.Open( task[ 'pathname'] )\n if ds is not None:\n\n # get bounds\n s,w,n,e = self._tiler.TileBounds( *( task[ 'xyz' ] ) )\n\n # setup geotiff translation options\n options = '-of GTiff -co compress=lzw ' \n options += '-a_srs \"{}\" -a_ullr {} {} {} {} '.format ( self._tiler._proj, w, n, e, s )\n \n if self._options is not None:\n options += self._options\n\n try:\n\n # translate png / jpg into geotiff\n pathname = os.path.splitext( task[ 'pathname'] )[ 0 ] + '.tif'\n ds = gdal.Translate( pathname, ds, options=options )\n ds = None\n\n # record pathname of newly created image\n self._tiles.append( pathname )\n\n except Exception as e:\n\n # translation error\n print ( 'Translation Exception: {}'.format( str( e ) ) )\n\n return\n\n\n def getTile( self, url, pathname ):\n\n \"\"\"\n get tile image from https url\n \"\"\"\n \n # retry counters\n tries = 1; max_tries = 3\n while tries <= max_tries:\n\n try:\n\n # setup curl object - include ssl certificates\n curl = pycurl.Curl()\n curl.setopt(pycurl.CAINFO, certifi.where())\n curl.setopt(pycurl.URL, url )\n\n # write binary data to file\n fp = open( pathname, \"wb\" )\n curl.setopt(pycurl.WRITEDATA, fp)\n curl.perform()\n\n # close object and file\n curl.close()\n fp.close()\n\n print ( '{}: {} -> {}'. format( self._idx, url, pathname ))\n break\n\n except Exception as e:\n\n # increment retry counter - wait for random interval\n print ( 'Download Exception {}: {} -> {}'.format( str( e ), url, pathname ) )\n tries += 1\n time.sleep ( random.randrange( 5 ) )\n\n # delete file if download failed \n if tries > max_tries:\n os.remove( pathname )\n\n return \n\n","sub_path":"ingestion/webmap/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":3212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"341295703","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Copyright (C) 2004-2012 Pexego Sistemas Informáticos All Rights Reserved\n# $Marta Vázquez Rodríguez$ \n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\nfrom openerp.osv import osv, fields\nimport decimal_precision as dp\n\nclass mrp_indicators(osv.osv):\n _name = 'mrp.indicators'\n _columns = {\n 'name': fields.char('Name', size=255, required=True),\n 'line_ids': fields.one2many('mrp.indicators.line', 'indicator_id', 'Lines'),\n 'line_average_ids': fields.one2many('mrp.indicators.averages', 'indicator_id', 'Averages'),\n 'date': fields.date('Date'),\n 'user_id': fields.many2one('res.users', 'User'),\n 'company_id': fields.many2one('res.company', 'Company'),\n 'report_name': fields.char('Report', size=255)\n }\nmrp_indicators()\n\nclass mrp_indicators_line(osv.osv):\n _name = 'mrp.indicators.line'\n _columns = {\n 'name': fields.char('Name', size=255, required=True),\n 'date': fields.date('Date'),\n 'workcenter_id': fields.many2one('mrp.workcenter', 'Workcenter'),\n 'qty': fields.float('Qty', digits_compute=dp.get_precision('Product UoM'), required=True),\n 'qty_scraps': fields.float('Scraps', digits_compute=dp.get_precision('Product UoM')),\n 'qty_good': fields.float('Real qty', digits_compute=dp.get_precision('Product UoM')),\n 'product_id': fields.many2one('product.product', 'Product', required=True),\n 'stop_time': fields.float('Stop time'),\n 'real_time': fields.float('Real time'),\n 'tic_time': fields.float('TiC time'),\n 'time_start': fields.float('Time start'),\n 'time_stop': fields.float('Time stop'),\n 'gasoleo_start': fields.float('Gasoleo start'),\n 'gasoleo_stop': fields.float('Gasoleo stop'),\n 'oee': fields.float('OEE'),\n 'availability': fields.float('Availability'),\n 'performance': fields.float('Performance'),\n 'quality': fields.float('Quality'),\n 'indicator_id': fields.many2one('mrp.indicators', 'Indicator', required=True)\n }\nmrp_indicators_line()\n\nclass mrp_indicators_averages(osv.osv):\n _name = 'mrp.indicators.averages'\n _columns = {\n 'name': fields.char('Name', size=255, required=True),\n 'oee': fields.float('OEE'),\n 'availability': fields.float('Availability'),\n 'performance': fields.float('Performance'),\n 'quality': fields.float('Quality'),\n 'indicator_id': fields.many2one('mrp.indicators', 'Incicator', required=True)\n }\nmrp_indicators_averages()\n\nclass mrp_indicators_scrap(osv.osv):\n\n _name = 'mrp.indicators.scrap'\n _columns = {\n 'name': fields.char('Name', size=255, required=True),\n 'line_ids': fields.one2many('mrp.indicators.scrap.line', 'indicator_id', 'Lines'),\n 'date': fields.date('Date'),\n 'user_id': fields.many2one('res.users', 'User'),\n 'company_id': fields.many2one('res.company', 'Company'),\n 'report_name': fields.char('Report', size=255)\n }\n\nmrp_indicators_scrap()\n\nclass mrp_indicators_scrap_line(osv.osv):\n\n _name = 'mrp.indicators.scrap.line'\n _columns = {\n 'name': fields.char('Name', size=255, required=True),\n 'date': fields.date('Date'),\n 'production_id': fields.many2one('mrp.production', 'Production', select=True),\n 'product_id': fields.many2one('product.product', 'Product', select=True),\n 'product_uom': fields.many2one('product.uom', 'Unit of Measure'),\n 'real_qty': fields.float('Real qty.', digits_compute=dp.get_precision('Product UoM')),\n 'theorical_qty':fields.float('Total qty.', digits_compute=dp.get_precision('Product UoM')),\n 'scrap_qty': fields.float('Scrap qty.', digits_compute=dp.get_precision('Product UoM')),\n 'real_cost': fields.float('Real cost', digits_compute=dp.get_precision('Product UoM')),\n 'theorical_cost': fields.float('Theorical cost', digits_compute=dp.get_precision('Product UoM')),\n 'scrap_cost': fields.float('Scrap', digits_compute=dp.get_precision('Product UoM'), select=True),\n 'usage_cost': fields.float('Usage', digits_compute=dp.get_precision('Product UoM'), select=True),\n 'indicator_id': fields.many2one('mrp.indicators.scrap', 'Indicator', required=True),\n }\n\nmrp_indicators_scrap_line()\n","sub_path":"Varios/alimentacion/__unported__/performance_calculation/mrp_indicators.py","file_name":"mrp_indicators.py","file_ext":"py","file_size_in_byte":5141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"517672550","text":"# -*- coding: utf-8 -*-\r\n\r\nfrom django.db import models\r\nfrom django.db import connection\r\nfrom django.conf import settings\r\n\r\n\r\nSGBD_MYSQL = 'M'\r\nSGBD_MONGODB = 'G'\r\nSGBD_CHOICES = (\r\n (SGBD_MYSQL, u'MySQL'),\r\n (SGBD_MONGODB, u'MongoDB'),\r\n)\r\n\r\nMYSQL_SINGLE = 1\r\nMYSQL_HA = 2\r\nMONGODB_SINGLE = 3\r\nMONGODB_REPLICA_SET = 4\r\n\r\n\r\nTOPOLOGIA_CHOICES = (\r\n (MYSQL_SINGLE, u'MySQL Single Instance'),\r\n (MYSQL_HA, u'MySQL HA'),\r\n (MONGODB_SINGLE, u'MongoDB Single Instance'),\r\n (MONGODB_REPLICA_SET, u'MongoDB Replica Set'),\r\n)\r\n\r\nDATABASE_PRODUCAO = 'P'\r\nDATABASE_DEV = 'D'\r\nTIPO_DATABASE_CHOICES = (\r\n (DATABASE_PRODUCAO, u'Produção'),\r\n (DATABASE_DEV, u'DEV'),\r\n)\r\n\r\nTIPO_DATABASE_CHOICES_COLOR = (\r\n (DATABASE_PRODUCAO, (u'Produção', 'LightCyan')),\r\n (DATABASE_DEV,(u'Dev', 'Khaki')),\r\n)\r\n\r\nMONGODB_CD_PRIMARY = '1'\r\nMONGODB_CD_SECONDARY = '2'\r\nMONGODB_CD_ARBITER = '7'\r\n\r\nTIPO_INSTANCIA_MONGODB = (\r\n(MONGODB_CD_PRIMARY, 'Primary'),\r\n(MONGODB_CD_SECONDARY, 'Secondary'),\r\n(MONGODB_CD_ARBITER, 'Arbiter'),\r\n)\r\n\r\nINSTANCIA_MYSQL = 1\r\nINSTANCIA_MONGODB = 2\r\nINSTANCIA_MONGODB_ARBITER = 3\r\n\r\n\r\nTIPO_INSTANCIA = (\r\n (INSTANCIA_MYSQL, u'MySQL'),\r\n (INSTANCIA_MONGODB, u'MongoDB'),\r\n (INSTANCIA_MONGODB_ARBITER, u'MongoDB Arbiter'),\r\n)\r\n\r\nclass DatabaseManager(models.Manager):\r\n def get_query_set(self):\r\n query_set = super(DatabaseManager, self).get_query_set()\r\n\r\n return query_set.extra(\r\n select = {\r\n 'senha': \"select decode(senha, '\" + settings.DECODE_KEY + \"')\",\r\n 'tipo2': \"select ELT(FIND_IN_SET(tipo, 'P,Q,B,A'),'Produção','QA','Backup','Administração')\"\r\n },\r\n order_by = ['nome']\r\n )\r\n\r\n\r\nclass Database(models.Model):\r\n\r\n nome = models.CharField(max_length=50)\r\n maquina = models.CharField(verbose_name=u'máquina', max_length=200, null=True, blank=True, help_text=u'deixar em branco caso seja um cluster database')\r\n sgbd = models.CharField(verbose_name='SGBD', max_length=1, choices=SGBD_CHOICES)\r\n topologia = models.IntegerField(verbose_name='Topologia', choices=TOPOLOGIA_CHOICES)\r\n tipo = models.CharField(max_length=1, choices=TIPO_DATABASE_CHOICES)\r\n dns = models.CharField(verbose_name='DNS', max_length=400, null=True, blank=True)\r\n porta = models.CharField(max_length=5, null=True, blank=True)\r\n versao = models.CharField(verbose_name=u'versão', max_length=50, null=True, blank=True)\r\n usuario = models.CharField(verbose_name=u'usuário', max_length=50, null=True, blank=True)\r\n senha = models.CharField(max_length=50, null=True, blank=True)\r\n ativo = models.BooleanField()\r\n flag_cluster = models.BooleanField(verbose_name=u'cluster',)\r\n coleta_info_sessoes = models.BooleanField(verbose_name=u'coleta dados de sessão',)\r\n testa_conexao = models.BooleanField(verbose_name=u'executa teste de conexão',)\r\n coleta_tamanho_database = models.BooleanField(verbose_name=u'coleta dados do tamanho do database',)\r\n testa_replicacao = models.BooleanField(verbose_name=u'Verifica se a replicação está funcionando',)\r\n objects = DatabaseManager()\r\n\r\n def __unicode__(self):\r\n return self.nome\r\n\r\n def save(self, *args, **kwargs):\r\n senha = self.senha\r\n self.senha = ''\r\n super(Database, self).save(*args, **kwargs)\r\n cursor = connection.cursor()\r\n cursor.execute(\"UPDATE dbmonitor_database set senha = encode('\" + senha + \"', '\" + settings.DECODE_KEY + \"') where id = \" + str(self.id))\r\n\r\n class Meta:\r\n ordering = ['nome']\r\n verbose_name = u'DatabaseInfra'\r\n verbose_name_plural = u'DatabaseInfras'\r\n\r\n\r\nclass Instancia(models.Model):\r\n database = models.ForeignKey(Database)\r\n nome = models.CharField(max_length=50)\r\n maquina = models.CharField(max_length=200, null=True, blank=True)\r\n dns = models.CharField(max_length=200, null=True, blank=True)\r\n porta = models.CharField(max_length=5, null=True, blank=True)\r\n ativo = models.BooleanField()\r\n tipo_instancia = models.IntegerField(verbose_name=u'Tipo de intância', choices=TIPO_INSTANCIA)\r\n tipo_mongodb = models.CharField(max_length=1, null=True, blank=True, choices=TIPO_INSTANCIA_MONGODB)\r\n\r\n class Meta:\r\n verbose_name = u'instância'\r\n\r\n def __unicode__(self):\r\n return self.nome\r\n\r\n","sub_path":"ProjetoFinalProgramacao/Projeto/monitor/dbmonitor/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"8905498","text":"\n# coding: utf-8\n\n# In[ ]:\n\n\n\nimport pygame\nfrom pygame.locals import *\nimport sys\n \nSCREEN_SIZE = (640, 480)\n \npygame.init()\nscreen = pygame.display.set_mode(SCREEN_SIZE)\npygame.display.set_caption(u\"キーイベント\")\npygame.key.set_repeat(500, 30)\n \nimg = pygame.image.load(\"python.png\").convert_alpha()\nimg_rect = img.get_rect()\nimg_rect.center = (320, 240)\n \nvx = vy = 10 # キーを押したときの移動距離\n \nwhile True:\n screen.fill((0,0,255))\n screen.blit(img, img_rect)\n pygame.display.update()\n \n for event in pygame.event.get():\n if event.type == QUIT: quit()\n if event.type == KEYDOWN: # キーを押したとき\n # ESCキーならスクリプトを終了\n if event.key == K_ESCAPE:\n quit()\n \n # 矢印キーなら画像を移動\n if event.key == K_LEFT:\n img_rect.move_ip(-vx, 0)\n print('left')\n if event.key == K_RIGHT:\n img_rect.move_ip(vx, 0)\n print('right')\n if event.key == K_UP:\n img_rect.move_ip(0, -vy)\n if event.key == K_DOWN:\n img_rect.move_ip(0, vy)\n\n\n# In[19]:\n\n\ndef funca(a, b):\n return a + b\n\n\n# In[20]:\n\n\ndef funcb(func, a, b, c):\n return func(a, b)+c\n\n\n# In[21]:\n\n\nfuncb(funca, 1, 2, 3)\n\n\n# In[23]:\n\n\na = [funca, funcb]\n\n\n# In[24]:\n\n\nfor func in a:\n func(2,3)\n\n\n# In[25]:\n\n\na = funca + funcb\n\n\n# In[27]:\n\n\nif funca is object:\n print(\"aaa\")\n\n\n# In[31]:\n\n\nisinstance(funca, object)\n\n\n# In[29]:\n\n\ntype(funca)\n\n\n# In[ ]:\n\n\ncals\n\n","sub_path":"pysynth/.ipynb_checkpoints/Untitled-checkpoint.py","file_name":"Untitled-checkpoint.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"575272465","text":"# coding=utf-8\n# Copyright 2022 The Google Research 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\"\"\"Run NarrativeQA fine-tuning for ReadItTwice BERT.\"\"\"\n\nimport collections\nimport functools\nimport json\nimport os\nimport re\nimport sys\nimport time\nfrom typing import List, Text\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\nimport dataclasses\nimport numpy as np\nimport tensorflow.compat.v1 as tf\n\nfrom readtwice.data_utils import tokenization\nfrom readtwice.models import checkpoint_utils\nfrom readtwice.models import config\nfrom readtwice.models import input_utils\nfrom readtwice.models import losses\nfrom readtwice.models import modeling\nfrom readtwice.models import optimization\nfrom readtwice.models.hotpot_qa import evaluation\nfrom readtwice.models.hotpot_qa import losses as hotpot_qa_losses\n\nFLAGS = flags.FLAGS\n\n## Model parameters\n\nflags.DEFINE_string(\n \"read_it_twice_bert_config_file\", None,\n \"The config json file corresponding to the pre-trained ETC ReadItTwiceBERT \"\n \"model. This specifies the model architecture.\")\n\nflags.DEFINE_string(\n \"read_it_twice_bert_config_base64\", None,\n \"The config json file corresponding to the pre-trained ETC ReadItTwiceBERT \"\n \"model. This specifies the model architecture.\")\n\nflags.DEFINE_bool(\n \"enable_side_inputs\", False,\n \"If True, enables read-it-twice model. Otherwise, the model becomes equivalent to the standard Transformer model.\"\n)\n\nflags.DEFINE_enum(\n \"cross_block_attention_mode\", \"doc\", [\"block\", \"doc\", \"batch\"],\n \"The policy on how summaries between different \"\n \"blocks are allowed to interact with each other.\")\n\n## Input parameters\n\nflags.DEFINE_string(\n \"input_file\", None,\n \"Input TF example files (can be a glob or comma separated).\")\nflags.DEFINE_string(\n \"input_json\", None,\n \"Input JSON example files (can be a glob or comma separated).\")\n\nflags.DEFINE_string(\n \"output_dir\", None,\n \"The output directory where the model checkpoints will be written.\")\n\nflags.DEFINE_string(\n \"checkpoint\", None, \"Checkpoint to evaluate. \"\n \"`do_train` must be false and `do_eval` must be true\")\n\nflags.DEFINE_string(\n \"init_checkpoint\", None, \"Initial checkpoint \"\n \"(usually from a pre-trained ETC ReadItTwiceBERT model).\")\n\nflags.DEFINE_integer(\n \"padding_token_id\", 0,\n \"The token id of the padding token according to the WordPiece vocabulary.\")\n\nflags.DEFINE_integer(\n \"num_replicas_concat\", 1,\n \"Number of replicas to gather summaries from. If None (default) then cross-replicas summaries are not used.\"\n)\n\n## Other parameters\n\nflags.DEFINE_bool(\"do_train\", False, \"Whether to run training.\")\n\nflags.DEFINE_bool(\"do_eval\", False, \"Whether to run eval on the dev set.\")\n\nflags.DEFINE_enum(\"optimizer\", \"adamw\", [\"adamw\", \"lamb\"],\n \"The optimizer for training.\")\n\nflags.DEFINE_float(\"learning_rate\", 1e-4, \"The initial learning rate for Adam.\")\n\nflags.DEFINE_enum(\n \"learning_rate_schedule\", \"poly_decay\", [\"poly_decay\", \"inverse_sqrt\"],\n \"The learning rate schedule to use. The default of \"\n \"`poly_decay` uses tf.train.polynomial_decay, while \"\n \"`inverse_sqrt` uses inverse sqrt of time after the warmup.\")\n\nflags.DEFINE_float(\"poly_power\", 1.0,\n \"The power of poly decay if using `poly_decay` schedule.\")\n\nflags.DEFINE_float(\"num_train_epochs\", 3.0, \"Number of training epochs.\")\n\nflags.DEFINE_float(\n \"warmup_proportion\", 0.1,\n \"Proportion of training to perform linear learning rate warmup for. \"\n \"E.g., 0.1 = 10% of training.\")\n\nflags.DEFINE_integer(\"start_warmup_step\", 0, \"The starting step of warmup.\")\n\nflags.DEFINE_string(\n \"spm_model_path\",\n \"/namespace/webanswers/generative_answers/checkpoints/vocab_gpt.model\",\n \"Path to sentence piece model.\")\n\nflags.DEFINE_integer(\"decode_top_k\", 40,\n \"Maximum number of logits to consider for begin/end.\")\n\nflags.DEFINE_integer(\"decode_max_size\", 10,\n \"Maximum number of sentence pieces in an answer.\")\n\nflags.DEFINE_integer(\"save_checkpoints_steps\", 5000,\n \"How often to save the model checkpoint.\")\n\nflags.DEFINE_integer(\"steps_per_summary\", 1000, \"How often to write summaries.\")\n\nflags.DEFINE_integer(\"iterations_per_loop\", 1000,\n \"How many steps to make in each estimator call.\")\n\nflags.DEFINE_integer(\"cross_attention_top_k\", None,\n \"How many steps to make in each estimator call.\")\n\nflags.DEFINE_bool(\"use_tpu\", False, \"Whether to use TPU or GPU/CPU.\")\n\nflags.DEFINE_bool(\n \"use_one_hot_embeddings\", False,\n \"Whether to use one-hot multiplication instead of gather for embedding \"\n \"lookups.\")\n\nflags.DEFINE_string(\n \"tpu_name\", None,\n \"The Cloud TPU to use for training. This should be either the name \"\n \"used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 \"\n \"url.\")\n\nflags.DEFINE_string(\n \"tpu_zone\", None,\n \"[Optional] GCE zone where the Cloud TPU is located in. If not \"\n \"specified, we will attempt to automatically detect the GCE project from \"\n \"metadata.\")\n\nflags.DEFINE_string(\n \"gcp_project\", None,\n \"[Optional] Project name for the Cloud TPU-enabled project. If not \"\n \"specified, we will attempt to automatically detect the GCE project from \"\n \"metadata.\")\n\nflags.DEFINE_string(\"master\", None, \"[Optional] TensorFlow master URL.\")\n\nflags.DEFINE_string(\n \"tpu_job_name\", None,\n \"Name of TPU worker binary. Only necessary if job name is changed from\"\n \" default tpu_worker.\")\n\nflags.DEFINE_integer(\"num_tpu_cores\", None, \"Number of tpu cores for the job.\")\n\nflags.DEFINE_integer(\"num_tpu_tasks\", None, \"Number of tpu tasks in total.\")\n\n\n\ndef _get_global_step_for_checkpoint(checkpoint_path):\n \"\"\"Returns the global step for the checkpoint path, or -1 if not found.\"\"\"\n re_match = re.search(r\"ckpt-(\\d+)$\", checkpoint_path)\n return -1 if re_match is None else int(re_match.group(1))\n\n\ndef _get_all_checkpoints(model_dir):\n checkpoint_pattern = re.compile(\"(model.ckpt-([0-9]+)).meta\")\n checkpoints = []\n for path in tf.io.gfile.listdir(model_dir):\n checkpoint_match = re.match(checkpoint_pattern, path)\n if not checkpoint_match:\n continue\n checkpoint_path = os.path.join(model_dir, checkpoint_match.group(1))\n if (not tf.io.gfile.exists(checkpoint_path + \".meta\") or\n not tf.io.gfile.exists(checkpoint_path + \".index\")):\n raise ValueError(\"Invalid checkpoint path: {}\".format(checkpoint_path))\n checkpoints.append((int(checkpoint_match.group(2)), checkpoint_path))\n checkpoints.sort()\n return [os.path.normpath(x[1]) for x in checkpoints]\n\n\ndef make_scalar_summary(tag, value):\n \"\"\"Returns a TF Summary proto for a scalar summary value.\n\n Args:\n tag: The name of the summary.\n value: The scalar float value of the summary.\n\n Returns:\n A TF Summary proto.\n \"\"\"\n return tf.summary.Summary(\n value=[tf.summary.Summary.Value(tag=tag, simple_value=value)])\n\n\ndef write_eval_results(global_step, eval_results, eval_name, summary_writer):\n logging.info(\"***** EVAL on step %d (%s) *****\", global_step,\n eval_name.upper())\n for metric, value in eval_results.items():\n value_float = float(value)\n logging.info(\" %s = %.3f\", metric, value_float)\n summary_writer.add_summary(\n make_scalar_summary(\n tag=\"eval_metrics_%s/%s\" % (eval_name, metric), value=value_float),\n global_step=global_step)\n summary_writer.flush()\n\n\ndef _convert_prediction_logits_to_probs(nbest_predictions):\n \"\"\"Compute probabilities for answers.\"\"\"\n nbest_predictions_probs = collections.OrderedDict()\n for question, predictions in nbest_predictions.items():\n # pylint: disable=g-complex-comprehension\n all_logits = np.array(\n [logit for answer, logits in predictions.items() for logit in logits])\n if len(all_logits) == 0: # pylint: disable=g-explicit-length-test\n # There are no valid predictions for this question\n continue\n max_logit = all_logits.max()\n norm_const = np.exp(all_logits - max_logit).sum()\n nbest_predictions_probs[question] = {\n answer:\n [float(np.exp(logit - max_logit) / norm_const) for logit in logits]\n for answer, logits in predictions.items()\n }\n return nbest_predictions_probs\n\n\ndef _get_best_predictions(nbest_predictions, reduction_fn):\n best_predictions = collections.OrderedDict()\n for question, predictions in nbest_predictions.items():\n scores_predictions = [(reduction_fn(scores), answer)\n for answer, scores in predictions.items()]\n scores_predictions.sort()\n best_predictions[question] = scores_predictions[-1][1]\n return best_predictions\n\n\ndef _convert_dict_to_list(d):\n list_of_pairs = list(d.items())\n list_of_pairs.sort(key=lambda x: x[0])\n result = []\n for i in range(len(list_of_pairs)):\n result.append(list_of_pairs[i][1])\n return result\n\n\ndef record_summary_host_fn(metrics_dir, **kwargs):\n \"\"\"A host_fn function for the host_call in TPUEstimatorSpec.\n\n Args:\n metrics_dir: Directory where tf summary events should be written. recorded.\n **kwargs: Contains tensors for which summaries are to be recorded. It must\n contain a key of `global_step`.\n\n Returns:\n A summary op for each tensor to be recorded.\n \"\"\"\n # It's not documented, but when recording summaries via TPUEstimator,\n # you need to pass in the global_step value to your host_call function.\n\n # Describe the difference between sum and max. All tensors are supposed to\n # be of shape [num_cores]\n global_step = kwargs.pop(\"global_step\")[0]\n with tf.compat.v2.summary.create_file_writer(metrics_dir).as_default():\n with tf.compat.v2.summary.record_if(True):\n for name, tensor in kwargs.items():\n tf.compat.v2.summary.scalar(\n name, tf.reduce_mean(tensor), step=global_step)\n tf.compat.v2.summary.scalar(\n name + \"_sum\", tf.reduce_sum(tensor), step=global_step)\n return tf.summary.all_v2_summary_ops()\n\n\ndef supporting_fact_model(sent_rep):\n logits = tf.layers.dense(\n sent_rep,\n 1,\n activation=None,\n kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),\n name=\"supporting_fact_model\")\n logits = tf.squeeze(logits, -1)\n return logits\n\n\ndef yesno_model(sent_rep):\n logits = tf.layers.dense(\n sent_rep,\n 3,\n activation=None,\n kernel_initializer=tf.truncated_normal_initializer(stddev=0.02),\n name=\"yesno_model\")\n return logits\n\n\ndef compute_pooled_loss(logits, labels, num_labels, example_mask):\n log_probs = tf.nn.log_softmax(logits, axis=-1)\n one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)\n per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)\n loss = tf.reduce_sum(per_example_loss * example_mask) / (\n tf.reduce_sum(example_mask) + 1e-5)\n return loss\n\n\ndef compute_supporting_facts_loss(logits, labels, example_mask):\n labels = tf.cast(labels, dtype=tf.float32)\n per_example_loss = tf.nn.sigmoid_cross_entropy_with_logits(\n labels=labels, logits=logits)\n loss = tf.reduce_sum(per_example_loss * example_mask) / (\n tf.reduce_sum(example_mask) + 1e-5)\n return loss\n\n\ndef model_fn_builder(model_config,\n padding_token_id, enable_side_inputs,\n num_replicas_concat, cross_block_attention_mode,\n init_checkpoint, learning_rate,\n num_train_steps, num_warmup_steps, use_tpu,\n use_one_hot_embeddings, optimizer,\n poly_power, start_warmup_step,\n learning_rate_schedule, nbest_logits_for_eval):\n \"\"\"Returns `model_fn` closure for TPUEstimator.\"\"\"\n\n def model_fn(features, labels, mode, params): # pylint: disable=unused-argument\n \"\"\"The `model_fn` for TPUEstimator.\"\"\"\n\n logging.info(\"*** Model: Params ***\")\n for name in sorted(params.keys()):\n logging.info(\" %s = %s\", name, params[name])\n logging.info(\"*** Model: Features ***\")\n for name in sorted(features.keys()):\n logging.info(\" name = %s, shape = %s\", name, features[name].shape)\n\n model = modeling.ReadItTwiceBertModel(\n config=model_config, use_one_hot_embeddings=use_one_hot_embeddings)\n\n span_prediction_layer = modeling.SpanPredictionHead(\n intermediate_size=model_config.intermediate_size,\n dropout_rate=model_config.hidden_dropout_prob)\n\n # [batch_size, main_seq_length]\n token_ids = features[\"token_ids\"]\n main_seq_length = tf.shape(token_ids)[1]\n block_ids = features[\"block_ids\"]\n block_pos = features[\"block_pos\"]\n answer_type = features[\"answer_type\"]\n supporting_fact = features[\"is_supporting_fact\"]\n\n annotation_begins = features.get(\"entity_annotation_begins\")\n annotation_ends = features.get(\"entity_annotation_ends\")\n annotation_labels = features.get(\"entity_annotation_labels\")\n\n # Do not attend padding tokens\n # [batch_size, main_seq_length, main_seq_length]\n att_mask = tf.tile(\n tf.expand_dims(tf.not_equal(token_ids, padding_token_id), 1),\n [1, main_seq_length, 1])\n att_mask = tf.cast(att_mask, dtype=tf.int32)\n\n main_output = model(\n token_ids=token_ids,\n training=(mode == tf_estimator.ModeKeys.TRAIN),\n block_ids=block_ids,\n block_pos=block_pos,\n att_mask=att_mask,\n annotation_begins=annotation_begins,\n annotation_ends=annotation_ends,\n annotation_labels=annotation_labels,\n enable_side_inputs=enable_side_inputs,\n num_replicas_concat=num_replicas_concat,\n cross_block_attention_mode=cross_block_attention_mode)\n\n span_logits = span_prediction_layer(\n hidden_states=main_output.final_hidden_states,\n token_ids=token_ids,\n padding_token_id=padding_token_id,\n ignore_prefix_length=features[\"prefix_length\"],\n training=(mode == tf_estimator.ModeKeys.TRAIN))\n\n # The \"pooler\" converts the encoded sequence tensor of shape\n # [batch_size, seq_length, hidden_size] to a tensor of shape\n # [batch_size, hidden_size]. This is necessary for segment-level\n # (or segment-pair-level) classification tasks where we need a fixed\n # dimensional representation of the segment.\n with tf.variable_scope(\"pooler\"):\n # We \"pool\" the model by simply taking the hidden state corresponding\n # to the first token. We assume that this has been pre-trained\n first_token_tensor = tf.squeeze(\n main_output.final_hidden_states[:, 0:1, :], axis=1)\n pooled_output = tf.layers.dense(\n first_token_tensor,\n model_config.hidden_size,\n activation=tf.tanh,\n kernel_initializer=tf.truncated_normal_initializer(\n stddev=model_config.initializer_range))\n\n yesno_logits = yesno_model(pooled_output)\n supporting_fact_logits = supporting_fact_model(pooled_output)\n\n tvars = tf.trainable_variables()\n\n initialized_variable_names = {}\n scaffold_fn = None\n if init_checkpoint:\n (assignment_map, initialized_variable_names\n ) = checkpoint_utils.get_assignment_map_from_checkpoint(\n tvars, init_checkpoint)\n if use_tpu:\n\n def tpu_scaffold():\n tf.train.init_from_checkpoint(init_checkpoint, assignment_map)\n return tf.train.Scaffold()\n\n scaffold_fn = tpu_scaffold\n else:\n tf.train.init_from_checkpoint(init_checkpoint, assignment_map)\n\n logging.info(\"**** Trainable Variables ****\")\n for var in tvars:\n init_string = \"\"\n if var.name in initialized_variable_names:\n init_string = \", *INIT_FROM_CKPT*\"\n logging.info(\" name = %s, shape = %s%s\", var.name, var.shape,\n init_string)\n\n output_spec = None\n if mode == tf_estimator.ModeKeys.TRAIN:\n host_inputs = dict()\n\n span_prediction_loss = losses.BatchSpanCrossEntropyLoss()\n\n total_loss = 0\n qa_loss = span_prediction_loss(\n logits=span_logits,\n annotation_begins=features[\"answer_annotation_begins\"],\n annotation_ends=features[\"answer_annotation_ends\"],\n annotation_labels=features[\"answer_annotation_labels\"],\n block_ids=block_ids,\n num_replicas=num_replicas_concat,\n eps=1e-5)\n host_inputs[\"train_metrics/qa_loss\"] = tf.expand_dims(qa_loss, 0)\n total_loss += qa_loss\n\n # example_mask = tf.cast(tf.not_equal(block_ids, 0), tf.float32)\n # yesno_loss = compute_pooled_loss(yesno_logits, answer_type, 3,\n # example_mask)\n # supporting_fact_loss = compute_supporting_facts_loss(\n # supporting_fact_logits, supporting_fact, example_mask)\n hotpot_qa_loss = hotpot_qa_losses.BatchSpanCrossEntropyLoss()\n yesno_loss, supporting_fact_loss = hotpot_qa_loss(\n yesno_logits,\n answer_type,\n supporting_fact_logits,\n supporting_fact,\n block_ids,\n eps=1e-5)\n\n host_inputs[\"train_metrics/yesno_loss\"] = tf.expand_dims(yesno_loss, 0)\n total_loss += yesno_loss\n\n host_inputs[\"train_metrics/supporting_fact_loss\"] = tf.expand_dims(\n supporting_fact_loss, 0)\n total_loss += supporting_fact_loss\n\n # Add regularization losses.\n if model.losses:\n total_loss += tf.math.add_n(model.losses)\n\n train_op = optimization.create_optimizer(\n total_loss,\n learning_rate,\n num_train_steps,\n num_warmup_steps,\n use_tpu,\n optimizer,\n poly_power,\n start_warmup_step,\n learning_rate_schedule,\n reduce_loss_sum=True)\n\n host_inputs.update({\n \"global_step\":\n tf.expand_dims(tf.train.get_or_create_global_step(), 0),\n \"train_metrics/loss\":\n tf.expand_dims(total_loss, 0),\n })\n\n host_call = (functools.partial(\n record_summary_host_fn,\n metrics_dir=os.path.join(FLAGS.output_dir,\n \"train_metrics\")), host_inputs)\n\n output_spec = tf_estimator.tpu.TPUEstimatorSpec(\n mode=mode,\n loss=total_loss,\n train_op=train_op,\n scaffold_fn=scaffold_fn,\n host_call=host_call)\n elif mode == tf_estimator.ModeKeys.PREDICT:\n begin_logits_values, begin_logits_indices = tf.math.top_k(\n span_logits[:, :, 0],\n k=nbest_logits_for_eval,\n )\n end_logits_values, end_logits_indices = tf.math.top_k(\n span_logits[:, :, 1],\n k=nbest_logits_for_eval,\n )\n\n predictions = {\n \"block_ids\": tf.identity(block_ids),\n \"begin_logits_values\": begin_logits_values,\n \"begin_logits_indices\": begin_logits_indices,\n \"end_logits_values\": end_logits_values,\n \"end_logits_indices\": end_logits_indices,\n \"token_ids\": tf.identity(token_ids),\n \"answer_type\": answer_type,\n \"yesno_logits\": yesno_logits,\n \"supporting_fact_logits\": supporting_fact_logits,\n \"is_supporting_fact\": supporting_fact,\n }\n output_spec = tf_estimator.tpu.TPUEstimatorSpec(\n mode=mode, predictions=predictions, scaffold_fn=scaffold_fn)\n else:\n raise ValueError(\"Only TRAIN and PREDICT modes is supported: %s\" % mode)\n\n return output_spec\n\n return model_fn\n\n\ndef input_fn_builder(input_files,\n is_training,\n num_cpu_threads = 4):\n \"\"\"Creates an `input_fn` closure to be passed to TPUEstimator.\"\"\"\n num_blocks_per_example, block_length = input_utils.get_block_params_from_input_file(\n input_files[0])\n max_num_annotations = input_utils.get_num_annotations_from_input_file(\n input_files[0])\n logging.info(\"***** Building Input pipeline *****\")\n logging.info(\" Number of blocks per example = %d\", num_blocks_per_example)\n logging.info(\" Block length = %d\", block_length)\n logging.info(\" Number of anntotations per block = %d\", max_num_annotations)\n\n def input_fn(params):\n \"\"\"The actual input function.\"\"\"\n logging.info(\"*** Input: Params ***\")\n for name in sorted(params.keys()):\n logging.info(\" %s = %s\", name, params[name])\n\n # For training, we want a lot of parallel reading and shuffling.\n # For eval, we want no shuffling and parallel reading doesn't matter.\n if is_training:\n d = tf.data.Dataset.from_tensor_slices(tf.constant(input_files))\n\n # From https://www.tensorflow.org/guide/data#randomly_shuffling_input_data\n # Dataset.shuffle doesn't signal the end of an epoch until the shuffle\n # buffer is empty. So a shuffle placed before a repeat will show every\n # element of one epoch before moving to the next.\n d = d.shuffle(buffer_size=len(input_files))\n d = d.repeat()\n\n # `cycle_length` is the number of parallel files that get read.\n cycle_length = min(num_cpu_threads, len(input_files))\n\n # `sloppy` mode means that the interleaving is not exact. This adds\n # even more randomness to the training pipeline.\n d = d.apply(\n tf.data.experimental.parallel_interleave(\n tf.data.TFRecordDataset,\n sloppy=is_training,\n cycle_length=cycle_length))\n d = d.shuffle(buffer_size=1000)\n else:\n d = tf.data.TFRecordDataset(input_files)\n\n extra_int_features_shapes = {\n \"answer_type\": [num_blocks_per_example],\n \"is_supporting_fact\": [num_blocks_per_example],\n }\n d = d.map(\n input_utils.get_span_prediction_example_decode_fn(\n num_blocks_per_example,\n block_length,\n max_num_answer_annotations=max_num_annotations,\n max_num_entity_annotations=max_num_annotations,\n extra_int_features_shapes=extra_int_features_shapes,\n ),\n num_parallel_calls=tf.data.experimental.AUTOTUNE)\n\n d = d.prefetch(tf.data.experimental.AUTOTUNE)\n return d\n\n return input_fn\n\n\ndef validate_flags():\n \"\"\"Basic flag validation.\"\"\"\n if not FLAGS.do_train and not FLAGS.do_eval:\n raise ValueError(\"At least one of `do_train` or `do_eval` must be True.\")\n\n\ndef read_question_answer_json(json_path):\n \"\"\"Read a CVS file into a list of QuestionAnswer objects.\"\"\"\n # We skip the first question ID as it corresponds on a padding document.\n question_ids = [None]\n ground_truth = {}\n with tf.io.gfile.GFile(json_path) as f:\n data = json.load(f)\n for datum in data:\n question_id = datum[\"_id\"]\n ground_truth[question_id] = evaluation.normalize_answer(datum[\"answer\"])\n question_ids.append(question_id)\n logging.info(\"Read %d questions from %s\", len(ground_truth), json_path)\n return question_ids, ground_truth\n\n\ndef main(_):\n logging.set_verbosity(logging.INFO)\n\n validate_flags()\n tf.io.gfile.makedirs(FLAGS.output_dir)\n\n for flag in FLAGS.flags_by_module_dict()[sys.argv[0]]:\n logging.info(\" %s = %s\", flag.name, flag.value)\n\n model_config = config.get_model_config(\n model_dir=FLAGS.output_dir,\n source_file=FLAGS.read_it_twice_bert_config_file,\n source_base64=FLAGS.read_it_twice_bert_config_base64,\n write_from_source=FLAGS.do_train)\n\n\n if FLAGS.checkpoint is not None:\n assert not FLAGS.do_train\n assert FLAGS.do_eval\n\n if FLAGS.cross_attention_top_k is not None:\n model_config = dataclasses.replace(\n model_config, cross_attention_top_k=FLAGS.cross_attention_top_k)\n\n input_files = []\n for input_pattern in FLAGS.input_file.split(\",\"):\n input_files.extend(tf.io.gfile.glob(input_pattern))\n\n logging.info(\"*** Input Files ***\")\n for input_file in input_files:\n logging.info(\" %s\", input_file)\n\n num_blocks_per_example, block_length = input_utils.get_block_params_from_input_file(\n input_files[0])\n\n tpu_cluster_resolver = None\n if FLAGS.use_tpu and FLAGS.tpu_name:\n tpu_cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver(\n FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)\n\n # Basically, quoting the answer above\n # PER_HOST_V1: iterator.get_next() is called 1 time with per_worker_batch_size\n # PER_HOST_V2: iterator.get_next() is called 8 times with per_core_batch_size\n # pylint: enable=line-too-long\n is_per_host = tf_estimator.tpu.InputPipelineConfig.PER_HOST_V1\n run_config = tf_estimator.tpu.RunConfig(\n cluster=tpu_cluster_resolver,\n master=FLAGS.master,\n model_dir=FLAGS.output_dir,\n save_checkpoints_steps=FLAGS.save_checkpoints_steps,\n # Keep all checkpoints\n keep_checkpoint_max=None,\n tpu_config=tf_estimator.tpu.TPUConfig(\n iterations_per_loop=FLAGS.iterations_per_loop,\n tpu_job_name=FLAGS.tpu_job_name,\n per_host_input_for_training=is_per_host,\n experimental_host_call_every_n_steps=FLAGS.steps_per_summary))\n\n # TODO(urikz): Is there a better way to compute the number of tasks?\n # the code below doesn't work because `tpu_cluster_resolver.cluster_spec()`\n # returns None. Therefore, I have to pass number of total tasks via CLI arg.\n # num_tpu_tasks = tpu_cluster_resolver.cluster_spec().num_tasks()\n batch_size = (FLAGS.num_tpu_tasks or 1) * num_blocks_per_example\n\n num_train_examples = input_utils.get_num_examples_in_tf_records(input_files)\n num_train_steps = int(num_train_examples * FLAGS.num_train_epochs)\n num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)\n\n logging.info(\"***** Input configuration *****\")\n logging.info(\" Number of blocks per example = %d\", num_blocks_per_example)\n logging.info(\" Block length = %d\", block_length)\n logging.info(\" Number of TPU tasks = %d\", FLAGS.num_tpu_tasks or 1)\n logging.info(\" Batch size = %d\", batch_size)\n logging.info(\" Number of TPU cores = %d\", FLAGS.num_tpu_cores or 0)\n logging.info(\" Number training steps = %d\", num_train_steps)\n logging.info(\" Number warmup steps = %d\", num_warmup_steps)\n\n model_fn = model_fn_builder(\n model_config=model_config,\n padding_token_id=FLAGS.padding_token_id,\n enable_side_inputs=FLAGS.enable_side_inputs,\n num_replicas_concat=FLAGS.num_tpu_cores,\n cross_block_attention_mode=FLAGS.cross_block_attention_mode,\n init_checkpoint=FLAGS.init_checkpoint,\n learning_rate=FLAGS.learning_rate,\n num_train_steps=num_train_steps,\n num_warmup_steps=num_warmup_steps,\n use_tpu=FLAGS.use_tpu,\n use_one_hot_embeddings=FLAGS.use_one_hot_embeddings,\n optimizer=FLAGS.optimizer,\n poly_power=FLAGS.poly_power,\n start_warmup_step=FLAGS.start_warmup_step,\n learning_rate_schedule=FLAGS.learning_rate_schedule,\n nbest_logits_for_eval=FLAGS.decode_top_k)\n\n # If TPU is not available, this will fall back to normal Estimator on CPU\n # or GPU.\n estimator = tf_estimator.tpu.TPUEstimator(\n use_tpu=FLAGS.use_tpu,\n model_fn=model_fn,\n config=run_config,\n train_batch_size=batch_size,\n eval_batch_size=batch_size,\n predict_batch_size=batch_size)\n\n training_done_path = os.path.join(FLAGS.output_dir, \"training_done\")\n\n if FLAGS.do_train:\n logging.info(\"***** Running training *****\")\n train_input_fn = input_fn_builder(input_files=input_files, is_training=True)\n estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)\n # Write file to signal training is done.\n with tf.gfile.GFile(training_done_path, \"w\") as writer:\n writer.write(\"\\n\")\n\n if FLAGS.do_eval:\n logging.info(\"***** Running evaluation *****\")\n eval_input_fn = input_fn_builder(input_files=input_files, is_training=False)\n question_ids, ground_truth = read_question_answer_json(FLAGS.input_json)\n tokenizer = tokenization.FullTokenizer(FLAGS.spm_model_path)\n logging.info(\"Loaded SentencePiece model from %s\", FLAGS.spm_model_path)\n\n # Writer for TensorBoard.\n summary_writer = tf.summary.FileWriter(\n os.path.join(FLAGS.output_dir, \"eval_metrics\"))\n\n if not FLAGS.checkpoint:\n # for checkpoint_path in _get_all_checkpoints(FLAGS.output_dir):\n checkpoint_iter = tf.train.checkpoints_iterator(\n FLAGS.output_dir, min_interval_secs=5 * 60, timeout=8 * 60 * 60)\n else:\n checkpoint_iter = [FLAGS.checkpoint]\n\n for checkpoint_path in checkpoint_iter:\n start_time = time.time()\n global_step = _get_global_step_for_checkpoint(checkpoint_path)\n if global_step == 0:\n continue\n logging.info(\"Starting eval on step %d on checkpoint: %s\", global_step,\n checkpoint_path)\n try:\n nbest_predictions = collections.OrderedDict()\n yesno_logits, yesno_labels = {}, {}\n supporting_fact_logits, supporting_fact_labels = {}, {}\n\n for prediction in estimator.predict(\n eval_input_fn,\n checkpoint_path=checkpoint_path,\n yield_single_examples=True):\n block_id = prediction[\"block_ids\"]\n if block_id == 0:\n # Padding document\n continue\n question_id = question_ids[block_id]\n if question_id not in nbest_predictions:\n nbest_predictions[question_id] = {}\n yesno_logits[question_id] = []\n yesno_labels[question_id] = []\n supporting_fact_logits[question_id] = []\n supporting_fact_labels[question_id] = []\n\n yesno_logits[question_id].append(prediction[\"yesno_logits\"].tolist())\n yesno_labels[question_id].append(prediction[\"answer_type\"].tolist())\n supporting_fact_logits[question_id].append(\n prediction[\"supporting_fact_logits\"].tolist())\n supporting_fact_labels[question_id].append(\n prediction[\"is_supporting_fact\"].tolist())\n\n token_ids = prediction[\"token_ids\"]\n for begin_index, begin_logit in zip(\n prediction[\"begin_logits_indices\"],\n prediction[\"begin_logits_values\"]):\n for end_index, end_logit in zip(prediction[\"end_logits_indices\"],\n prediction[\"end_logits_values\"]):\n if begin_index > end_index or end_index - begin_index + 1 > FLAGS.decode_max_size:\n continue\n answer = \"\".join(\n tokenizer.convert_ids_to_tokens([\n int(token_id)\n for token_id in token_ids[begin_index:end_index + 1]\n ]))\n\n answer = answer.replace(tokenization.SPIECE_UNDERLINE,\n \" \").strip()\n if not answer:\n continue\n normalized_answer = evaluation.normalize_answer(answer)\n if normalized_answer not in nbest_predictions[question_id]:\n nbest_predictions[question_id][normalized_answer] = []\n nbest_predictions[question_id][normalized_answer].append(\n begin_logit + end_logit)\n except tf.errors.NotFoundError:\n # Since the coordinator is on a different job than the TPU worker,\n # sometimes the TPU worker does not finish initializing until long after\n # the CPU job tells it to start evaluating. In this case, the checkpoint\n # file could have been deleted already.\n tf.logging.info(\"Checkpoint %s no longer exists, skipping checkpoint\",\n checkpoint_path)\n continue\n\n nbest_predictions_probs = _convert_prediction_logits_to_probs(\n nbest_predictions)\n\n best_predictions_max = _get_best_predictions(nbest_predictions_probs, max)\n for question_id in yesno_logits:\n if question_id in best_predictions_max:\n span_answer = best_predictions_max[question_id]\n else:\n span_answer = None\n best_predictions_max[question_id] = {\n \"yesno_logits\": yesno_logits[question_id],\n \"yesno_labels\": yesno_labels[question_id],\n \"supporting_fact_logits\": supporting_fact_logits[question_id],\n \"supporting_fact_labels\": supporting_fact_labels[question_id],\n }\n if span_answer is not None:\n best_predictions_max[question_id][\"span_answer\"] = span_answer\n\n with tf.gfile.GFile(checkpoint_path + \".best_predictions_max.json\",\n \"w\") as f:\n json.dump(best_predictions_max, f, indent=2)\n\n best_predictions_max_results = evaluation.make_predictions_and_eval(\n ground_truth, best_predictions_max)\n write_eval_results(global_step, best_predictions_max_results, \"max\",\n summary_writer)\n\n if tf.io.gfile.exists(training_done_path):\n # Break if the checkpoint we just processed is the last one.\n last_checkpoint = tf.train.latest_checkpoint(FLAGS.output_dir)\n if last_checkpoint is None:\n continue\n last_global_step = _get_global_step_for_checkpoint(last_checkpoint)\n if global_step == last_global_step:\n break\n\n global_step = _get_global_step_for_checkpoint(checkpoint_path)\n logging.info(\"Finished eval on step %d in %d seconds\", global_step,\n time.time() - start_time)\n\n\nif __name__ == \"__main__\":\n logging.set_verbosity(logging.INFO)\n flags.mark_flags_as_required([\"input_file\", \"output_dir\"])\n app.run(main)\n","sub_path":"readtwice/models/hotpot_qa/run_finetuning.py","file_name":"run_finetuning.py","file_ext":"py","file_size_in_byte":33778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"522841233","text":"from conans import ConanFile, CMake, tools\nfrom conans.errors import ConanInvalidConfiguration\nimport os\n\nclass KcovConan(ConanFile):\n name = \"kcov\"\n version = \"0.0.0\"\n license = \"GPL-2.0\"\n author = \"davidtazy\"\n url = \"https://github.com/davidtazy/conan-kcov\"\n description = \"Code coverage tool for compiled programs, Python and Bash which uses debugging information to collect and report data without special compilation options\"\n topics = (\"coverage\", \"linux\", \"debug\")\n settings = \"os\", \"compiler\", \"build_type\", \"arch\" \n #options = {\"shared\": [True, False]}\n #default_options = {\"shared\": False}\n requires = [\"zlib/1.2.11\",\n \"libiberty/9.1.0\",\n \"libcurl/7.64.1\"]\n generators = \"cmake\"\n\n def configure(self):\n if self.settings.compiler == \"Visual Studio\":\n raise ConanInvalidConfiguration(\"kcov can not be built by Visual Studio.\")\n\n def source(self):\n self.run(\"git clone https://github.com/SimonKagstrom/kcov.git\")\n #inject conan deps\n tools.replace_in_file(\"kcov/CMakeLists.txt\", \"project (kcov)\",\n '''project (kcov)\ninclude(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)\nconan_basic_setup()''')\n\n def system_requirements(self):\n required_package = []\n if self.settings.os == \"Linux\": \n \n if tools.os_info.linux_distro in [\"ubuntu\", \"debian\"]:\n required_package.append( \"libdw-dev\" )\n elif tools.os_info.linux_distro in [\"fedora\", \"centos\"]:\n required_package.append( \"elfutils-libs\")\n elif tools.os_info.linux_distro == \"opensuse\":\n required_package.append( \"libdw-devel\")\n elif tools.os_info.linux_distro == \"arch\":\n required_package.append( \"libelf\" )\n\n \n if tools.os_info.linux_distro in [\"ubuntu\", \"debian\"]:\n required_package.append( \"binutils-dev\")\n elif tools.os_info.linux_distro in [\"fedora\", \"centos\", \"opensuse\"]:\n required_package.append( \"binutils-devel\")\n elif tools.os_info.linux_distro == \"arch\":\n required_package.append( \"binutils\")\n elif tools.os_info.is_freebsd:\n required_package.append( \"libbfd\")\n \n \n installer = tools.SystemPackageTool()\n installer.install(required_package)\n \n\n\n def build(self):\n cmake = CMake(self)\n cmake.configure(source_folder=\"kcov\")\n cmake.build()\n\n def package(self):\n cmake = CMake(self)\n cmake.configure(source_folder=\"kcov\")\n cmake.install()\n\n def package_info(self):\n bindir = os.path.join(self.package_folder, \"bin\")\n self.output.info(\"Appending PATH environment variable: {}\".format(bindir))\n self.env_info.PATH.append(bindir)\n\n","sub_path":"conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":2890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"278265621","text":"from bisect import bisect_left\nfrom collections import deque\n\nclass Puz:\n def __init__(self, filename):\n self.load(filename)\n\n def load(self, fn):\n self.grid = open(fn).read().splitlines()\n self.width = len(self.grid[0])\n self.height = len(self.grid)\n\n\n def neighbours_adj(self, x, y):\n for _y in (y - 1, y + 1):\n if 0 <= _y < self.height:\n yield (x, _y)\n for _x in (x - 1, x + 1):\n if 0 <= _x < self.width:\n yield (_x, y)\n\n def iter_grid(self):\n new_grid = []\n for y, row in enumerate(self.grid):\n new_row = []\n for x, tile in enumerate(row):\n bugs = 0\n for (_x, _y) in self.neighbours_adj(x, y):\n bugs += self.grid[_y][_x] == '#'\n if tile == '#':\n if bugs != 1:\n new_row.append('.')\n else:\n new_row.append('#')\n else:\n if 1 <= bugs <= 2:\n new_row.append('#')\n else:\n new_row.append('.')\n new_grid.append(''.join(new_row))\n self.grid = new_grid\n\n def __str__(self):\n return '\\n'.join(self.grid)\n \n def to_tuple(self):\n the_list = []\n for row in self.grid:\n the_list.extend(row)\n return tuple(the_list)\n\n\ndef solve_1(filename):\n puz = Puz(filename)\n patterns = deque()\n while 1:\n tup = puz.to_tuple()\n num_patterns = len(patterns)\n index = bisect_left(patterns, tup)\n if index >= num_patterns:\n patterns.append(tup)\n else:\n if patterns[index] != tup:\n patterns.insert(index, tup)\n else:\n break\n\n res = puz.iter_grid()\n tot = 0\n for x in range(puz.width):\n for y in range(puz.height):\n index = x + y*puz.width\n if puz.grid[y][x] == '#':\n tot += 2**index\n return tot\n\n\nclass PuzRecursive:\n # Set of neighbours for each tile. have keys (x, y) coordinates, and each\n # value is a tuple of the neighbours we consider. Each neighbour is\n # represented by a tuple of the form (d, (u, v)) where d represents a grid\n # offset and (u, v) a coordinate on the corresponding grid. For example,\n # d=0 indicates the same grid, d=-1, the outer grid, and d=1, the inner\n # grid.\n neighbours = {\n # Corners:\n (0, 0): ((-1, (2, 1)),\n (-1, (1, 2)),\n (0, (1, 0)),\n (0, (0, 1))),\n (4, 0): ((-1, (2, 1)),\n (-1, (3, 2)),\n (0, (3, 0)),\n (0, (4, 1))),\n (0, 4): ((-1, (1, 2)),\n (-1, (2, 3)),\n (0, (0, 3)),\n (0, (1, 4))),\n (4, 4): ((-1, (3, 2)),\n (-1, (2, 3)),\n (0, (4, 3)),\n (0, (3, 4))),\n # Edges\n (1, 0): ((-1, (2, 1)),\n (0, (0, 0,)),\n (0, (2, 0)),\n (0, (1, 1))),\n (2, 0): ((-1, (2, 1)),\n (0, (1, 0)),\n (0, (3, 0)),\n (0, (2, 1))),\n (3, 0): ((-1, (2, 1)),\n (0, (2, 0)),\n (0, (4, 0)),\n (0, (3, 1))),\n (0, 1): ((-1, (1, 2)),\n (0, (0, 0)),\n (0, (1, 1)),\n (0, (0, 2))),\n (0, 2): ((-1, (1, 2)),\n (0, (0, 1)),\n (0, (1, 2)),\n (0, (0, 3))),\n (0, 3): ((-1, (1, 2)),\n (0, (0, 2)),\n (0, (1, 3)),\n (0, (0, 4))),\n (4, 1): ((-1, (3, 2)),\n (0, (4, 0)),\n (0, (3, 1)),\n (0, (4, 2))),\n (4, 2): ((-1, (3, 2)),\n (0, (4, 1)),\n (0, (3, 2)),\n (0, (4, 3))),\n (4, 3): ((-1, (3, 2)),\n (0, (4, 2)),\n (0, (3, 3)),\n (0, (4, 4))),\n (1, 4): ((-1, (2, 3)),\n (0, (1, 3)),\n (0, (0, 4)),\n (0, (2, 4))),\n (2, 4): ((-1, (2, 3)),\n (0, (1, 4)),\n (0, (2, 3)),\n (0, (3, 4))),\n (3, 4): ((-1, (2, 3)),\n (0, (2, 4)),\n (0, (3, 3)),\n (0, (4, 4))),\n # bordering center tile\n (2, 1):\n ((0, (2, 0)), (0, (1, 1)), (0, (3, 1)),\n (1, (0, 0)), (1, (1, 0)), (1, (2, 0)), (1, (3, 0)), (1, (4, 0))),\n (1, 2):\n ((0, (1, 1)), (0, (0, 2)), (0, (1, 3)),\n (1, (0, 0)), (1, (0, 1)), (1, (0, 2)), (1, (0, 3)), (1, (0, 4))),\n (3, 2):\n ((0, (3, 1)), (0, (4, 2)), (0, (3, 3)),\n (1, (4, 0)), (1, (4, 1)), (1, (4, 2)), (1, (4, 3)), (1, (4, 4))),\n (2, 3):\n ((0, (1, 3)), (0, (2, 4)), (0, (3, 3)),\n (1, (0, 4)), (1, (1, 4)), (1, (2, 4)), (1, (3, 4)), (1, (4, 4))),\n # remaining non-special tiles:\n (1, 1): ((0, (1, 0)), (0, (0, 1)), (0, (2, 1)), (0, (1, 2))),\n (3, 1): ((0, (3, 0)), (0, (2, 1)), (0, (4, 1)), (0, (3, 2))),\n (1, 3): ((0, (0, 3)), (0, (1, 2)), (0, (2, 3)), (0, (1, 4))),\n (3, 3): ((0, (3, 2)), (0, (2, 3)), (0, (4, 3)), (0, (3, 4))),\n # center:\n (2, 2): ()\n }\n def __init__(self, filename):\n self.load(filename)\n\n def load(self, filename):\n grid = open(filename).read().splitlines()\n self.height = len(grid)\n self.width = len(grid[0])\n self.grids = deque([grid])\n assert self.width == 5\n assert self.height == 5\n\n\n def iter_grids(self):\n # First we add new grids to the start and end, and scrap them if they\n # get no new bugs\n self.grids.appendleft(['.'*self.width]*self.height)\n self.grids.append(['.'*self.width]*self.height)\n total_grids = len(self.grids)\n new_grids = deque()\n for i, grid in enumerate(self.grids):\n new_grid = []\n for y in range(self.height):\n new_row = []\n for x in range(self.width):\n bug_neighbours = 0\n tile = grid[y][x]\n for d, (_x, _y) in self.neighbours[x, y]:\n index = d + i\n if 0 <= index < len(self.grids):\n bug_neighbours += self.grids[index][_y][_x] == '#'\n if tile == '#':\n if bug_neighbours == 1:\n new_row.append('#')\n else:\n new_row.append('.')\n else:\n if 1 <= bug_neighbours <= 2:\n new_row.append('#')\n else:\n new_row.append('.')\n new_grid.append(''.join(new_row))\n new_grids.append(new_grid)\n grid = new_grids[0]\n if not any('#' in row for row in grid):\n new_grids.popleft()\n grid = new_grids[-1]\n if not any('#' in row for row in grid):\n new_grids.pop()\n self.grids = new_grids\n\n\ndef solve_2(filename):\n puz = PuzRecursive(filename)\n for __ in range(200):\n puz.iter_grids()\n total = 0\n for grid in puz.grids:\n for row in grid:\n for tile in row:\n total += tile == '#'\n return total\n\n\ndef main():\n filename = \"input.txt\"\n print(solve_1(filename))\n print(solve_2(filename))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"day24/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"314083109","text":"import boto3\nimport locale\nimport json\nfrom pkg_resources import resource_filename\nimport scrape\n\n\n# Translate between the API and what is used locally\ndef translate_platform_name(operating_system, preinstalled_software):\n os = {'Linux': 'linux',\n 'RHEL': 'rhel',\n 'SUSE': 'sles',\n 'Windows': 'mswin'}\n software = {'NA': '',\n 'SQL Std': 'SQL',\n 'SQL Web': 'SQLWeb',\n 'SQL Ent': 'SQLEnterprise'}\n return os[operating_system] + software[preinstalled_software]\n\n\n# Translate between the API and what is used locally\ndef translate_reserved_terms(term_attributes):\n lease_contract_length = term_attributes.get('LeaseContractLength')\n purchase_option = term_attributes.get('PurchaseOption')\n offering_class = term_attributes.get('OfferingClass')\n leases = {'1yr': 'yrTerm1',\n '3yr': 'yrTerm3'}\n options = {'All Upfront': 'allUpfront',\n 'Partial Upfront': 'partialUpfront',\n 'No Upfront': 'noUpfront'}\n return leases[lease_contract_length] + str(offering_class).capitalize() + '.' + options[purchase_option]\n\n\n# The pricing API requires human readable names for some reason\ndef get_region_descriptions():\n result = dict()\n # Source: https://github.com/boto/botocore/blob/develop/botocore/data/endpoints.json\n endpoint_file = resource_filename('botocore', 'data/endpoints.json')\n with open(endpoint_file, 'r') as f:\n endpoints = json.load(f)\n for partition in endpoints['partitions']:\n for region in partition['regions']:\n result[partition['regions'][region]['description']] = region\n\n # The Osaka region is invite only and not in boto's list: https://github.com/boto/botocore/issues/1423\n result['Asia Pacific (Osaka-Local)'] = 'ap-northeast-3'\n # Alias GovCloud US-West to GovCloud US\n result['AWS GovCloud (US-West)'] = result['AWS GovCloud (US)']\n # Alias LA local zone to its home region\n result['US West (Los Angeles)'] = 'us-west-2'\n\n return result\n\n\ndef get_instances():\n instance_types = {}\n ec2_client = boto3.client('ec2', region_name='us-east-1')\n ec2_pager = ec2_client.get_paginator('describe_instance_types')\n instance_type_iterator = ec2_pager.paginate()\n for result in instance_type_iterator:\n for instance_type in result['InstanceTypes']:\n instance_types[instance_type['InstanceType']] = instance_type\n\n instances = {}\n pricing_client = boto3.client('pricing', region_name='us-east-1')\n product_pager = pricing_client.get_paginator('get_products')\n\n product_iterator = product_pager.paginate(\n ServiceCode='AmazonEC2', Filters=[\n # We're gonna assume N. Virginia has all the available types\n {'Type': 'TERM_MATCH', 'Field': 'location', 'Value': 'US East (N. Virginia)'},\n\n ]\n )\n for product_item in product_iterator:\n for offer_string in product_item.get('PriceList'):\n offer = json.loads(offer_string)\n product = offer.get('product')\n\n # Check if it's an instance\n if product.get('productFamily') not in ['Compute Instance', 'Compute Instance (bare metal)', 'Dedicated Host']:\n continue\n\n product_attributes = product.get('attributes')\n instance_type = product_attributes.get('instanceType')\n\n if instance_type in ['u-6tb1', 'u-9tb1', 'u-12tb1']:\n # API returns the name without the .metal suffix\n instance_type = instance_type + '.metal'\n\n if instance_type in instances:\n continue\n\n new_inst = parse_instance(instance_type, product_attributes, instance_types.get(instance_type))\n\n # Some instanced may be dedicated hosts instead\n if new_inst is not None:\n instances[instance_type] = new_inst\n\n print(f\"Found data for instance types: {', '.join(sorted(instances.keys()))}\")\n return list(instances.values())\n\n\ndef add_pricing(imap):\n descriptions = get_region_descriptions()\n pricing_client = boto3.client('pricing', region_name='us-east-1')\n product_pager = pricing_client.get_paginator('get_products')\n\n product_iterator = product_pager.paginate(\n ServiceCode='AmazonEC2', Filters=[\n {'Type': 'TERM_MATCH', 'Field': 'capacityStatus', 'Value': 'Used'},\n {'Type': 'TERM_MATCH', 'Field': 'tenancy', 'Value': 'Shared'},\n {'Type': 'TERM_MATCH', 'Field': 'licenseModel', 'Value': 'No License required'},\n ])\n for product_item in product_iterator:\n for offer_string in product_item.get('PriceList'):\n offer = json.loads(offer_string)\n product = offer.get('product')\n product_attributes = product.get('attributes')\n instance_type = product_attributes.get('instanceType')\n location = product_attributes.get('location')\n\n # There may be a slight delay in updating botocore with new regional endpoints, skip and inform\n if location not in descriptions:\n print(f\"WARNING: Ignoring pricing - unknown location. instance={instance_type}, location={location}\")\n continue\n\n region = descriptions[location]\n terms = offer.get('terms')\n\n operating_system = product_attributes.get('operatingSystem')\n preinstalled_software = product_attributes.get('preInstalledSw')\n platform = translate_platform_name(operating_system, preinstalled_software)\n\n if instance_type not in imap:\n print(f\"WARNING: Ignoring pricing - unknown instance type. instance={instance_type}, location={location}\")\n continue\n\n # If the instance type is not in us-east-1 imap[instance_type] could fail\n try:\n inst = imap[instance_type]\n inst.pricing.setdefault(region, {})\n inst.pricing[region].setdefault(platform, {})\n inst.pricing[region][platform]['ondemand'] = get_ondemand_pricing(terms)\n # Some instances don't offer reserved terms at all\n reserved = get_reserved_pricing(terms)\n if reserved:\n inst.pricing[region][platform]['reserved'] = reserved\n except Exception as e:\n # print more details about the instance for debugging\n print(f\"ERROR: Exception adding pricing for {instance_type}: {e}\")\n\n\ndef format_price(price):\n return str(float(\"%f\" % float(price))).rstrip('0').rstrip('.')\n\n\ndef get_ondemand_pricing(terms):\n ondemand_terms = terms.get('OnDemand', {})\n price = 0.0\n # There should be only one ondemand_term and one price_dimension\n for ondemand_term in ondemand_terms.keys():\n price_dimensions = ondemand_terms.get(ondemand_term).get('priceDimensions')\n for price_dimension in price_dimensions.keys():\n price = price_dimensions.get(price_dimension).get('pricePerUnit').get('USD')\n return format_price(price)\n\n\ndef get_reserved_pricing(terms):\n pricing = {}\n reserved_terms = terms.get('Reserved', {})\n for reserved_term in reserved_terms.keys():\n term_attributes = reserved_terms.get(reserved_term).get('termAttributes')\n price_dimensions = reserved_terms.get(reserved_term).get('priceDimensions')\n # No Upfront instances don't have price dimension for upfront price\n upfront_price = 0.0\n price_per_hour = 0.0\n for price_dimension in price_dimensions.keys():\n temp_price = price_dimensions.get(price_dimension).get('pricePerUnit').get('USD')\n if price_dimensions.get(price_dimension).get('unit') == 'Hrs':\n price_per_hour = temp_price\n else:\n upfront_price = temp_price\n local_term = translate_reserved_terms(term_attributes)\n lease_in_years = term_attributes.get('LeaseContractLength')[0]\n hours_in_term = int(lease_in_years[0]) * 365 * 24\n price = float(price_per_hour) + (float(upfront_price)/hours_in_term)\n pricing[local_term] = format_price(price)\n return pricing\n\n\ndef parse_instance(instance_type, product_attributes, api_description):\n pieces = instance_type.split('.')\n if len(pieces) == 1:\n # Dedicated host that is not u-*.metal, skipping\n # May be a good idea to all dedicated hosts in the future\n return\n\n i = scrape.Instance()\n i.api_description = api_description\n i.instance_type = instance_type\n\n i.family = product_attributes.get('instanceFamily')\n\n if '32-bit' in product_attributes.get('processorArchitecture'):\n i.arch.append('i386')\n\n i.vCPU = locale.atoi(product_attributes.get('vcpu'))\n\n # Memory is given in form of \"1,952 GiB\", let's parse it\n i.memory = locale.atof(product_attributes.get('memory').split(' ')[0])\n\n if api_description:\n i.network_performance = api_description['NetworkInfo']['NetworkPerformance']\n else:\n i.network_performance = product_attributes.get('networkPerformance')\n\n if product_attributes.get('currentGeneration') == 'Yes':\n i.generation = 'current'\n else:\n i.generation = 'previous'\n\n gpu = product_attributes.get('gpu')\n if gpu is not None:\n i.GPU = locale.atoi(gpu)\n\n if api_description:\n if 'FpgaInfo' in api_description:\n for fpga in api_description['FpgaInfo']['Fpgas']:\n i.FPGA += fpga['Count']\n\n netinfo = api_description['NetworkInfo']\n if netinfo['EnaSupport'] == 'required':\n i.ebs_as_nvme = True\n\n i.vpc = { 'max_enis': netinfo['MaximumNetworkInterfaces'],\n 'ips_per_eni': netinfo['Ipv4AddressesPerInterface'] }\n\n try:\n ecu = product_attributes.get('ecu')\n if ecu == 'Variable':\n i.ECU = 'variable'\n else:\n i.ECU = locale.atof(ecu)\n except:\n pass\n\n i.physical_processor = product_attributes.get('physicalProcessor')\n\n # CPU features\n processor_features = product_attributes.get('processorFeatures')\n if processor_features is not None:\n if \"Intel AVX512\" in processor_features:\n i.intel_avx512 = True\n if \"Intel AVX2\" in processor_features:\n i.intel_avx2 = True\n if \"Intel AVX\" in processor_features:\n i.intel_avx = True\n if \"Intel Turbo\" in processor_features:\n i.intel_turbo = True\n\n i.clock_speed_ghz = product_attributes.get('clockSpeed')\n\n enhanced_networking = product_attributes.get('enhancedNetworkingSupported')\n if enhanced_networking is not None and enhanced_networking == 'Yes':\n i.enhanced_networking = True\n\n return i\n","sub_path":"ec2.py","file_name":"ec2.py","file_ext":"py","file_size_in_byte":10782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"328012103","text":"#############################################################################\n# lag_processor.py\n#\n# Description: Contains class for computing lagged features\n#############################################################################\n\nimport itertools\nimport logging\nimport numpy as np\nimport pandas as pd\n\nfrom functools import partial\nfrom sklearn.base import TransformerMixin\nfrom pandas.tseries.frequencies import to_offset\n\nfrom utils import get_freq\nfrom storm_utils import (\n iterate_storms_method,\n apply_storms,\n StormAccessor,\n StormIndexAccessor,\n has_storm_index,\n)\n\nlogger = logging.getLogger(__name__)\n\nZERO_MINUTES = to_offset(\"0T\")\n\n\nclass LaggedFeaturesProcessor:\n \"\"\"\n NOTE: X, y don't necessarily have the same freq so we can't just pass one\n combined dataframe.\n\n XXX: Not a proper scikit learn transformer. fit and transform take X and y.\n\n \"\"\"\n\n def __init__(\n self,\n lag=\"0T\",\n exog_lag=\"H\",\n lead=\"0T\",\n unit=\"minutes\",\n history_freq=None,\n history_func=\"mean\",\n transformer_y=None,\n njobs=1,\n return_pandas=False,\n verbose=False,\n **transformer_y_kwargs,\n ):\n\n self.unit = unit\n self.lag = self._process_params(lag)\n self.exog_lag = self._process_params(exog_lag)\n self.lead = self._process_params(lead)\n self.history_freq = self._process_params(history_freq)\n self.history_func = history_func\n\n self.njobs = njobs\n self.return_pandas = return_pandas\n self.verbose = verbose\n\n # NOTE: transformer_y must keep input as pd DataFrame\n # NOTE: Pass transformer that was used for X here.\n # (use PandasTransformer if required)\n self.transformer_y = transformer_y\n self.transformer_y_kwargs = transformer_y_kwargs\n\n def _process_params(self, param):\n\n if param is None:\n return None\n\n assert isinstance(param, (str, int))\n\n if isinstance(param, str):\n param = to_offset(param)\n elif isinstance(param, int):\n param = to_offset(pd.Timedelta(**{self.unit: param}))\n\n return param\n\n def _check_data(self, X, y):\n # TODO: Input validation\n # - pd Dataframe\n pass\n\n # TODO: Use storm accessor wherever possible\n def _compute_feature(self, target_index, X, y=None):\n \"\"\"Computes ARX features to predict target at a specified time\n `target_time`.\n\n This method ravels subsets of `target` and `self.solar_wind` that depend on\n `self.lag` and `self.exog_lag` to obtain features to predict the target\n time series at a specified `target_time`.\n\n Parameters\n ----------\n\n target_time : datetime-like\n Time to predict.\n X : pd.DataFrame\n Exogeneous features\n y : pd.DataFrame or pd.Series\n Target time series to use as features to predict at target_time\n\n Returns\n -------\n np.ndarray\n Array containing features to use to predict target at target_time.\n\n # FIXME: Docstring outdated\n \"\"\"\n\n # HACK: Assume time is the second element if target_index is MultiIndex tuple\n if isinstance(target_index, tuple):\n target_storm, target_time = target_index\n else:\n # TODO: Change to elif time index\n target_time = target_index\n\n feature = np.full(self.n_cols_, np.nan)\n end = target_time - self.lead\n\n # Ravel target and solar wind between start and end time\n if self.n_lag_ != 0:\n assert y is not None\n # HACK: Subset storm\n if has_storm_index(y):\n y = y.xs(target_storm, level=\"storm\")\n\n start = end - self.lag\n y_ = y[start:end][::-1]\n\n if self.history_freq is not None:\n y_ = y_.resample(\n self.history_freq, label=\"right\", closed=\"right\", origin=\"start\"\n ).apply(self.history_func)[::-1]\n\n feature[: self.n_lag_] = y_[: self.n_lag_].to_numpy().ravel()\n\n if self.n_exog_each_col_ != 0:\n # HACK: Subset storm\n if has_storm_index(X):\n X = X.xs(target_storm, level=\"storm\")\n\n start_exog = end - self.exog_lag\n X_ = X[start_exog:end][::-1][: self.n_exog_each_col_]\n feature[self.n_lag_ : self.n_cols_] = X_.to_numpy().ravel()\n\n # error_msg = f\"Length of feature ({len(feature)}) at {target_index} != self.n_cols_ ({self.n_cols_})\"\n # assert len(feature) == self.n_cols_, error_msg\n\n return feature\n\n def fit(self, X, y=None):\n\n # TODO: Replace with function from utils\n self.freq_X_ = get_freq(X)\n if self.lag != ZERO_MINUTES and y is not None:\n self.freq_y_ = get_freq(y)\n\n if self.history_freq is not None:\n # Doesn't make sense to have history_freq < y's freq since there will be\n # unnecessary NAs\n assert self.history_freq >= self.freq_y_\n\n if self.lag == ZERO_MINUTES:\n self.n_lag_ = 0\n else:\n if self.history_freq is not None:\n history_freq = self.history_freq\n else:\n history_freq = self.freq_y_\n\n self.n_lag_ = int(self.lag / history_freq)\n\n logger.debug(\"# of lagged features: %s\", self.n_lag_)\n\n if self.exog_lag == ZERO_MINUTES:\n self.n_exog_each_col_ = 0\n else:\n self.n_exog_each_col_ = int((self.exog_lag / self.freq_X_))\n\n n_exog = self.n_exog_each_col_ * X.shape[1]\n logger.debug(\"# of exogeneous features: %s\", n_exog)\n\n self.n_cols_ = self.n_lag_ + n_exog\n\n self.feature_names_ = self.get_feature_names(X, y)\n assert len(self.feature_names_) == self.n_cols_\n\n if self.transformer_y is not None and y is not None:\n self.transformer_y.set_params(**self.transformer_y_kwargs)\n self.transformer_y.fit(y)\n\n return self\n\n def get_feature_names(self, X, y=None):\n\n exog_feature_names = self._get_feature_names(\n self.exog_lag, X.columns, self.freq_X_\n )\n\n if y is None:\n return exog_feature_names\n\n if self.history_freq is None:\n lag_freq = self.freq_y_\n else:\n lag_freq = self.history_freq\n\n lag_feature_names = self._get_feature_names(self.lag, [\"y\"], lag_freq)\n\n # Lagged y goes first\n return lag_feature_names + exog_feature_names\n\n @staticmethod\n def _get_feature_names(lag, columns, freq):\n lags_timedelta = pd.timedelta_range(\n start=\"0 days\", end=lag, freq=freq, closed=\"left\"\n )\n # Minutes in reverse order\n lags = (int(t.total_seconds() / 60) for t in lags_timedelta)\n\n # Order: Iterate columns first\n # e.g. [density0, density5, ..., temperature0, temperature5, ....]\n feature_names = [f\"{col}_{t}\" for t, col in itertools.product(lags, columns)]\n\n return feature_names\n\n # @iterate_storms_method(drop_storms=True)\n # def _get_target(self, X, y=None):\n # # TODO: Handle MultiIndex case\n\n # if y is not None:\n # y = y.dropna()\n # y_start = y.index[0]\n # else:\n # y_start = 0\n\n # max_time = max(\n # to_offset(self.lag) + y_start, to_offset(self.exog_lag) + X.index[0]\n # )\n # cutoff = max_time + self.lead\n\n # # FIXME\n # return y[y.index > cutoff]\n\n @iterate_storms_method(drop_storms=True)\n def _get_target_index(self, X, y=None):\n # TODO: Handle MultiIndex case\n\n if y is not None:\n y = y.dropna()\n y_start = y.index[0]\n else:\n y_start = 0\n\n max_time = max(\n to_offset(self.lag) + y_start, to_offset(self.exog_lag) + X.index[0]\n )\n cutoff = max_time + self.lead\n\n if y is not None:\n return y.index[y.index > cutoff]\n else:\n return X.index[X.index > cutoff]\n\n @iterate_storms_method([\"target_index\"], concat=\"numpy\", drop_storms=True)\n def _transform(self, X, y, target_index):\n # TODO: Implement parallel\n\n n_obs = len(target_index)\n\n compute_feature_ = partial(self._compute_feature, X=X, y=y)\n features_map = map(compute_feature_, target_index)\n\n features_iter = itertools.chain.from_iterable(features_map)\n features = np.fromiter(\n features_iter, dtype=np.float32, count=n_obs * self.n_cols_\n ).reshape(n_obs, self.n_cols_)\n\n return features\n\n def transform(self, X, y=None):\n # NOTE: Include interpolator in transformer_y if want to interpolate\n # TODO: Write tests\n\n if y is None:\n y_feature = None\n elif self.transformer_y is not None:\n y_feature = self.transformer_y.transform(y)\n else:\n y_feature = y\n\n logger.debug(\"Getting targets...\")\n # y_target = self._get_target(X, y)\n target_index = self._get_target_index(X, y)\n\n logger.debug(\"Computing lagged features...\")\n # features = self._transform(X, y_feature, target_index=y_target.index)\n features = self._transform(X, y_feature, target_index=target_index)\n\n assert features.shape[0] == len(target_index)\n\n if self.return_pandas:\n features = pd.DataFrame(\n features, index=target_index, columns=self.feature_names_\n )\n\n if y is None:\n return features, None\n else:\n return features, y.loc[target_index]\n\n # return features, y_target\n\n def fit_transform(self, X, y=None, **fit_params):\n # fit_transform from TransformerMixin doesn't allow y in transform\n return self.fit(X, y, **fit_params).transform(X, y)\n","sub_path":"lag_processor.py","file_name":"lag_processor.py","file_ext":"py","file_size_in_byte":9962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"532645244","text":"import math\nno_of_entries = int(input(\"Enter number of entries:\"))\ni = 1\nnum_lists = []\nwhile i <= no_of_entries:\n num_inputs = int(input(\"Enter a number\"))\n num_lists.append(num_inputs)\n geo_mean = (math.prod(num_lists)) ** (1/no_of_entries)\n i += 1\nprint(\"The geometric mean is \",geo_mean)\n","sub_path":"Geometric-mean.py","file_name":"Geometric-mean.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"42643237","text":"import unittest\r\n\r\nfrom mockito import unstub, mock, when, verifyZeroInteractions, verify\r\n\r\nfrom app.customers.model import Customer\r\nfrom app.customers.service import CustomerNotificationService\r\n\r\n\r\nclass CustomerNotificationServiceTestCase(unittest.TestCase):\r\n\r\n mock_customers = [Customer(1, 'Armando Barreda', 1, 1), Customer(2, 'Cosme Fulanito', 2, 2)]\r\n customer_dao_mock = None\r\n max_kilometers_allowed = 100\r\n great_circle_distance_service_mock = None\r\n\r\n def setUp(self):\r\n self.customer_dao_mock = mock()\r\n self.great_circle_distance_service_mock = mock()\r\n self.service = CustomerNotificationService(self.customer_dao_mock,\r\n self.max_kilometers_allowed,\r\n self.great_circle_distance_service_mock)\r\n\r\n def tearDown(self):\r\n unstub()\r\n\r\n def test_empty_customers(self):\r\n when(self.customer_dao_mock).retrieve_all().thenReturn([])\r\n result = self.service.execute()\r\n self.assertEqual(len(result), 0)\r\n verifyZeroInteractions(self.great_circle_distance_service_mock)\r\n\r\n def test_retrieve_error(self):\r\n when(self.customer_dao_mock).retrieve_all().thenRaise(Exception('mock_exception'))\r\n try:\r\n self.service.execute()\r\n self.fail('Exception not raised')\r\n except Exception as e:\r\n self.assertEqual(e.args[0], 'mock_exception')\r\n verifyZeroInteractions(self.great_circle_distance_service_mock)\r\n\r\n def test_circe_distance_error(self):\r\n when(self.customer_dao_mock).retrieve_all().thenRaise(Exception('mock_exception'))\r\n try:\r\n self.service.execute()\r\n self.fail('Exception not raised')\r\n except Exception as e:\r\n self.assertEqual(e.args[0], 'mock_exception')\r\n\r\n def test_customers_not_match(self):\r\n when(self.customer_dao_mock).retrieve_all().thenReturn(self.mock_customers)\r\n when(self.great_circle_distance_service_mock).calculate(1, 1).thenReturn(101)\r\n when(self.great_circle_distance_service_mock).calculate(2, 2).thenReturn(120)\r\n\r\n response = self.service.execute()\r\n\r\n verify(self.customer_dao_mock, times=1).retrieve_all()\r\n verify(self.great_circle_distance_service_mock, times=2).calculate(...)\r\n self.assertEqual(len(response), 0, 'Customers should have been filtered because of distance')\r\n\r\n def test_customers_ok(self):\r\n when(self.customer_dao_mock).retrieve_all().thenReturn(self.mock_customers)\r\n when(self.great_circle_distance_service_mock).calculate(1, 1).thenReturn(100)\r\n when(self.great_circle_distance_service_mock).calculate(2, 2).thenReturn(90)\r\n\r\n response = self.service.execute()\r\n dict1 = response[0]\r\n dict2 = response[1]\r\n\r\n verify(self.customer_dao_mock, times=1).retrieve_all()\r\n verify(self.great_circle_distance_service_mock, times=2).calculate(...)\r\n\r\n self.assertEqual(len(response), 2, 'Customers should have not been filtered because of distance')\r\n\r\n self.assertEqual('Armando Barreda', dict1['name'])\r\n self.assertEqual(1, dict1['user_id'])\r\n\r\n self.assertEqual('Cosme Fulanito', dict2['name'])\r\n self.assertEqual(2, dict2['user_id'])\r\n\r\n","sub_path":"test/customers/service_test.py","file_name":"service_test.py","file_ext":"py","file_size_in_byte":3345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"489178856","text":"#!/usr/bin/env python3\n\"\"\"\nAPI server to run the JSON-RPC and REST API.\n\nUses servers specified in protocol.xxx.json files\n\nPrint the help and all possible arguments:\n\n ./api-server.py -h\n\nRun using TestNet with JSON-RPC API at port 10332 and REST API at port 8080:\n\n ./api-server.py --testnet --port-rpc 10332 --port-rest 8080\n\nSee also:\n\n* If you encounter any issues, please report them here: https://github.com/CityOfZion/neo-python/issues/273\n* Server setup\n * Guide for Ubuntu server setup: https://gist.github.com/metachris/2be27cdff9503ebe7db1c27bfc60e435\n * Systemd service config: https://gist.github.com/metachris/03d1cc47df7cddfbc4009d5249bdfc6c\n * Ansible playbook to update nodes: https://gist.github.com/metachris/2be27cdff9503ebe7db1c27bfc60e435\n\nLogging\n-------\n\nThis api-server can log to stdout/stderr, logfile and syslog.\nCheck `api-server.py -h` for more details.\n\nTwisted uses a quite custom logging setup. Here we simply setup the Twisted logger\nto reuse our logzero logging setup. See also:\n\n* http://twisted.readthedocs.io/en/twisted-17.9.0/core/howto/logger.html\n* https://twistedmatrix.com/documents/17.9.0/api/twisted.logger.STDLibLogObserver.html\n\"\"\"\nimport os\nimport sys\nimport argparse\nimport threading\nfrom time import sleep\nfrom logging.handlers import SysLogHandler\n\nimport logzero\nfrom logzero import logger\nfrom prompt_toolkit import prompt\n\n# Twisted logging\nfrom twisted.logger import STDLibLogObserver, globalLogPublisher\n\n# Twisted and Klein methods and modules\nfrom twisted.internet import reactor, task, endpoints, threads\nfrom twisted.web.server import Site\n\n# neo methods and modules\nfrom neo.Core.Blockchain import Blockchain\nfrom neo.Implementations.Blockchains.LevelDB.LevelDBBlockchain import LevelDBBlockchain\nfrom neo.Implementations.Notifications.LevelDB.NotificationDB import NotificationDB\nfrom neo.Wallets.utils import to_aes_key\nfrom neo.Implementations.Wallets.peewee.UserWallet import UserWallet\n\nfrom neo.Network.NodeLeader import NodeLeader\nfrom neo.Settings import settings\nfrom neo.Utils.plugin import load_class_from_path\nimport neo.Settings\n\n# Logfile default settings (only used if --logfile arg is used)\nLOGFILE_MAX_BYTES = 5e7 # 50 MB\nLOGFILE_BACKUP_COUNT = 3 # 3 logfiles history\n\n# Set the PID file, possible to override with env var PID_FILE\nPID_FILE = os.getenv(\"PID_FILE\", \"/tmp/neopython-api-server.pid\")\n\ncontinue_persisting = True\nblock_deferred = None\n\n\ndef write_pid_file():\n \"\"\" Write a pid file, to easily kill the service \"\"\"\n with open(PID_FILE, \"w\") as f:\n f.write(str(os.getpid()))\n\n\ndef custom_background_code():\n \"\"\" Custom code run in a background thread.\n\n This function is run in a daemonized thread, which means it can be instantly killed at any\n moment, whenever the main thread quits. If you need more safety, don't use a daemonized\n thread and handle exiting this thread in another way (eg. with signals and events).\n \"\"\"\n while True:\n logger.info(\"[%s] Block %s / %s\", settings.net_name, str(Blockchain.Default().Height + 1), str(Blockchain.Default().HeaderHeight + 1))\n sleep(15)\n\n\ndef on_persistblocks_error(err):\n logger.debug(\"On Persist blocks loop error! %s \" % err)\n\n\ndef stop_block_persisting():\n global continue_persisting\n continue_persisting = False\n\n\ndef persist_done(value):\n \"\"\"persist callback. Value is unused\"\"\"\n if continue_persisting:\n start_block_persisting()\n else:\n block_deferred.cancel()\n\n\ndef start_block_persisting():\n global block_deferred\n block_deferred = threads.deferToThread(Blockchain.Default().PersistBlocks)\n block_deferred.addCallback(persist_done)\n block_deferred.addErrback(on_persistblocks_error)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n\n # Network options\n group_network_container = parser.add_argument_group(title=\"Network options\")\n group_network = group_network_container.add_mutually_exclusive_group(required=True)\n group_network.add_argument(\"--mainnet\", action=\"store_true\", default=False, help=\"Use MainNet\")\n group_network.add_argument(\"--testnet\", action=\"store_true\", default=False, help=\"Use TestNet\")\n group_network.add_argument(\"--privnet\", action=\"store_true\", default=False, help=\"Use PrivNet\")\n group_network.add_argument(\"--coznet\", action=\"store_true\", default=False, help=\"Use CozNet\")\n group_network.add_argument(\"--config\", action=\"store\", help=\"Use a specific config file\")\n\n # Ports for RPC and REST api\n group_modes = parser.add_argument_group(title=\"Mode(s)\")\n group_modes.add_argument(\"--port-rpc\", type=int, help=\"port to use for the json-rpc api (eg. 10332)\")\n group_modes.add_argument(\"--port-rest\", type=int, help=\"port to use for the rest api (eg. 80)\")\n\n # Advanced logging setup\n group_logging = parser.add_argument_group(title=\"Logging options\")\n group_logging.add_argument(\"--logfile\", action=\"store\", type=str, help=\"Logfile\")\n group_logging.add_argument(\"--syslog\", action=\"store_true\", help=\"Log to syslog instead of to log file ('user' is the default facility)\")\n group_logging.add_argument(\"--syslog-local\", action=\"store\", type=int, choices=range(0, 7), metavar=\"[0-7]\",\n help=\"Log to a local syslog facility instead of 'user'. Value must be between 0 and 7 (e.g. 0 for 'local0').\")\n group_logging.add_argument(\"--disable-stderr\", action=\"store_true\", help=\"Disable stderr logger\")\n\n # Where to store stuff\n parser.add_argument(\"--datadir\", action=\"store\",\n help=\"Absolute path to use for database directories\")\n # peers\n parser.add_argument(\"--maxpeers\", action=\"store\", default=5,\n help=\"Max peers to use for P2P Joining\")\n\n # If a wallet should be opened\n parser.add_argument(\"--wallet\",\n action=\"store\",\n help=\"Open wallet. Will allow you to use methods that require an open wallet\")\n\n # host\n parser.add_argument(\"--host\", action=\"store\", type=str, help=\"Hostname ( for example 127.0.0.1)\", default=\"0.0.0.0\")\n\n # Now parse\n args = parser.parse_args()\n # print(args)\n\n if not args.port_rpc and not args.port_rest:\n print(\"Error: specify at least one of --port-rpc / --port-rest\")\n parser.print_help()\n return\n\n if args.port_rpc == args.port_rest:\n print(\"Error: --port-rpc and --port-rest cannot be the same\")\n parser.print_help()\n return\n\n if args.logfile and (args.syslog or args.syslog_local):\n print(\"Error: Cannot only use logfile or syslog at once\")\n parser.print_help()\n return\n\n # Setting the datadir must come before setting the network, else the wrong path is checked at net setup.\n if args.datadir:\n settings.set_data_dir(args.datadir)\n\n # Network configuration depending on command line arguments. By default, the testnet settings are already loaded.\n if args.config:\n settings.setup(args.config)\n elif args.mainnet:\n settings.setup_mainnet()\n elif args.testnet:\n settings.setup_testnet()\n elif args.privnet:\n settings.setup_privnet()\n elif args.coznet:\n settings.setup_coznet()\n\n if args.maxpeers:\n try:\n settings.set_max_peers(args.maxpeers)\n print(\"Maxpeers set to \", args.maxpeers)\n except ValueError:\n print(\"Please supply a positive integer for maxpeers\")\n return \n\n if args.syslog or args.syslog_local is not None:\n # Setup the syslog facility\n if args.syslog_local is not None:\n print(\"Logging to syslog local%s facility\" % args.syslog_local)\n syslog_facility = SysLogHandler.LOG_LOCAL0 + args.syslog_local\n else:\n print(\"Logging to syslog user facility\")\n syslog_facility = SysLogHandler.LOG_USER\n\n # Setup logzero to only use the syslog handler\n logzero.syslog(facility=syslog_facility)\n else:\n # Setup file logging\n if args.logfile:\n logfile = os.path.abspath(args.logfile)\n if args.disable_stderr:\n print(\"Logging to logfile: %s\" % logfile)\n else:\n print(\"Logging to stderr and logfile: %s\" % logfile)\n logzero.logfile(logfile, maxBytes=LOGFILE_MAX_BYTES, backupCount=LOGFILE_BACKUP_COUNT, disableStderrLogger=args.disable_stderr)\n\n else:\n print(\"Logging to stdout and stderr\")\n\n if args.wallet:\n if not os.path.exists(args.wallet):\n print(\"Wallet file not found\")\n return\n\n passwd = os.environ.get('NEO_PYTHON_JSONRPC_WALLET_PASSWORD', None)\n if not passwd:\n passwd = prompt(\"[password]> \", is_password=True)\n\n password_key = to_aes_key(passwd)\n try:\n wallet = UserWallet.Open(args.wallet, password_key)\n\n except Exception as e:\n print(f\"Could not open wallet {e}\")\n return\n else:\n wallet = None\n\n # Disable logging smart contract events\n settings.set_log_smart_contract_events(False)\n\n # Write a PID file to easily quit the service\n write_pid_file()\n\n # Setup Twisted and Klein logging to use the logzero setup\n observer = STDLibLogObserver(name=logzero.LOGZERO_DEFAULT_LOGGER)\n globalLogPublisher.addObserver(observer)\n\n def loopingCallErrorHandler(error):\n logger.info(\"Error in loop: %s \" % error)\n\n # Instantiate the blockchain and subscribe to notifications\n blockchain = LevelDBBlockchain(settings.chain_leveldb_path)\n Blockchain.RegisterBlockchain(blockchain)\n\n start_block_persisting()\n\n # If a wallet is open, make sure it processes blocks\n if wallet:\n walletdb_loop = task.LoopingCall(wallet.ProcessBlocks)\n wallet_loop_deferred = walletdb_loop.start(1)\n wallet_loop_deferred.addErrback(loopingCallErrorHandler)\n\n # Setup twisted reactor, NodeLeader and start the NotificationDB\n reactor.suggestThreadPoolSize(15)\n NodeLeader.Instance().Start()\n NotificationDB.instance().start()\n\n # Start a thread with custom code\n d = threading.Thread(target=custom_background_code)\n d.setDaemon(True) # daemonizing the thread will kill it when the main thread is quit\n d.start()\n\n if args.port_rpc:\n logger.info(\"Starting json-rpc api server on http://%s:%s\" % (args.host, args.port_rpc))\n try:\n rpc_class = load_class_from_path(settings.RPC_SERVER)\n except ValueError as err:\n logger.error(err)\n sys.exit()\n api_server_rpc = rpc_class(args.port_rpc, wallet=wallet)\n\n endpoint_rpc = \"tcp:port={0}:interface={1}\".format(args.port_rpc, args.host)\n endpoints.serverFromString(reactor, endpoint_rpc).listen(Site(api_server_rpc.app.resource()))\n\n if args.port_rest:\n logger.info(\"Starting REST api server on http://%s:%s\" % (args.host, args.port_rest))\n try:\n rest_api = load_class_from_path(settings.REST_SERVER)\n except ValueError as err:\n logger.error(err)\n sys.exit()\n api_server_rest = rest_api()\n endpoint_rest = \"tcp:port={0}:interface={1}\".format(args.port_rest, args.host)\n endpoints.serverFromString(reactor, endpoint_rest).listen(Site(api_server_rest.app.resource()))\n\n reactor.addSystemEventTrigger('before', 'shutdown', stop_block_persisting)\n reactor.run()\n\n # After the reactor is stopped, gracefully shutdown the database.\n logger.info(\"Closing databases...\")\n NotificationDB.close()\n Blockchain.Default().Dispose()\n NodeLeader.Instance().Shutdown()\n if wallet:\n wallet.Close()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"neo/bin/api_server.py","file_name":"api_server.py","file_ext":"py","file_size_in_byte":11747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"247256310","text":"#!/usr/bin/python\nimport sys\nimport csv\nimport re\n\nreader = csv.reader(sys.stdin, delimiter = '\\t')\nwriter = csv.writer(sys.stdout, delimiter = '\\t', quotechar = '\"',\n\tquoting = csv.QUOTE_ALL)\n\nfor line in reader:\n\tnode_id = line[0]\n\tbody = line[4]\n\n\twords = re.split(r'\\.|,|!|\\?|\\s|:|\\n|;|\"|\\(|\\)|<|>|\\[|\\]|#|\\$|=|-|/', body)\n\n\tfor word in words:\n\t\tif not (word == \"\" or word == \"p\"):\n\t\t\twriter.writerow([word.lower(), node_id])\n\t\telse:\n\t\t\tcontinue","sub_path":"code/forum_data/summarizing/inverted_index_mapper.py","file_name":"inverted_index_mapper.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"532092689","text":"\"\"\"\nA small grid world with a \"mother\" cat and a lot of \"baby\" cats.\nThe cats get positive reinforcement for eating.\nFood appears on the grid at one of four corners.\nThe mother can see the entire grid, the babies only see nearby.\n\nThe babies have a fixed policy:\nIf they see food, they go to the food.\nElse, if they see the mother, they go to the mother.\nElse, they stay put.\n\nThe mother can have varying degrees of selfishness and empathy.\nSelfishness determines how much she wants to eat.\nEmpathy determines how much she wants the babies to eat.\nBoth can be positive or negative numbers.\nHer policy is to be determined by MDP value iteration.\n\nState representation:\n(\n mother x, mother y,\n (..., baby x, ...), (..., baby y, ...)),\n food\n)\n\nwhere food is a length-4 boolean tuple which is True for each corner that has food.\nCorners are listed clockwise in the order (0,0), (0,5), (5,5), (5,0)\n\"\"\"\nimport itertools as it\nimport numpy as np\nimport scipy.sparse as sp\nimport matplotlib.pyplot as pt\nfrom scipy.sparse import identity\nimport random\n\n\n# Initial parameters. P tables need to be rebuilt when these are changed.\ngrid_cols = 6 # size of grid world\ngrid_rows = 6 # size of grid world\nbaby_view = 1 # how far babies can see\nnum_babies = 2 # number of babies\n\n# total number of possible states (mother/baby/food positions)\nnum_states = (grid_cols*grid_rows)**(1+num_babies) * 2**4\n\ndef food_coords(food):\n \"\"\"\n Convert a length 4 boolean food array into x/y coordinates of food.\n For example, if food == (True, False, True, True), then\n f_x = (0, 5, 5), f_y = (0, 5, 0)\n \"\"\"\n f_x = tuple(np.array([0, 0, grid_cols-1, grid_cols-1])[np.array(food, dtype=bool)])\n f_y = tuple(np.array([0, grid_rows-1, grid_rows-1, 0])[np.array(food, dtype=bool)])\n \n return f_x, f_y\n\ndef plot_state(state):\n \"\"\"\n Visualize a state with matplotlib:\n Green circles are food\n Red circle is mother\n Blue circles are babies\n A little noise is added to each baby position to see distinct babies\n \"\"\"\n m_x, m_y, b_x, b_y, food = state\n f_x, f_y = food_coords(food)\n pt.scatter(f_x, f_y, s=400, c='g')\n pt.scatter(m_x, m_y, s=200, c='r')\n pt.scatter(\n np.array(b_x)+np.random.randn(num_babies)*0.1,\n np.array(b_y)+np.random.randn(num_babies)*0.1, s=50, c='b')\n pt.xlim([-1, grid_cols])\n pt.ylim([-1, grid_rows])\n pt.grid()\n\ndef state_to_index(state):\n \"\"\"\n For initial parameters there are ~ 700K possible states.\n This assigns each of those states a unique index in the range 0,...,700K-1.\n \"\"\"\n m_x, m_y, b_x, b_y, food = state\n digits = (m_x, m_y) + b_x + b_y + food\n factors = [grid_cols, grid_rows]*(num_babies+1) + [2]*4\n idx = 0\n coef = 1\n for i in range(2*(1 + num_babies) + 4):\n idx += digits[i]*coef\n coef *= factors[i]\n return int(idx)\n\ndef index_to_state(idx):\n \"\"\"\n This method is the inverse of \"state_to_index\":\n Given an integer index, it reconstructs the corresponding state.\n \"\"\"\n factors = [grid_cols, grid_rows]*(num_babies+1) + [2]*4\n digits = []\n for i in range(2*(1 + num_babies) + 4):\n digit = idx % factors[i]\n idx = (idx - digit) / factors[i]\n digits.append(digit)\n m_x, m_y = tuple(digits[:2])\n b_x = tuple(digits[2:2+num_babies])\n b_y = tuple(digits[2+num_babies:-4])\n food = tuple(digits[-4:])\n return (m_x, m_y, b_x, b_y, food)\n\ndef move(state, dx, dy):\n \"\"\"\n This moves the mother's position by dx,dy grid units.\n Babies will also move according to their fixed policy.\n It returns the new state after the mother has moved.\n Typically dx and dy will be in [-1,0,1].\n So the mother moves one unit at a time horizontally/vertically/diagonally.\n \"\"\"\n m_x, m_y, b_x, b_y, food = state\n f_x, f_y = food_coords(food)\n #print(food[2])\n # move babies\n food1=list(food)\n #print(food1)\n# for fx, fy in zip(f_x, f_y):\n# if max(abs(fx-m_x), abs(fy-m_y)) == 0:\n# print(\"*\")\n# if fx ==0 & fy==0:\n# food1[0] = 0.0\n# elif fx ==0 & fy==5:\n# food1[1]= 0.0\n# elif fx==5 & fy==5:\n# food1[2]= 0.0\n# elif fx==5 & fy==0:\n# food1[3]= 0.0\n b_x_new, b_y_new = [], []\n for bx, by in zip(b_x, b_y):\n\n # if food is in this baby's view, it steps towards food\n food_step = False\n for fx, fy in zip(f_x, f_y):\n \n if max(abs(fx-bx), abs(fy-by)) <= baby_view:\n food_step = True\n \n b_x_new.append(bx + np.sign(fx-bx))\n b_y_new.append(by + np.sign(fy-by))\n if max(abs(fx-bx), abs(fy-by)) == 0:\n if fx ==0 and fy==0:\n food1[0] = False\n elif fx ==0 and fy==5:\n food1[1]= False\n elif fx==5 and fy==5:\n food1[2]= False\n elif fx==5 and fy==0:\n print(\"*\")\n \n food1[3]= False\n print(food1[3])\n# food = tuple(food1)\n# print(1)\n# food = reappear(food)\n## if fx==0 && fy==0\n# food = (False, , ,)\n# elif fx=0 && fy ==5:\n# food = (False, False, False, False)\n# i =0\n# while i<5:\n# i =i+1\n \n \n\n\n \n break\n if food_step: continue\n \n # otherwise, if mother is in this baby's view, it steps towards mother\n if max(abs(m_x-bx), abs(m_y-by)) <= baby_view:\n b_x_new.append(bx + np.sign(m_x-bx))\n b_y_new.append(by + np.sign(m_y-by))\n \n continue\n \n # otherwise, this baby stays at its current position\n b_x_new.append(bx)\n b_y_new.append(by)\n # move mother\n m_x_new = max(0, min(m_x + dx, grid_cols-1))\n m_y_new = max(0, min(m_y + dy, grid_rows-1))\n for fx, fy in zip(f_x, f_y):\n if max(abs(fx-m_x), abs(fy-m_y)) == 0:\n print(\"*\")\n if fx ==0 and fy==0:\n food1[0] = False\n elif fx ==0 and fy==5:\n food1[1]= False\n elif fx==5 and fy==5:\n food1[2]= False\n elif fx==5 and fy==0:\n food1[3]= False\n print(food1[3])\n food = tuple(food1)\n print(food1) \n \n print(food)\n# i= 0\n# while i<5:\n# i=i+1\n# print(food)\n# i= 0\n# while i<10:\n# i=i+1\n# print(food)\n new_state = (m_x_new, m_y_new, tuple(b_x_new), tuple(b_y_new), food)\n return new_state\n\ndef reappear(food):\n a = random.uniform(0,1)\n food1 = list(food)\n print(len(food1))\n b=[]\n if a <= 0.1:\n print(2)\n for i in range(len(food1)):\n if food1[i] == False:\n b.append(i)\n r = random.randint(0,len(b))\n if r ==1:\n food = (True, False, False, False) \n elif r ==2:\n food = (False, True, False, False) \n elif r == 3:\n food = (False, False, True, False) \n elif r == 4:\n food = (False, False, False, True) \n else:\n food = (False, False, False, False) \n else:\n print(3)\n for i in range(len(food1)):\n if food1[i] == False:\n b.append(i)\n r = random.randint(0,len(b))\n if r ==1:\n food = (True, False, False, False) \n elif r ==2:\n food = (False, True, False, False) \n elif r == 3:\n food = (False, False, True, False) \n elif r == 4:\n food = (False, False, False, True) \n else:\n food = (False, False, False, False) \n \n return food\n\ndef reward(state, selfish=0., empathy=4.):\n \"\"\"\n This computes the mother's reward in the given state.\n By default, the reward is zero.\n If the mother is colocated with food, 'selfish' is added to her reward.\n If a baby is colocated with food, 'empathy' is added to her reward.\n Either 'selfish' or 'empathy' can be negative:\n selfish < 0: the mother wants starve\n empathy < 0: the mother wants babies to starve\n \"\"\"\n m_x, m_y, b_x, b_y, food = state\n f_x, f_y = food_coords(food)\n r = 0.\n for fx, fy in zip(f_x, f_y):\n if m_x == fx and m_y == fy:\n r += selfish\n break\n for bx, by in zip(b_x, b_y):\n if bx == fx and by == fy:\n r += empathy\n break\n return r\n\ndef build_mdp():\n \"\"\"\n Builds the transition arrays P defining the MDP:\n P[(dx,dy)] is a 2d probability matrix when action (dx,dy) is taken.\n If the mother is in state with index i, and moves by (dx,dy),\n there is some probability the mother will end up in another state with index j.\n P[(dx,dy)][i,j] is that probability.\n So P[(dx,dy)] is a 700K x 700K matrix, which is huge.\n However, most probabilities are zero (there is no chance the mother will jump 3 spaces for example).\n So P[(dx,dy)] can be feasibly stored as a *sparse* matrix.\n For this we use scipy's \"CSR\" format to build the sparse matrices.\n \"\"\"\n \n # Initial input data for CSR construction:\n # P[row_ind[k], col_ind[k]] = data[k]\n # Any position not in row_ind, col_ind are zero.\n drc = {\n (dx,dy): {\"data\": [], \"row_ind\": [], \"col_ind\": []}\n for dx in [-1,0,1] for dy in [-1,0,1]}\n\n print(\"Building MDP\")\n # Enumerate each possible state by its index\n for idx in range(num_states):\n\n if idx % (num_states / 100) == 0: print(\"%d of %d...\" % (idx, num_states))\n\n # Get state corresponding to current index\n # This corresponds to one row of the P table\n state = index_to_state(idx)\n m_x, m_y, b_x, b_y, food = state\n f_x, f_y = food_coords(food)\n\n # Try each possible move from this state\n for dx in [-1,0,1]:\n for dy in [-1,0,1]:\n\n # Get new state and its index, corresponding to a column of the P table\n new_state = move(state, dx, dy)\n new_idx = state_to_index(new_state)\n \n # Taking action dx,dy in current state will produce new_state with probability 1\n # So add it to the P table (all other probabilities in this row will be zero)\n drc[(dx,dy)][\"data\"].append(1.)\n drc[(dx,dy)][\"row_ind\"].append(idx)\n drc[(dx,dy)][\"col_ind\"].append(new_idx)\n\n # Use scipy constructor to build sparse P tables\n P = {(dx,dy): sp.csr_matrix(\n (drc[(dx,dy)][\"data\"], (drc[(dx,dy)][\"row_ind\"], drc[(dx,dy)][\"col_ind\"])),\n shape=(num_states, num_states))\n for (dx,dy) in drc.keys()}\n \n return P\n\ndef build_reward(selfish=1., empathy=0.):\n \"\"\"\n Builds the reward vector of the MDP\n r[i] is the reward for state with index i\n \"\"\"\n\n # Initialize reward vector and enumerate possible states\n r = np.empty(num_states)\n for idx in range(num_states):\n\n if idx % (num_states / 100) == 0: print(\"%d of %d...\" % (idx, num_states))\n\n # Construct current state from index and all reward function on it\n state = index_to_state(idx)\n r[idx] = reward(state, selfish, empathy)\n #print(idx)\n #print(r[idx])\n return r\n\ndef value_iteration(r, P, g = 0.9, target_error=0, num_iters=None):\n \"\"\"\n MDP value iteration to \"learn\" the optimal policy for the mother.\n Conceptually this is an efficient way to run all possible simulations in parallel.\n It uses a \"discount factor\" g to balance instant and delayed rewards\n It returns a \"utility\" vector: u[k] is the utility of state with index k.\n \"Utility\" is the net long-term reward the mother can get from a given state.\n Net long-term rewards put more weight on short-term rewards according to the discount factor.\n Discount factor closer to 1 weights distant rewards more similarly to immediate rewards.\n The more \"value iterations\", the closer this algorithm gets to approximating true utility.\n It is possible to bound the error between the approximation and the truth.\n\n Input:\n r: the reward vector from build_reward\n P: the P tables from build_mdp\n g: the \"discount\" factor in (0,1)\n target_error: using the bound, try to get this close to the true utility vector\n num_iters: how many iterations to perform (None goes until target error achieved)\n Output:\n u: the utility vector \n \"\"\"\n u = np.zeros(num_states) # utility vector\n error = np.inf\n\n for i in it.count():\n\n if i == num_iters: break\n if error <= target_error: break\n\n P_u = np.array([P[a].dot(u) for a in P])\n u_new = r + g * P_u.max(axis=0)\n error = np.fabs(u_new - u).max() * (1 - g) / g\n u = u_new\n \n print(\"iter %d error = %f\"%(i,error))\n \n return u\n\ndef policy_iteration(r, P, g = 0.9):\n # Initialize thel value function\n V = np.zeros(num_states)\n policy = [0 for s in range(num_states)]\n\n is_value_changed = True\n iterations = 0\n I = identity(num_states,format = 'csr')\n print(I-P[-1,-1])\n action = [P[-1,-1],P[-1,0],P[-1,1],P[0,-1],P[0,0],P[0,-1],P[1,-1],P[1,0],P[1,1]]\n \n \n while is_value_changed:\n is_value_changed = False\n iterations += 1 \n print(\"*\")\n for s in range(num_states):\n for s1 in range(num_states):\n a= I[s,s1]\n b = P[(-1,-1)][s,s1]\n c = a -g*b\n #print(c)\n if c!=0:\n V[s] = float(r[s1])/c\n #print(V[s])\n else:\n V[s]=0\n print(s,s1)\n print(2)\n for s in range(num_states):\n q_best = V[s]\n #print \"State\", s, \"q_best\", q_best\n for s1 in range(num_states):\n print(3)\n\n for i in range(9):\n a = I[s,s1]\n b = action[i][s,s1]\n c = a -g*b\n if c!=0:\n q_sa = float(r[s1])/c\n else:\n q_sa = 0\n \n #q_sa = sum([P[s, a, s1] * (R[s, a, s1] + gamma * V[s1]) for s1 in range(N_STATES)])\n if q_sa > q_best:\n #print (\"State\", s, \": q_sa\", q_sa, \"q_best\", q_best)\n policy[s] = a\n q_best = q_sa\n is_value_changed = True\n print(iterations)\n print(\"Final policy\")\n print(policy)\n print(V)\n return V\n\ndef build_policy(P, u):\n \"\"\"\n Determines mother's final policy based on P tables and u vector.\n Mother will choose the action with highest expected utility.\n Inputs: P and u\n Returns a policy array p\n a[k,:] = [dx,dy], the optimal move to take in state with index k \n \"\"\"\n A = P.keys()\n p = np.array(list(A))[\n np.array([P[a].dot(u) for a in A]).argmax(axis=0)\n ,:]\n return p\n\nif __name__ == \"__main__\":\n\n # # test state/index mapping\n # for idx in range(num_states):\n # if idx % int(num_states/20) == 0: print(idx)\n # assert(idx == state_to_index(index_to_state(idx)))\n\n #### !!! Do this once to build P tables and save to disk !!! ###\n P = build_mdp()\n for dx,dy in P:\n sp.save_npz(\"P_%d_%d.npz\" % (dx,dy), P[dx,dy])\n\n #Load P tables from disk, after previous code has been executed once.\n P = {(dx,dy): sp.load_npz(\"P_%d_%d.npz\" % (dx,dy))\n for dx in [-1,0,1] for dy in [-1,0,1]}\n #print(P[(-1,-1)])\n #I = identity(num_states,format = 'csr')\n #print(I-P[-1,-1])\n # Build reward vector with desired parameters\n r = build_reward(selfish=0.6, empathy=0.6)\n # r = build_reward(selfish=1., empathy=-1.)\n # r = build_reward(selfish=1., empathy=1.)\n\n # Load P tables from disk, after previous code has been executed once.\n #P = {(dx,dy): sp.load_npz(\"P_%d_%d.npz\" % (dx,dy))\n # for dx in [-1,0,1] for dy in [-1,0,1]}\n\n # Build reward vector with desired parameters !!! Do this whenever changing selfish/empathy\n # r = build_reward(selfish=-.1, empathy=.9)\n # r = build_reward(selfish=1., empathy=-1.)\n # r = build_reward(selfish=1., empathy=1.)\n #r = build_reward(selfish=.6, empathy=.5)\n # np.savez(\"r.npz\", r=r)\n\n # Load the built reward vector from disk\n # r = np.load(\"r.npz\")[\"r\"]\n\n # Do value iteration to get optimal mother policy\n u = value_iteration(r, P, g = 0.95, target_error=0, num_iters=50)\n #u = policy_iteration(r, P, g = 0.9)\n p = build_policy(P, u)\n\n # Run a simulation with optimal policy to check that it works well\n # Initial state\n state = (1, 0, (0, 0), (5, 4), (False, False,True ,False))\n #state = (0, 0, (0, 0), (5, 4), (True, False, False, True))\n #state = (5, 5, (5, 5), (5, 5), (True, True, True, True))\n print(r)\n # distance = []\n # for episode in range(30):\n \n #state = index_to_state(np.random.randint(num_states)) # random initial\n\n # Run simulation\n pt.ion()\n for t in range(30): # number of time-steps\n\n # show current state\n print(t)\n pt.cla()\n plot_state(state)\n pt.show()\n pt.pause(10.)\n\n # move and update according to optimal policy\n dx, dy = p[state_to_index(state),:]\n state = move(state, dx, dy)\n\n \n # np.mean(distance)\n # np.std(distance)\n","sub_path":"CAT_MDP(food limited).py","file_name":"CAT_MDP(food limited).py","file_ext":"py","file_size_in_byte":17855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"319733120","text":"print (\"\"\"\n========================plot_best_config_vads.py========================\nPlots DREAM VAD spread per scenario for each configuration\n\nProgrammed by K. Mansoor - Mar 2016\nUpdated by J. Whiting - Dec 2019\n========================================================================\n\"\"\")\n\n# python plot_dreamout01.py objective_summary_best.csv\n\n\nimport sys, re, os, csv\nimport numpy as np\nimport time\nimport matplotlib.pyplot as plt\n\nt0=float(time.process_time())\n\n# Make sure that we have the correct number of arguments, otherwise abort\nif (len(sys.argv) != 2):\n\tprint('Usage : plot_best_config_vads.py \\n')\n\texit()\n\n# Arguments\ncsvfile=sys.argv[1]\n#csvfile='C:\\\\Users\\\\whit162\\\\OneDrive - PNNL\\\\Documents\\\\Projects\\\\DreamProject\\\\Results_20191205155836\\\\best_configuration_vads.csv'\n\nif not re.search('.csv$',csvfile.lower()):\n\tprint('\\nError - input file must be a *.csv file\\n')\n\texit()\n\n# Determine the directory where we save results\nnew_folder = os.path.join(os.path.dirname(csvfile) + '/best_config_vad_plots')\nprint(new_folder)\nif not os.path.isdir(new_folder): os.mkdir(new_folder)\nelse: print('already exists')\n\nfilepre=re.sub('.csv$','',csvfile)\nfignamepdf='%s.pdf'%filepre\n\n## Get the data ##\nnames = []\nvads = set()\nlist_of_counts = []\nwith open(csvfile) as f:\n reader = csv.reader(f)\n for row in reader:\n if 'Volume of Aquifer Degraded' in row[0]: #Header\n unit = row[0][row[0].find(\"(\")+1:row[0].find(\")\")]\n else: #Information for a configuration\n names.append(row[0]) #Creates a list of configuration names\n count = {} #Stores the scenario count per vad (not cumulative)\n for entry in row[1:]:\n if entry =='': continue\n value = float(entry)\n vads.add(value)\n if value not in count:\n count[value] = 0\n count[value] += 1\n list_of_counts.append(count)\n\nvads = sorted(vads)\nto_plot_list = []\nfor count in list_of_counts:\n counts = []\n cumulative = 0 #stores detections at earlier ttds\n for vad in vads:\n if vad in count:\n counts.append(count[vad] + cumulative)\n cumulative += count[vad]\n else:\n counts.append(cumulative)\n to_plot_list.append(counts)\n\n## Plot the data ##\ni = 0\nfor x in to_plot_list:\n print (\"Plotting Config_%d\"%(i+1))\n \n N = len(vads)\n if N>10: #Too many values won't plot, need to take intervals\n interval = round(N/10)\n x = x[round(interval/2)-1::interval]\n labels = vads[round(interval/2)-1::interval]\n ind = np.arange(N/interval) + 1 # the x locations for the groups\n else:\n labels = vads\n ind = np.arange(N) + 1 # the x locations for the groups\n \n width = 0.35 # the width of the bars\n fig, ax = plt.subplots()\n rects1 = ax.bar(ind, x, width, color='r')\n\n # add some text for labels, title and axes ticks\n ax.set_ylabel('Number of Scenarios')\n ax.set_xlabel('Volume of Aquifer Degraded (%s)'%(unit))\n ax.set_title('Config_%d - Number of Scenarios Detected by VAD'%(i+1))\n ax.set_xticks(ind)\n ax.set_xticklabels(labels)\n plt.xticks(rotation=45)\n plt.tight_layout()\n\n def autolabel(rects):\n # attach some text labels\n for rect in rects:\n height = rect.get_height()\n ax.text(rect.get_x() + rect.get_width()/2., 0.90*height,\n '%d' % int(height),\n ha='center', va='bottom')\n\n autolabel(rects1)\n \n plt.savefig(new_folder + '/' + names[i] + '.pdf')\n plt.close()\n i += 1\n\nt1=float(time.process_time())\nprint('\\n Done!! [%3ds] open %s\\n\\n\\n' % (t1-t0,fignamepdf))","sub_path":"scripts/plot_best_config_vads.py","file_name":"plot_best_config_vads.py","file_ext":"py","file_size_in_byte":3726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"61136450","text":"__author__ = 'lachesis'\nimport os, sys, subprocess\nimport h5py as h5\nfrom collections import defaultdict\nimport numpy as np\nfrom pbtools.pbh5tools.CmpH5Utils import copyAttributes\nfrom Bio import SeqIO\n\nclass FilteredRegionHandler:\n \"\"\"\n Handle the reading/manipulation/wrting of filtered region files\n (currently, as .bax.h5) mainly for creating a whitelist to run pbalign.py\n \"\"\"\n def __init__(self, fofn_filename=None):\n self.reg_dict = {} # key is movie, value is a list of (base_filename, region)\n if fofn_filename is not None:\n with open(fofn_filename) as f:\n for line in f:\n self.add_region_file(line.strip())\n\n def add_region_file(self, filename):\n # it should be .rgn.h5 but some versions of smrtpipe have the renaming error of .bax.h5\n assert filename.endswith('.rgn.h5') or filename.endswith('.bax.h5')\n base_filename = os.path.basename(filename)\n movie = base_filename[:base_filename.find('.')]\n reg = h5.File(filename, 'r')['/PulseData/Regions']\n if movie not in self.reg_dict:\n self.reg_dict[movie] = [(base_filename, reg)]\n else:\n self.reg_dict[movie].append((base_filename, reg))\n\n def write_whitelist_region_file(self, seqids, output_dir='./filtered_regions/'):\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n output_dir = os.path.abspath(output_dir)\n holes_by_movie = defaultdict(lambda: set()) # movie --> holenumber\n for seqid in seqids:\n movie, hole, s_e = seqid.split('/')\n holes_by_movie[movie].add(int(hole))\n\n fnnames = []\n baxnames = []\n\n for movie, chunks in self.reg_dict.iteritems():\n for (base_filename, regTbl) in chunks:\n a = np.in1d(regTbl[:, 0], np.array(list(holes_by_movie[movie])))\n print >> sys.stderr, \"{0} from {1}\".format(sum(a), base_filename)\n if any(a):\n reg = regTbl[a, :]\n fname = os.path.join(output_dir, base_filename[:-7]+'.rgn.h5')\n nfile = h5.File(fname, 'w')\n ndset = nfile.create_dataset('/PulseData/Regions', data = reg, maxshape = (None, None))\n copyAttributes(regTbl, ndset)\n nfile.close()\n fnnames.append(fname)\n baxnames.append(base_filename)\n return fnnames, baxnames\n\ndef write_fofn_from_whitelist(input_fofn, fnames, baxnames):\n \"\"\"\n Write to\n /filtered_regions.fofn\n /filtered_input.fofn\n\n NOTE: order in both .fofn files should be the same, so sort...\n \"\"\"\n bs = []\n for line in open(input_fofn, 'r'):\n b = os.path.basename(line.strip())\n if b in baxnames:\n bs.append(line.strip())\n bs.sort(key=lambda x: os.path.basename(x))\n with open('filtered_input.fofn', 'w') as f_input:\n f_input.writelines(\"\\n\".join(bs))\n\n fnames.sort(key=lambda x: os.path.basename(x))\n with open('filtered_regions.fofn', 'w') as f_region:\n f_region.writelines(\"\\n\".join(fnames))\n\n return f_input.name, f_region.name\n\n\ndef get_quiver_consensus(input_fofn, ref_fasta, output_dir=None, input_fasta=None, region_fofn=None):\n \"\"\"\n input_fasta --- if not None, then a whitelist filtered region is created (region_fofn must also be not None)\n ref_fasta --- reference fasta (ex: g_consensus.fa) to align to\n output_dir --- if None, automatically set to where ref_fasta is\n\n (1) Create a whitelist if necessary\n (2) Run pbalign.py to get .cmp.h5\n (3) loadPulses\n (4) sort cmp.h5\n (5) call quiver\n \"\"\"\n output_dir = os.path.dirname(ref_fasta) if output_dir is None else output_dir\n if input_fasta is not None:\n filreg = FilteredRegionHandler(region_fofn)\n ids = [r.id for r in SeqIO.parse(open(input_fasta), 'fasta')]\n fnnames, baxnames = filreg.write_whitelist_region_file(ids, os.path.join(output_dir, 'filtered_regions'))\n fofn_name, region_name = write_fofn_from_whitelist(input_fofn, fnnames, baxnames)\n else:\n fofn_name = input_fofn\n region_name = region_fofn\n\n out_fname = os.path.join(output_dir, 'out.cmp.h5')\n cmd = \"pbalign.py {i} {r} {o} --nproc 12\".format(i=fofn_name, r=ref_fasta, o=out_fname)\n if region_name is not None:\n cmd += \" --regionTable \" + region_name\n print >> sys.stderr, \"CMD:\", cmd\n subprocess.check_call(cmd, shell=True)\n\n cmd = \"loadPulses {i} {o} -bymetric -metrics QualityValue,\" \\\n \"InsertionQV,MergeQV,DeletionQV,DeletionTag,SubstitutionTag,SubstitutionQV\".format(i=fofn_name, o=out_fname)\n print >> sys.stderr, \"CMD:\", cmd\n subprocess.check_call(cmd, shell=True)\n\n cmd = \"cmph5tools.py sort --inPlace \" + out_fname\n print >> sys.stderr, \"CMD:\", cmd\n subprocess.check_call(cmd, shell=True)\n\n cmd = \"quiver -p P4-C2.AllQVsMergingByChannelModel -j8 {o} -r {r} -o {o}.quivered.fq\".format(o=out_fname, r=ref_fasta)\n print >> sys.stderr, \"CMD:\", cmd\n subprocess.check_call(cmd, shell=True)\n\n\nif __name__ == \"__main__\":\n from argparse import ArgumentParser\n parser = ArgumentParser()\n parser.add_argument(\"--input_fofn\", default='input.fofn')\n parser.add_argument(\"--ref_fasta\", required=True)\n parser.add_argument(\"--region_fofn\")\n parser.add_argument(\"--input_fasta\")\n parser.add_argument(\"--output_dir\")\n\n args = parser.parse_args()\n\n get_quiver_consensus(args.input_fofn, args.ref_fasta, args.output_dir, args.input_fasta, args.region_fofn)\n\n","sub_path":"obsolete/quiver_consensus.py","file_name":"quiver_consensus.py","file_ext":"py","file_size_in_byte":5628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"135822123","text":"from afisha_rss.parsers.base_parser import BaseParser\nimport feedparser\nfrom datetime import datetime, timezone as tz\nfrom time import mktime\nfrom django.utils import timezone\nfrom datetime import timedelta\n\nclass RssParser(BaseParser):\n\n def update_events(self):\n feed = feedparser.parse(self.source.url)\n events = []\n for event in feed.entries:\n date = datetime.fromtimestamp(mktime(event['published_parsed']))\n date = timezone.make_aware(date, timezone=tz(timedelta(0)))\n event['published'] = date\n if date > self.source.lastVisited:\n events.append(event)\n self.process_events(events)\n\n date = datetime.fromtimestamp(mktime(feed.feed['updated_parsed']))\n date = timezone.make_aware(date, timezone=tz(timedelta(0)))\n self.source.lastVisited = date\n self.source.save()\n","sub_path":"afisha_crawler/afisha_rss/parsers/rss_parser.py","file_name":"rss_parser.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"72509265","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: Wei, Shuowen\n\nhttps://leetcode.com/problems/maximum-number-of-points-with-cost\n\nhttps://leetcode.com/problems/maximum-number-of-points-with-cost/discuss/1344908/C%2B%2BJavaPython-3-DP-Explanation-with-pictures.\n\nLC931, LC1937\n\"\"\"\nclass Solution(object):\n def maxPoints(self, points):\n \"\"\"\n :type points: List[List[int]]\n :rtype: int\n \"\"\"\n # no need to compare everything\n row, col = len(points), len(points[0])\n if row == 1:\n return max(points[0])\n if col == 1:\n return sum(sum(col) for col in points)\n \n dp_table = points[:][:]\n for i in range(1, row):\n ########\n left, right = [0]*col, [0]*col\n left[0] = dp_table[i-1][0]\n right[col-1] = dp_table[i-1][col-1]\n for ll in range(1, col):\n left[ll] = max(left[ll - 1] - 1, dp_table[i-1][ll])\n for rr in range(col-2, -1, -1):\n right[rr] = max(right[rr + 1] - 1, dp_table[i-1][rr])\n #########\n for j in range(col):\n dp_table[i][j] = max(left[j], right[j]) + points[i][j]\n return max(dp_table[row-1])\n\"\"\"\n # dp, bottom up\n row, col = len(points), len(points[0])\n dp_table = points[:][:]\n for i in range(1, row):\n for c in range(col):\n res = 0 \n for j in range(col):\n res = max(res, points[i][c] + dp_table[i-1][j] - abs(c-j))\n dp_table[i][c] = res \n return max(dp_table[row-1])\n \n # dp, top down \n row, col = len(points), len(points[0])\n dp_table = {}\n def dp(points, r, c):\n if r == 0:\n dp_table[(r, c)] = points[0][c]\n return points[0][c]\n if (r, c) in dp_table:\n return dp_table[(r, c)]\n res = 0\n for j in range(col):\n res = max(res, dp(points, r-1, j) + points[r][c] - abs(j-c))\n dp_table[(r, c)] = res\n return res\n \n final_res = 0 \n for y in range(col):\n final_res = max(final_res, dp(points, row-1, y))\n print(dp_table)\n return final_res\n\"\"\"","sub_path":"Medium/LC1937.py","file_name":"LC1937.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"223432863","text":"# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n\nfrom datetime import datetime\n\nfrom odoo.tests.common import SavepointCase, new_test_user\n\n\nclass TestEventNotifications(SavepointCase):\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.event = cls.env['calendar.event'].create({\n 'name': \"Doom's day\",\n 'start': datetime(2019, 10, 25, 8, 0),\n 'stop': datetime(2019, 10, 27, 18, 0),\n }).with_context(mail_notrack=True)\n cls.user = new_test_user(cls.env, 'xav', email='em@il.com', notification_type='inbox')\n cls.partner = cls.user.partner_id\n\n def test_attendee_added(self):\n self.event.partner_ids = self.partner\n self.assertTrue(self.event.attendee_ids, \"It should have created an attendee\")\n self.assertEqual(self.event.attendee_ids.partner_id, self.partner, \"It should be linked to the partner\")\n self.assertIn(self.partner, self.event.message_follower_ids.partner_id, \"He should be follower of the event\")\n\n def test_attendee_added_create(self):\n event = self.env['calendar.event'].create({\n 'name': \"Doom's day\",\n 'start': datetime(2019, 10, 25, 8, 0),\n 'stop': datetime(2019, 10, 27, 18, 0),\n 'partner_ids': [(4, self.partner.id)],\n })\n self.assertTrue(event.attendee_ids, \"It should have created an attendee\")\n self.assertEqual(event.attendee_ids.partner_id, self.partner, \"It should be linked to the partner\")\n self.assertIn(self.partner, event.message_follower_ids.partner_id, \"He should be follower of the event\")\n\n def test_attendee_added_multi(self):\n event = self.env['calendar.event'].create({\n 'name': \"Doom's day\",\n 'start': datetime(2019, 10, 25, 8, 0),\n 'stop': datetime(2019, 10, 27, 18, 0),\n })\n events = self.event | event\n events.partner_ids = self.partner\n self.assertEqual(len(events.attendee_ids), 2, \"It should have created one attendee per event\")\n\n def test_existing_attendee_added(self):\n self.event.partner_ids = self.partner\n attendee = self.event.attendee_ids\n self.event.write({'partner_ids': [(4, self.partner.id)]}) # Add existing partner\n self.assertEqual(self.event.attendee_ids, attendee, \"It should not have created an new attendee record\")\n\n def test_attendee_add_self(self):\n self.event.with_user(self.user).partner_ids = self.partner\n self.assertTrue(self.event.attendee_ids, \"It should have created an attendee\")\n self.assertEqual(self.event.attendee_ids.partner_id, self.partner, \"It should be linked to the partner\")\n self.assertEqual(self.event.attendee_ids.state, 'accepted', \"It should be accepted for the current user\")\n\n def test_attendee_removed(self):\n partner_bis = self.env['res.partner'].create({'name': \"Xavier\"})\n self.event.partner_ids = partner_bis\n attendee = self.event.attendee_ids\n self.event.partner_ids |= self.partner\n self.event.partner_ids -= self.partner\n self.assertEqual(attendee, self.event.attendee_ids, \"It should not have re-created an attendee record\")\n self.assertNotIn(self.partner, self.event.attendee_ids.partner_id, \"It should have removed the attendee\")\n self.assertNotIn(self.partner, self.event.message_follower_ids.partner_id, \"It should have unsubscribed the partner\")\n self.assertIn(partner_bis, self.event.attendee_ids.partner_id, \"It should have left the attendee\")\n","sub_path":"addons/calendar/tests/test_attendees.py","file_name":"test_attendees.py","file_ext":"py","file_size_in_byte":3607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"307552936","text":"#!/usr/bin/env python\r\n#\r\n# parseProjectWhiteFox.py: Script parses the http URLs from ProjectWhiteFox release\r\n# http://pastebin.com/agUFkEEa\r\n\r\n__author__ = \"Vinay Kudithipudi\"\r\n\r\n#Importing modules\r\nimport re\r\nimport string\r\nimport os\r\nimport glob\r\nimport fileinput\r\nimport urllib\r\nimport uuid\r\nimport time\r\nimport random\r\n\r\n\r\n#Define Variables\r\nfileParse=\"projectwhitefox.txt\"\r\n\r\ndef find_urls(string):\r\n \"\"\" Extract all URL's from a string & return as a list \"\"\"\r\n \"\"\" Credit to http://www.noah.org/wiki/RegEx_Python \"\"\"\r\n url_list = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',string)\r\n return url_list\r\n\r\ndef convert_privatepaste_url(string):\r\n \"\"\" Convert the privatepate URL to downloadable format \"\"\"\r\n head, sep, tail = string.rpartition('/')\r\n return_url = head + '/download/' + tail\r\n return return_url\r\n\r\ndef convert_pastesite_url(string):\r\n \"\"\" Convert the pastesite URL to downloadable format \"\"\"\r\n head, sep, tail = string.rpartition('/')\r\n return_url = head + '/plain/' + tail + '.txt'\r\n return return_url\r\n\r\ndef download_file(string,url):\r\n \"\"\" Download url \"\"\"\r\n fileName = string.replace('/','_')\r\n fileName = fileName.replace(':',\"_\")\r\n urllib.urlretrieve(url, fileName)\r\n \r\n\r\ninputFile = open(fileParse)\r\nfor eachLine in inputFile:\r\n if re.search(\"http\", eachLine):\r\n parse1 = eachLine.split('-', 1)\r\n compromised = parse1[0]\r\n if (len(parse1) > 1):\r\n compromisedURLs = parse1[1]\r\n urls = find_urls(compromisedURLs)\r\n for url in urls:\r\n if 'privatepaste.com' in url:\r\n fixed_url = convert_privatepaste_url(url)\r\n print (compromised + \": \" + fixed_url)\r\n download_file(fixed_url, fixed_url)\r\n","sub_path":"parseProjectWhiteFox.py","file_name":"parseProjectWhiteFox.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"627339943","text":"### Note:\n# This file was used to organize historical NASDAQ data from vaious stocks\n# and convert them into a csv file\n# Because of the large number of raw data files, raw data are not included in \n# the zip package\n\nimport pandas as pd # load \"numpy\"\nimport numpy as np\n\n#NASDAQ data\nimport glob # 'glob' searches for files\n# '*.csv' selects files ending in '.csv'\n\n\nfilelist = glob.glob('*.csv') \n# Can concatenate the dataframes into one large dataframe\n# Concatenate df1 and df2 by rows\ndfnasd = pd.DataFrame()\nfor b in filelist:\n newdf = pd.read_csv(b)\n str = b\n i= str.find(\".\")\n stockname=str[0:i]\n newdf['Stockname']=[stockname]*len(newdf) #add the stock names\n dfnasd = pd.concat([dfnasd,newdf])\ndfnasd\n\ndfnasd.to_csv('nasdaq.csv')\n\n","sub_path":"NASDAQdf.py","file_name":"NASDAQdf.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"357545311","text":"#!/usr/bin/env python3\n\nimport sys\n\nfrom broker.utils import _colorize_traceback\n\nif __name__ == \"__main__\":\n import broker.eblocbroker.Contract as Contract\n\n Ebb = Contract.eblocbroker\n\n if len(sys.argv) == 2:\n tx = str(sys.argv[1])\n else:\n tx = \"0xfa65c8516e81f972d1bdf801e0524aad1b2a9c54bb8e746613fb7316034f3e3e\"\n\n try:\n print(Ebb.get_transaction_receipt(tx))\n # print(getTransactionReceipt(tx)['blockNumber'])\n except:\n _colorize_traceback()\n sys.exit(1)\n","sub_path":"broker/eblocbroker/get_transaction_receipt.py","file_name":"get_transaction_receipt.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"76211652","text":"\n#!/usr/bin/env python3\nimport tkinter as tk\nfrom tkinter import filedialog\nfrom tkinter.filedialog import askopenfilename\nimport math\nfrom math import *\nimport matplotlib.pyplot as plt\nfrom cooperative_game import * \nimport pickle\nimport string\n\ndef powerset(s):\n x = len(s)\n masks = [1 << i for i in range(x)]\n for i in range(1 << x):\n yield [ss for mask, ss in zip(masks, s) if i & mask]\n\n\nentries={}\nparty_names={}\npolls={}\n\nroot = tk.Tk()\n\nFILENAME=askopenfilename()\nentries = pickle.load( open( FILENAME, \"rb\" ) )\nroot.destroy()\n\ns=0\nparty_num=0\nfor k in range(0, 15):\n try:\n polls[k]=float(entries[k+1,3])\n s=s+1\n except ValueError:\n party_num=s\n\n\n# Initialize parties and coalitions (labelled by letters)\n\nlabels=['']*party_num\ncolors=['']*party_num\nexcluded=['']*party_num\n\nparties = list(string.ascii_uppercase)[0:party_num]\n\nfor k in range(0, party_num):\n party_names[k]=str(entries[k+1,0])\n labels[k]=str(entries[k+1,1])\n colors[k]=str(entries[k+1,2])\n excluded[k]=list(str(entries[k+1,4]))\n\n\nlabel = dict(zip(parties,labels)) \ncolor = dict(zip(parties,colors))\ncoalitions = powerset(parties)\n\n\n# Introduce campaign commitments\n\nfr={}\nfriends={}\nfor k in range(0,party_num):\n fr[k]=list(set(parties) - set(excluded[k]))\n\nfor k in range(0,party_num):\n friends[parties[k]]=fr[k]\n\n# Computing seats, Shapley values and all winning coalitions\n\nP=0\nfor i in range(len(polls)):\n P += polls[i]\n\n\n# Initialize proportions of seats (precise and rounded) \n\ns ={} \nsround = {} \npl = {} \ni = 0 \nfor p in parties:\n pl[p]=polls[i]\n s[p] = polls[i]/P\n sround[p]= round(float(s[p]*100),1)\n i+=1\n\nworth = {} \nfor i in tuple(coalitions):\n sumsp=0\n for r in tuple(i):\n j=set(i).intersection(set(friends[r]))\n if j==set(i):\n sumsp = sumsp + s[r]\n worth[tuple(i)] = ( copysign(1,(sumsp - 0.5)) + 1)/2\n if ( copysign(1,(sumsp - 0.5)) + 1)==1:\n worth[tuple(i)] = 0\n\n\nprint(worth)\nwirth = {}\nprint(tuple(powerset(i)))\nfor i in tuple(coalitions):\n wirth[tuple(i)]=0\n for r in tuple(powerset(i)):\n if worth[tuple(r)]==1:\n wirth[tuple(i)]=1\nprint(wirth)\n\nletter_game = CooperativeGame(worth)\nsh = letter_game.shapley_value()\nprint( \"{:<10} {:<10} {:<10} {:<10} {:<10}\".format('Label', 'Party', 'Votes (%)', 'Seats (%)', 'Strength') )\nfor k in parties:\n lb = label[k]\n num = sround[k]\n v = max(sh[k],0)\n print( \"{:<10} {:<10} {:<10} {:<10} {:<10}\".format(k, lb, round(float(pl[k]),2), num, v) ) \n\nletter_function = {}\nfor k in worth.keys(): # Find all winning coalitions\n if worth[k] != 0:\n letter_function[k]=worth[k]\n\n\n# Find all minimal winning coalitions\n\nnon_minimal_winning={}\nfor k in letter_function.keys():\n for j in letter_function.keys():\n if (j!= k) and (set(k).intersection(set(j)) == set(k)): \n non_minimal_winning[j]=letter_function[j]\n\nminimal_winning={}\nfor k in letter_function.keys():\n if not(k in non_minimal_winning.keys()):\n minimal_winning[k]=letter_function[k]\n\n\n# Find all stable coalitions\n\nplt.figure(0) \nchi = {}\npower = {}\nmaxchi = 0\nfor k in minimal_winning.keys():\n S = 0\n for j in k:\n S += max(sh[j],0)\n chi[k] = minimal_winning[k]/S\n if chi[k] > maxchi:\n maxchi = chi[k]\n u=''\n b = 0\n for j in k:\n po=''\n pc=''\n power[j] = max(0,sh[j])*chi[k]\n if power[j]==0:\n po='('\n pc=')'\n u = u + po + label[j].split('/')[0] + pc + ' ' \n for i in k:\n plt.bar(u, power[i], bottom = b, color = color[i])\n b = b +power[i]\n plt.bar(u, 0.03, bottom=chi[k]/maxchi*(0.9), color='white', width=.2) \nplt.xticks(rotation=-20, fontsize=8, horizontalalignment='left')\nplt.show()\n\nprint('Minimal winning coalitions and Power distribution') \nprint('( Power = Strength x Stability ):') \n\nS = 0\nfor j in parties:\n S += max(sh[j],0)\n\nplt.figure(1) \nfor i in parties:\n plt.bar(label[i], s[i], color = color[i], width=0.3, align='center')\n plt.bar(label[i], 0.003, bottom = max(0,sh[i])/S, color = 'red', width=0.6, align='center') \nplt.xticks(rotation=-20, fontsize=8, horizontalalignment='left')\nplt.show()\n\n","sub_path":"goldenapp.py","file_name":"goldenapp.py","file_ext":"py","file_size_in_byte":4419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"248713511","text":"#coding=utf8\n'''\nCreated on 2019年5月7日\n\n@author: 82114\n'''\nimport torch\nfrom models import greedysearchdecoder as gs\n\nUSE_CUDA = torch.cuda.is_available()\ndevice = torch.device(\"cuda\" if USE_CUDA else \"cpu\")\n\nMAX_LENGTH = 10 # 句子最大长度是10个词(包括EOS等特殊词)\n#MIN_COUNT = 3 # 阈值为3\n\nclass Evaluation(object):\n def __init__(self,dp,encoder, decoder):\n self.dp = dp\n self.voc = dp.voc\n \n # 进入eval模式,从而去掉dropout。 \n print(\"Starting Evaluating!\")\n encoder.eval()\n decoder.eval()\n \n # 构造searcher对象 \n self.searcher = gs.GreedySearchDecoder(encoder, decoder)\n \n # 测试\n self.evaluateInput()\n \n \n def evaluate(self, sentence, max_length=MAX_LENGTH):\n \n ### 把输入的一个batch句子变成id\n indexes_batch = [self.dp.indexesFromSentence(self.voc, sentence)]\n # 创建lengths tensor\n lengths = torch.tensor([len(indexes) for indexes in indexes_batch])\n # 转置 \n input_batch = torch.LongTensor(indexes_batch).transpose(0, 1)\n # 放到合适的设备上(比如GPU)\n input_batch = input_batch.to(device)\n lengths = lengths.to(device)\n # 用searcher解码\n tokens, scores = self.searcher(input_batch, lengths, max_length)\n # ID变成词。\n decoded_words = [self.voc.index2word[token.item()] for token in tokens]\n return decoded_words\n \n \n def evaluateInput(self):\n input_sentence = ''\n while(1):\n try:\n # 得到用户终端的输入\n input_sentence = input('> ')\n \n # 是否退出\n if input_sentence == 'q' or input_sentence == 'quit': break\n \n # 句子归一化\n input_sentence = self.dp.normalizeString(input_sentence)\n \n # 生成响应Evaluate sentence\n output_words = self.evaluate(input_sentence)\n \n # 去掉EOS后面的内容\n words = []\n for word in output_words:\n if word == 'EOS':\n break\n elif word != 'PAD':\n words.append(word)\n print('Bot:', ' '.join(words))\n \n except KeyError:\n print(\"Error: Encountered unknown word.\")\n \n ","sub_path":"evaluation/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"651870007","text":"################################################################################\n# Aaron Penne \n# 2018-08-28\n# https://github.com/aaronpenne\n################################################################################\n\nimport math\nimport sys\n\n# Define globals here\nrand_seed = 1138\nframe_rate = 1\nw = 800 # width\nh = 800 # height\nborder_pad = 60\ncount = 0\n\n\n\ndef setup():\n # Sets size of canvas in pixels (must be first line)\n size(w, h) # (width, height)\n \n # Sets resolution dynamically (affects resolution of saved image)\n pixelDensity(displayDensity()) # 1 for low, 2 for high\n \n # Sets color space to Hue Saturation Brightness with max values of HSB respectively\n colorMode(HSB, 360, 100, 100, 100)\n \n # Set the number of frames per second to display\n frameRate(frame_rate)\n \n # Set (x, y) for circles to center\n ellipseMode(CENTER)\n \n background(0, 0, 97)\n \n # Stops draw() from running in an infinite loop (should be last line)\n randomSeed(rand_seed)\n noLoop()\n\n\n\ndef draw():\n\n background(0, 0, 97)\n \n # global count\n # print(count)\n # if count > 30:\n # sys.exit(0)\n # count += 1\n\n # radius_list = [50, 100, 150, 200, 250, 300]\n # spread_list = [3, 5, 10, 15, 20, 30, 40, 50, 60]\n # number_list = [1000, 5000, 10000, 50000, 100000]\n # type_list = [0, 1]\n\n\n #num_circles = int(random(3,20))\n # num_circles = 1\n # for i in range(num_circles):\n # radius = random_list_value(radius_list)\n # spread = random_list_value(spread_list)\n # number = random_list_value(number_list)\n \n # radius = int(random(20, 300))\n # spread = int(random(3, 50))\n # type = random_list_value(type_list)\n \n # radius = 200\n # spread = 20\n # type = 1\n \n\n # if type == 0:\n # type = 'dots'\n # number = int(random(50000, 100000))\n # circle_dots(hsba=(0, 0, 0, 5), number=number, radius=(radius, radius), spread=[spread])\n # elif type == 1:\n # type = 'lines'\n # # number = int(random(100, 5000))\n # # center = int(random(0, 20))\n # number = 100000\n # center = 0\n # circle_lines(hsba=(0, 0, 0, 5), number=number, radius=(radius, radius), spread=[spread], center_offset=center)\n \n # print('num: {}, type: {}, radius: {}, spread: {}, number: {}'.format(num_circles, type, radius, spread, number))\n # fill(color(0, 0, 0, 100))\n # ellipse(w/2, h/2, 2*radius, 2*radius)\n \n # fill(color(0, 0, 100, 100))\n # ellipse(w/2, h/2, radius, radius)\n \n # noFill()\n # ellipse(w/2, h/2, 160, 160)\n # ellipse(w/2, h/2, 240, 240)\n\n\n # Dot circles (looks like spraypaint)\n # for spread in [5, 7, 9, 11, 13, 14, 15, 16, 17, 18, 19, 20]:\n # circle_dots(hsba=(0, 0, 0, 5), number=100000, spread=spread, stroke_weight=0.7)\n \n #circle_lines(hsba=(0, 0, 0, 5), center=(w/2,h/2), number=1000, radius=(150, 150), spread=20, stroke_weight=0.5)\n #circle_lines(hsba=(0, 0, 0, 5), center=(w/2,h/2), number=3000, radius=(400, 400), spread=50, stroke_weight=0.5)\n \n # Dot circles (looks like spraypaint)\n # spread = [5, 7, 9, 11, 13, 14, 15, 16, 17, 18, 19, 20]\n # spread = [10]\n # circle_dots(hsba=(0, 0, 0, 5), number=1000000, radius=(160, 160), spread=spread, stroke_weight=0.7)\n # circle_dots(hsba=(0, 0, 0, 5), number=1000000, radius=(240, 240), spread=spread, stroke_weight=0.7)\n #circle_dots(hsba=(0, 0, 0, 5), number=100000, radius=(300, 300), spread=spread, stroke_weight=0.7)\n \n # noStroke()\n # fill(g.backgroundColor)\n # ellipse(w/2, h/2, 230, 230)\n \n \n # spread = [20]\n # circle_lines(hsba=(0, 0, 0, 5), number=5000, radius=(200, 200), spread=spread, stroke_weight=0.7)\n \n #border()\n filename = create_filename('test')\n saveFrame('output/blur_circles_######.png')\n #print('concentric_{:02}_{:02}_{:01}.png'.format(num_circles, num_cols, int(xy_noise*10)))\n\ndef random_list_value(val_list):\n index = int(random(0, len(val_list)))\n value = val_list[index]\n return value\n \n \ndef circle_dots(hsba=(0, 50, 50, 50), center=(w/2,h/2), number=100, radius=(200,200), spread=[10], stroke_weight=0.7):\n for s in spread:\n for i in range(number):\n r_offset = randomGaussian()*s\n x = center[0] + (radius[0] + r_offset) * cos(TWO_PI * i / number) \n y = center[1] + (radius[1] + r_offset) * sin(TWO_PI * i / number)\n strokeWeight(stroke_weight)\n stroke(color(*hsba))\n point(x, y)\n \ndef circle_lines(hsba=(0, 50, 50, 50), center=(w/2,h/2), number=100, radius=(200, 200), spread=[10], stroke_weight=0.7, center_offset=10):\n for i in range(number):\n r_offset = randomGaussian()*spread[0]\n d_x = 2*radius[0] + r_offset\n d_y = 2*radius[1] + r_offset\n noFill()\n strokeWeight(stroke_weight)\n stroke(color(*hsba))\n ellipse(center[0]+randomGaussian()*center_offset, center[1]+randomGaussian()*center_offset, d_x, d_y)\n \ndef border():\n noStroke()\n fill(color(0, 0, 0))\n #fill(g.backgroundColor)\n rect(0, 0, width, border_pad) # Top\n rect(0, 0, border_pad, height) # Left\n rect(0, height - border_pad, width, border_pad) # Bottom\n rect(width - border_pad, 0, border_pad, height) # Right\n \ndef create_filename(word, num_list=[]):\n filename = word\n for number in num_list:\n filename = filename + '_{:04}'.format(int(number))\n filename = filename + '.png'\n return filename\n \ndef annotate(num_circles, num_cols, xy_noise):\n stroke(0)\n fill(0)\n textFont(createFont('Courier',100))\n textAlign(LEFT, TOP)\n textSize(height*0.013)\n text('concentric_{:02}_{:02}_{:01}.png\\nEmulating @paulrickards'.format(num_circles, num_cols, int(xy_noise*10)), width*pad_pct, height - (height*pad_pct*0.9))\n textAlign(RIGHT, TOP)\n text('Aaron Penne', width - width*pad_pct, height - (height*pad_pct*0.9))\n \n \n\n\n\n \n","sub_path":"blur_circles/blur_circles.pyde","file_name":"blur_circles.pyde","file_ext":"pyde","file_size_in_byte":6125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"313236572","text":"# coding: utf8\n\n__author__ = 'stroum'\n\n# Copyright (c) 2016 Alexander Rizaev\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n\nimport json\nimport traceback\nimport logging\n\nimport requests\nimport gevent\n\nfrom .api import API\nfrom .messages import Messages, Flags, Message\nfrom .attachments import Attachment, Types\n\n\nclass VK:\n handlers = {}\n CHAT_IDS = int(2e9)\n\n def __init__(self, bot_id, token, cache_cls=None):\n self.api = API(bot_id=bot_id, token=token)\n if cache_cls is not None:\n self.cache_cls = cache_cls\n else:\n self.cache_cls = False\n self.messages = Messages(self)\n\n def add_handler(self, on, func):\n self.handlers[on] = func\n return\n\n def get_longpoll_server(self):\n j = self.api.messages.getLongPollServer({\n \"use_ssl\": 1,\n \"lp_version\": 2\n })\n o = j[\"response\"]\n return VK_LongPoll(o[\"ts\"], o[\"server\"], o[\"key\"])\n\n def _parse_attachments(self, update):\n a = []\n for i, j in update.items():\n if \"attach\" in i:\n try:\n for k in range(0, 10):\n if \"attach{}_type\".format(k) in update:\n if \"attach{}_product_id\".format(k) in update: # sticker\n sticker_id = update[\"attach{}\".format(k)]\n a.append(Attachment(type='sticker', owner_id=0, media_id=sticker_id))\n continue\n owner_id, item_id = update[\"attach{}\".format(k)].split('_')\n at_type = update[\"attach{}_type\".format(k)]\n a.append(Attachment(type=at_type, owner_id=owner_id, media_id=item_id))\n except KeyError:\n return []\n return a\n\n def _parse_forwards(self, update):\n fwd = []\n if \"fwd\" in update:\n fwd.append(update[\"fwd\"])\n return fwd\n\n def _exec_task(self, i, j):\n updates = j[\"updates\"][i]\n type = updates[0]\n\n logging.debug(\"Execute task id: {}, Type {}\".format(i, type))\n\n \"\"\"\n 0,$message_id,0 -- удаление сообщения с указанным local_id\n 1,$message_id,$flags -- замена флагов сообщения (FLAGS:=$flags)\n 2,$message_id,$mask[,$user_id] -- установка флагов сообщения (FLAGS|=$mask)\n 3,$message_id,$mask[,$user_id] -- сброс флагов сообщения (FLAGS&=~$mask)\n 4,$message_id,$flags,$from_id,$timestamp,$text,$attachments -- добавление нового сообщения\n 5,$message_id(integer),$mask(integer),$peer_id(integer),$timestamp(integer),$new_text(string),[$attachments](array) -- Редактирование сообщения.\n 8,-$user_id,0 -- друг $user_id стал онлайн\n 9,-$user_id,$flags -- друг $user_id стал оффлайн ($flags равен 0, если пользователь покинул сайт (например, нажал выход) и 1, если оффлайн по таймауту (например, статус away))\n\n 51,$chat_id,$self -- один из параметров (состав, тема) беседы $chat_id были изменены. $self - были ли изменения вызываны самим пользователем\n 61,$user_id,$flags -- пользователь $user_id начал набирать текст в диалоге. событие должно приходить раз в ~5 секунд при постоянном наборе текста. $flags = 1\n 62,$user_id,$chat_id -- пользователь $user_id начал набирать текст в беседе $chat_id.\n 70,$user_id,$call_id -- пользователь $user_id совершил звонок имеющий идентификатор $call_id, дополнительную информацию о звонке можно получить используя метод voip.getCallInfo.\n 80,$count,0 — новый счетчик непрочитанных в левом меню стал равен $count.\n 114,{ $peerId, $sound, $disabled_until } — изменились настройки оповещений, где peerId — $peer_id чата/собеседника, sound — 1 || 0, включены/выключены звуковые оповещения, disabled_until — выключение оповещений на необходимый срок (-1: навсегда, 0: включены, other: timestamp, когда нужно включить).\n\n \"\"\"\n\n if \"on_typing\" in self.handlers and type == 5:\n msg_id = int(updates[1])\n mask = int(updates[2])\n peer_id = int(updates[3])\n timestamp = int(updates[4])\n new_text = updates[5]\n\n try:\n _attachments = self._parse_attachments(updates[6])\n except KeyError:\n _attachments = []\n\n self.handlers[\"on_message_edit\"](msg_id, mask, peer_id, timestamp, new_text, _attachments)\n\n if \"on_typing\" in self.handlers:\n if type == 61:\n # user_id, flags\n self.handlers[\"on_typing\"](user_id=updates[1], chat=0, flags=updates[2])\n if type == 62:\n # user_id, chat_id\n self.handlers[\"on_typing\"](user_id=updates[1], chat=1, chat_id=updates[2])\n\n if \"on_message\" in self.handlers and type == 4:\n msg_id = int(updates[1])\n flags = int(updates[2])\n from_id = int(updates[3])\n timestamp = int(updates[4])\n text = updates[5]\n if len(text) > 0:\n text = text.replace(\"
    \", \"\\n\")\n\n try:\n from_uid = int(updates[6][\"from\"])\n except KeyError:\n from_uid = from_id\n\n a = self._parse_attachments(update=updates[6])\n fwd = self._parse_forwards(update=updates[6])\n\n self.handlers[\"on_message\"](Message(msg_id=msg_id, flags=flags, from_id=from_id,\n ts=timestamp, text=text, from_uid=from_uid,\n attachments=a, forwarded=fwd))\n\n def _listen(self):\n server = self.get_longpoll_server()\n while True:\n r = requests.post(\"https://{}?act=a_check&key={}&ts={}&wait={}&mode=2&version=2\".format(\n server.server, server.key, server.ts, 25\n ))\n try:\n j = json.loads(r.text)\n logging.debug(j)\n\n if \"ts\" not in j:\n server = self.get_longpoll_server()\n continue\n\n if \"failed\" in j:\n if j[\"failed\"] == 1:\n server.ts = j[\"ts\"]\n else:\n server = self.get_longpoll_server()\n continue\n\n server.ts = j[\"ts\"]\n if len(j[\"updates\"]) == 0:\n continue\n\n threads = [gevent.spawn(self._exec_task, i, j) for i in range(len(j[\"updates\"]))]\n gevent.joinall(threads)\n except Exception as e:\n print(traceback.format_exc())\n\n def listen_longpoll(self):\n th = gevent.Greenlet(run=self._listen)\n th.start()\n th.join()\n\n\nclass VK_LongPoll:\n def __init__(self, ts, server, key):\n self.ts = ts\n self.server = server\n self.key = key\n","sub_path":"vk_lplib/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"234749066","text":"from django.core.management.base import BaseCommand\n\nimport json\nimport logging\nimport requests\nimport zipfile\nfrom os import path\n\nfrom data_import import _paths, _query\n\n\nclass Command(BaseCommand):\n help = 'Downloads the MtG JSON data file'\n\n def handle(self, *args, **options):\n\n if path.isfile(_paths.json_data_path):\n overwrite = _query.query_yes_no(\n '{0} already exists, overwrite?'.format(_paths.json_zip_path))\n\n if not overwrite:\n logging.info('The file {0} wasn''t overwritten'\n .format(_paths.json_zip_path))\n return\n\n logging.info('Downloading json file from {0}'\n .format(_paths.json_zip_download_url))\n stream = requests.get(_paths.json_zip_download_url)\n\n logging.info('Writing json data to file {0}'\n .format(_paths.json_zip_path))\n with open(_paths.json_zip_path, 'wb') as output:\n output.write(stream.content)\n\n json_zip_file = zipfile.ZipFile(_paths.json_zip_path)\n json_zip_file.extractall(_paths.data_folder)\n\n f = open(_paths.json_data_path, 'r', encoding=\"utf8\")\n json_data = json.load(f, encoding='UTF-8')\n f.close()\n\n pretty_file = open(_paths.pretty_json_path, 'w', encoding='utf8')\n pretty_file.write(json.dumps(\n json_data,\n sort_keys=True,\n indent=2,\n separators=(',', ': ')))\n\n pretty_file.close()\n","sub_path":"sylvan_library/data_import/management/commands/fetch_data.py","file_name":"fetch_data.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"461277619","text":"from django.contrib.auth.models import AbstractUser\nfrom django.db import models\nfrom collab.models.project import Project\n\n\nclass CustomUser(AbstractUser):\n # add additional fields in here\n nickname = models.CharField('nickname', max_length=15, blank=True)\n\n def __str__(self):\n return '%s' % (self.username)\n\n def project_right(self, project):\n \"\"\"\n Return the User project rights\n LEVEL = (\n ('0', 'Utilisateur anonyme'),\n ('1', 'Utilisateur connecté'),\n ('2', 'Contributeur'),\n ('3', 'Modérateur'),\n ('4', 'Administrateur'),\n )\n \"\"\"\n user_right = {'proj_creation': False,\n 'proj_modification': False,\n 'proj_consultation': False,\n 'feat_archive': False,\n 'feat_creation': False,\n 'feat_modification': False,\n 'feat_consultation': False,\n 'user_admin': False,\n 'model_creation': False}\n # modification if admin or super admin\n try:\n if self.is_superuser:\n user_right = {'proj_creation': True,\n 'proj_modification': True,\n 'proj_consultation': True,\n 'feat_archive': True,\n 'feat_creation': True,\n 'feat_modification': True,\n 'feat_consultation': True,\n 'user_admin': True,\n 'model_creation': True}\n else:\n try:\n autorisation = Autorisation.objects.get(user=self,\n project=project)\n level = int(autorisation.level)\n except Exception as e:\n # no autorisation on this project but the user is connected\n level = 1\n # Projet\n # if project and feature are visible\n # right to vizualize features and comments\n if level >= int(project.visi_feature) or \\\n int(project.visi_feature) < 2:\n user_right['proj_consultation'] = True\n user_right['feat_consultation'] = True\n # right to modify project fields and administrate users and add new type of feature\n if level >= 4:\n user_right['proj_modification'] = True\n user_right['user_admin'] = True\n user_right['model_creation'] = True\n # right to archive features\n if level >= int(project.visi_archive)or \\\n int(project.visi_archive) < 2:\n user_right['feat_archive'] = True\n # right to modify feature\n if level >= 3:\n user_right['feat_modification'] = True\n # right to create a feature or a comment\n if level >= 2:\n user_right['feat_creation'] = True\n\n except Exception as e:\n # no autorisation\n pass\n\n return user_right\n\n\nclass Autorisation(models.Model):\n LEVEL = (\n # ('0', 'Utilisateur anonyme'),\n ('1', 'Utilisateur connecté'),\n ('2', \"Contributeur\"),\n ('3', 'Modérateur'),\n ('4', \"Administrateur\"),\n )\n level = models.CharField(\"Niveau d'autorisation\",\n choices=LEVEL,\n max_length=1)\n user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)\n project = models.ForeignKey(Project, on_delete=models.CASCADE)\n creation_date = models.DateTimeField(\"Date de création de l'abonnement\",\n auto_now_add=True)\n modification_date = models.DateTimeField(\"Date de modification de l'abonnement\",\n auto_now=True)\n\n class Meta:\n # un role par projet\n unique_together = (\n ('user', 'project'),\n )\n","sub_path":"collab/models/customuser.py","file_name":"customuser.py","file_ext":"py","file_size_in_byte":4229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"202135195","text":"# -*- encoding: utf-8 -*-\n###########################################################################\n# Module Writen to OpenERP, Open Source Management Solution\n#\n# Copyright (c) 2010 Vauxoo - http://www.vauxoo.com/\n# All Rights Reserved.\n# info Vauxoo (info@vauxoo.com)\n############################################################################\n# Coded by: Luis Torres (luis_t@vauxoo.com)\n############################################################################\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\nfrom openerp.osv import osv, fields\nfrom lxml import etree\n\nclass account_move_line(osv.Model):\n _inherit = 'account.move.line'\n \n _columns = {\n 'amount_base' : fields.float('Amount Base', help='Amount base '\\\n 'without amount tax'),\n 'tax_id_secondary' : fields.many2one('account.tax', 'Tax Secondary',\n help='Tax used for this move'),\n }\naccount_move_line()\n\nclass account_invoice_tax(osv.Model):\n _inherit = \"account.invoice.tax\"\n \n def move_line_get(self, cr, uid, invoice_id, context=None):\n res = []\n super(account_invoice_tax, self).move_line_get(cr, uid, invoice_id)\n tax_invoice_ids = self.search(cr, uid, [\n ('invoice_id', '=', invoice_id)], context=context)\n for t in self.browse(cr, uid, tax_invoice_ids, context=context):\n if not t.amount and not t.tax_code_id and not t.tax_amount:\n continue\n res.append({\n 'type' : 'tax',\n 'name' : t.name,\n 'price_unit' : t.amount,\n 'quantity' : 1,\n 'price' : t.amount or 0.0,\n 'account_id' : t.account_id.id or False,\n 'tax_code_id' : t.tax_code_id.id or False,\n 'tax_amount' : t.tax_amount or False,\n 'amount_base' : t.base_amount or 0.0,\n 'tax_id_secondary' : t.tax_id.id or False,\n })\n return res\n \naccount_invoice_tax()\n\nclass account_invoice(osv.Model):\n _inherit = 'account.invoice'\n \n def line_get_convert(self, cr, uid, x, part, date, context=None):\n res = super(account_invoice, self).line_get_convert(cr, uid, x, part,\\\n date, context=context)\n res.update({\n 'amount_base': x.get('amount_base', False),\n 'tax_id_secondary': x.get('tax_id_secondary', False),\n })\n return res\n \naccount_invoice()","sub_path":"esc_account_move_line_base_tax/model/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":3191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"431430279","text":"#exemplo_3\r\n#Solicita um número ao usuário e mostra os valores de sua\r\n#tabuada.\r\n#import os \r\nwhile True:\r\n print(\"** Programa Calcula Tabuada **\")\r\n tabuada = 1\r\n num = int(input(\"digite um numero inteiro para calcular sua tabuada: \"))\r\n while tabuada <=10 :\r\n #condição a - mostrar os valores da multiplicação\r\n print(tabuada, \" * \", num, \" = \", num*tabuada)\r\n # condição b - Altere o valor de tabuada, acrescentando mais 1\r\n tabuada += 1 #tabuada = tabuada +1\r\n\r\n #fora do while tabuada\r\n ver = input(\"Deseja sair (s/n): \")\r\n if ver == 's' or ver == 'S':\r\n break;\r\n print(\" \\n \\n\")\r\n \r\n#fora do while True \r\nprint(\"Terminou !!!\")\r\n","sub_path":"aula 08/exemplo_3.py","file_name":"exemplo_3.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"431117138","text":"import tensorflow as tf\nfrom tensorflow.python import keras\nfrom tensorflow.python.keras.layers import Dense, Concatenate, Reshape, Activation\nfrom tensorflow.python.keras.initializers import RandomUniform\n\nfrom .actor_networks import dense_block\n\n\nclass CriticNetwork:\n\n def __init__(self, state_shape, action_size,\n hiddens=[256, 128, 64, 32],\n activations=[\"relu\", \"relu\", \"relu\", \"tanh\"],\n action_insert_block=0, num_atoms=1,\n v=(-10., 10.),\n layer_norm=False, noisy_layer=False,\n output_activation=None, scope=None):\n\n self.state_shape = state_shape\n self.action_size = action_size\n self.hiddens = hiddens\n self.activations = activations\n self.act_insert_block = action_insert_block\n self.num_atoms = num_atoms\n self.v = v\n self.layer_norm = layer_norm\n self.noisy_layer = noisy_layer\n self.out_activation = output_activation\n self.scope = scope or \"CriticNetwork\"\n self.model = self.build_model()\n\n def build_model(self):\n input_state = keras.layers.Input(\n shape=self.state_shape, name=\"state_input\")\n if self.act_insert_block == -1:\n model_inputs = [input_state]\n else:\n input_action = keras.layers.Input(\n shape=(self.action_size, ), name=\"action_input\")\n model_inputs = [input_state, input_action]\n\n input_size = self.get_input_size(self.state_shape)\n out = Reshape((input_size, ))(input_state)\n with tf.variable_scope(self.scope):\n for i in range(len(self.hiddens)):\n if (i == self.act_insert_block):\n out = Concatenate(axis=1)([out, input_action])\n out = dense_block(\n out, self.hiddens[i], self.activations[i],\n self.layer_norm, self.noisy_layer)\n out = Dense(\n self.num_atoms, self.out_activation,\n kernel_initializer=RandomUniform(-3e-3, 3e-3),\n bias_initializer=RandomUniform(-3e-3, 3e-3))(out)\n model = keras.models.Model(inputs=model_inputs, outputs=out)\n return model\n\n def get_input_size(self, shape):\n if len(shape) == 1:\n return shape[0]\n elif len(shape) == 2:\n return shape[0] * shape[1]\n\n def __call__(self, inputs):\n if self.act_insert_block == -1:\n state_input = inputs[0]\n model_input = state_input\n else:\n state_input = inputs[0][0]\n action_input = inputs[1]\n model_input = [state_input, action_input]\n return self.model(model_input)\n\n def variables(self):\n return self.model.trainable_weights\n\n def copy(self, scope=None):\n \"\"\"copy network architecture\"\"\"\n scope = scope or self.scope + \"_copy\"\n with tf.variable_scope(scope):\n return CriticNetwork(\n state_shape=self.state_shape,\n action_size=self.action_size,\n hiddens=self.hiddens,\n activations=self.activations,\n action_insert_block=self.act_insert_block,\n num_atoms=self.num_atoms,\n v=self.v,\n layer_norm=self.layer_norm,\n noisy_layer=self.noisy_layer,\n output_activation=self.out_activation,\n scope=scope)\n\n def get_info(self):\n info = {}\n info[\"architecture\"] = \"standard\"\n info[\"hiddens\"] = self.hiddens\n info[\"activations\"] = self.activations\n info[\"layer_norm\"] = self.layer_norm\n info[\"noisy_layer\"] = self.noisy_layer\n info[\"output_activation\"] = self.out_activation\n info[\"action_insert_block\"] = self.act_insert_block\n info[\"num_atoms\"] = self.num_atoms\n return info\n","sub_path":"rl_server/tensorflow/networks/critic_networks.py","file_name":"critic_networks.py","file_ext":"py","file_size_in_byte":3920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"389180088","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport json\n\nfrom flask.ext import restplus\n\nfrom . import TestCase\n\n\nclass ReqParseTestCase(TestCase):\n def setUp(self):\n super(ReqParseTestCase, self).setUp()\n self.api = restplus.Api(self.app)\n self.parser = self.api.parser()\n\n def post(self, url, data, status=200):\n headers = {\n 'Content-Type': 'application/json'\n }\n\n with self.app.test_client() as client:\n response = client.post(url, data=json.dumps(data), headers=headers)\n self.assertEquals(response.status_code, status)\n return json.loads(response.data.decode('utf8'))\n\n def test_parse_model(self):\n fields = self.api.model('Todo', {\n 'task': restplus.fields.String(required=True)\n })\n\n parser = self.parser\n parser.add_argument('todo', type=fields, required=True)\n\n @self.api.route('/reqparse', endpoint='reqparse')\n class TestApi(restplus.Resource):\n def post(self):\n args = parser.parse_args()\n return args['todo']\n\n data = self.post('/reqparse', {'todo': {'task': 'aaa'}})\n self.assertEqual(data, {'task': 'aaa'})\n\n def test_copy(self):\n parser = self.parser\n cloned = parser.copy()\n","sub_path":"tests/test_reqparse.py","file_name":"test_reqparse.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"37078652","text":"#!/usr/bin/env python\n# encoding: utf-8\n#\n# pylint: disable=C0111,E1101,R0201\n# C0111: Missing docstring\n# E1101: Module 'x' has no 'y' member\n# R0201: Method could be a function\n\nimport pytest\n\nfrom sagitta.cat import Category, TypeVariable, Number, Eq, Ord, Complex, Real\nfrom sagitta.test import assert_subclass\n\n\nclass TestCatogeries(object):\n\n @pytest.mark.parametrize(['cat', 'sub'], [\n [Category, TypeVariable],\n [Category, Number],\n [Category, Eq],\n [Eq, Ord],\n [Eq, Complex],\n [Ord, Real],\n ])\n def test_categories(self, sub, cat):\n assert_subclass(sub, cat)\n","sub_path":"sagitta/test/test_cat.py","file_name":"test_cat.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"401407712","text":"# segmentation.py\r\n# ===============\r\n#\r\n# particle analysis on the GPU\r\n#\r\n# Author: Robert Haase, rhaase@mpi-cbg.de\r\n# October 2019\r\n#########################################\r\n\r\nfrom ij import IJ;\r\nfrom net.haesleinhuepf.clijx import CLIJx;\r\n\r\n\r\nIJ.run(\"Close All\");\r\n\r\n# load example image\r\nimp = IJ.openImage(\"http://wsr.imagej.net/images/blobs.gif\");\nIJ.run(imp, \"32-bit\", \"\");\r\nimp.show();\r\n\r\n# init GPU\r\nclijx = CLIJx.getInstance();\r\n\r\n# push image to GPU\r\ninput = clijx.push(imp);\r\n\r\n# reserve memory for output, same size and type as input\nblurred = clijx.create(input);\nthresholded = clijx.create(input);\nlabelled = clijx.create(input);\nlabelled_without_edges = clijx.create(input);\n\n# blur, threshold and label the image\nclijx.blur(input, blurred, 5, 5, 0);\nclijx.automaticThreshold(blurred, thresholded, \"Otsu\");\r\nclijx.connectedComponentsLabeling(thresholded, labelled);\nclijx.excludeLabelsOnEdges(labelled, labelled_without_edges);\n\n# show result\r\nclijx.show(labelled_without_edges, \"labelled_without_edges\");\nIJ.run(\"glasbey\");\n\r\n# clean up\n\rinput.close();\nblurred.close();\nthresholded.close();\nlabelled.close();\n\r\n\r\n\r\n","sub_path":"src/main/jython/segmentation.py","file_name":"segmentation.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"301590459","text":"\n\nclass Word:\n\n\n def __init__(self, actualWord , partOfSpeech, characterOffsetBegin, characterOffsetEnd, linkers):\n self.actualWord = actualWord\n self.partOfSpeech = partOfSpeech\n self.characterOffsetBegin = characterOffsetBegin\n self.characterOffsetEnd = characterOffsetEnd\n self.linkers = linkers\n\n\n def __init__(self, actualWord , partOfSpeech):\n self.actualWord = actualWord\n self.partOfSpeech = partOfSpeech\n\n\n @classmethod\n def loadFromParser(self , parsedWord):\n actualWord = parsedWord[0]\n partOfSpeech = parsedWord[1]['PartOfSpeech']\n #characterOffsetEnd = parsedWord[1]['CharacterOffsetEnd']\n #characterOffsetBegin = parsedWord[1]['CharacterOffsetBegin']\n #linkers = parsedWord[1]['Linkers']\n return self(actualWord, partOfSpeech)\n","sub_path":"source/implicit_args/Word.py","file_name":"Word.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"652625832","text":"# -*- coding: utf-8 -*-\nimport airflow\nfrom datetime import datetime, timedelta\nfrom airflow.operators.hive_operator import HiveOperator\nfrom airflow.operators.impala_plugin import ImpalaOperator\nfrom utils.connection_helper import get_hive_cursor\nfrom airflow.operators.python_operator import PythonOperator\nfrom airflow.contrib.hooks.redis_hook import RedisHook\nfrom airflow.hooks.hive_hooks import HiveCliHook\nfrom airflow.operators.hive_to_mysql import HiveToMySqlTransfer\nfrom airflow.operators.mysql_operator import MySqlOperator\nfrom airflow.operators.dagrun_operator import TriggerDagRunOperator\nfrom airflow.sensors.external_task_sensor import ExternalTaskSensor\nfrom airflow.operators.bash_operator import BashOperator\nfrom airflow.sensors.named_hive_partition_sensor import NamedHivePartitionSensor\nfrom airflow.sensors.hive_partition_sensor import HivePartitionSensor\nfrom airflow.sensors import UFileSensor\nfrom plugins.TaskTimeoutMonitor import TaskTimeoutMonitor\nfrom plugins.TaskTouchzSuccess import TaskTouchzSuccess\nimport json\nimport logging\nfrom airflow.models import Variable\nimport requests\nimport os\nfrom airflow.sensors.s3_key_sensor import S3KeySensor\nfrom airflow.sensors import OssSensor\n\nargs = {\n 'owner': 'lijialong',\n 'start_date': datetime(2019, 9, 21),\n 'depends_on_past': False,\n 'retries': 3,\n 'retry_delay': timedelta(minutes=2),\n 'email': ['bigdata_dw@opay-inc.com'],\n 'email_on_failure': True,\n 'email_on_retry': False,\n}\n\ndag = airflow.DAG('app_oride_order_skyeye_analysis_d',\n schedule_interval=\"40 7 * * *\",\n default_args=args,\n )\n\nsleep_time = BashOperator(\n task_id='sleep_id',\n depends_on_past=False,\n bash_command='sleep 30',\n dag=dag)\n##----------------------------------------- 变量 ---------------------------------------##\n\ntable_name = \"app_oride_order_skyeye_analysis_d\"\n\n##----------------------------------------- 依赖 ---------------------------------------##\n#获取变量\ncode_map=eval(Variable.get(\"sys_flag\"))\n\n#判断ufile(cdh环境)\nif code_map[\"id\"].lower()==\"ufile\":\n\n # 依赖前一天分区\n dependence_dwd_oride_order_skyeye_di_prev_day_task = UFileSensor(\n task_id='dwd_oride_order_skyeye_di_prev_day_task',\n filepath='{hdfs_path_str}/dt={pt}/_SUCCESS'.format(\n hdfs_path_str=\"oride/oride_dw/dwd_oride_order_skyeye_di/country_code=nal\",\n pt='{{ds}}'\n ),\n bucket_name='opay-datalake',\n poke_interval=60, # 依赖不满足时,一分钟检查一次依赖状态\n dag=dag\n )\n\n dependence_dwd_oride_order_base_include_test_di_prev_day_task = S3KeySensor(\n task_id='dwd_oride_order_base_include_test_di_prev_day_task',\n bucket_key='{hdfs_path_str}/dt={pt}/_SUCCESS'.format(\n hdfs_path_str=\"oride/oride_dw/dwd_oride_order_base_include_test_di/country_code=NG\",\n pt='{{ds}}'\n ),\n bucket_name='opay-bi',\n poke_interval=60, # 依赖不满足时,一分钟检查一次依赖状态\n dag=dag\n )\n dependence_dim_oride_driver_base_prev_day_task = UFileSensor(\n task_id='dim_oride_driver_base_prev_day_task',\n filepath='{hdfs_path_str}/dt={pt}/_SUCCESS'.format(\n hdfs_path_str=\"oride/oride_dw/dim_oride_driver_base/country_code=NG\",\n pt='{{ds}}'\n ),\n bucket_name='opay-datalake',\n poke_interval=60, # 依赖不满足时,一分钟检查一次依赖状态\n dag=dag\n )\n hdfs_path = \"ufile://opay-datalake/oride/oride_dw/\" + table_name\n\nelse:\n print(\"成功\")\n dependence_dwd_oride_order_skyeye_di_prev_day_task = OssSensor(\n task_id='dwd_oride_order_skyeye_di_prev_day_task',\n bucket_key='{hdfs_path_str}/dt={pt}/_SUCCESS'.format(\n hdfs_path_str=\"oride/oride_dw/dwd_oride_order_skyeye_di/country_code=nal\",\n pt='{{ds}}'\n ),\n bucket_name='opay-datalake',\n poke_interval=60, # 依赖不满足时,一分钟检查一次依赖状态\n dag=dag\n )\n\n dependence_dwd_oride_order_base_include_test_di_prev_day_task = OssSensor(\n task_id='dwd_oride_order_base_include_test_di_prev_day_task',\n bucket_key='{hdfs_path_str}/dt={pt}/_SUCCESS'.format(\n hdfs_path_str=\"oride/oride_dw/dwd_oride_order_base_include_test_di/country_code=NG\",\n pt='{{ds}}'\n ),\n bucket_name='opay-datalake',\n poke_interval=60, # 依赖不满足时,一分钟检查一次依赖状态\n dag=dag\n )\n dependence_dim_oride_driver_base_prev_day_task = OssSensor(\n task_id='dim_oride_driver_base_prev_day_task',\n bucket_key='{hdfs_path_str}/dt={pt}/_SUCCESS'.format(\n hdfs_path_str=\"oride/oride_dw/dim_oride_driver_base/country_code=NG\",\n pt='{{ds}}'\n ),\n bucket_name='opay-datalake',\n poke_interval=60, # 依赖不满足时,一分钟检查一次依赖状态\n dag=dag\n )\n hdfs_path = \"oss://opay-datalake/oride/oride_dw/\" + table_name\n\n\n##----------------------------------------- 任务超时监控 ---------------------------------------##\n\ndef fun_task_timeout_monitor(ds,dag,**op_kwargs):\n\n dag_ids=dag.dag_id\n\n tb = [\n {\"dag\":dag,\"db\": \"oride_dw\", \"table\":\"{dag_name}\".format(dag_name=dag_ids), \"partition\": \"country_code=nal/dt={pt}\".format(pt=ds), \"timeout\": \"2400\"}\n ]\n\n TaskTimeoutMonitor().set_task_monitor(tb)\n\ntask_timeout_monitor= PythonOperator(\n task_id='task_timeout_monitor',\n python_callable=fun_task_timeout_monitor,\n provide_context=True,\n dag=dag\n)\n\n##----------------------------------------- 脚本 ---------------------------------------##\n\n##----------------------------------------- 脚本 ---------------------------------------##\n\n\napp_oride_order_skyeye_analysis_d_task = HiveOperator(\n task_id='app_oride_order_skyeye_analysis_d_task',\n hql='''\n\n set hive.exec.parallel=true;\n set hive.exec.dynamic.partition.mode=nonstrict;\n\n insert overwrite TABLE oride_dw.{table} partition(country_code,dt)\n SELECT \n a.ver, --\n a.order_id,--订单id\n a.tag_id,\n b.driver_id,--司机id\n b.passenger_id as user_id,--乘客id\n b.duration,--订单持续时间\n b.distance,--订单距离\n b.price,--订单价格\n b.reward,--司机奖励\n b.city_id,--城市id\n b.pay_mode as mode,--支付模式\n c.phone_number,--司机手机号\n 'nal' as country_code,--国家码\n '{pt}' as dt\n FROM\n (\n SELECT * \n FROM oride_dw.dwd_oride_order_skyeye_di \n WHERE dt = '{pt}' and ver is not null\n ) a\n LEFT JOIN\n ( SELECT \n order_id,\n driver_id,\n passenger_id,\n duration,\n distance,\n price,\n reward,\n city_id,\n pay_mode,\n country_code\n FROM oride_dw.dwd_oride_order_base_include_test_di\n WHERE dt = '{pt}'\n AND from_unixtime(create_time,\"yyyy-MM-dd\") = '{pt}'\n ) b ON a.order_id = b.order_id\n LEFT JOIN\n (\n SELECT\n driver_id,\n phone_number\n FROM oride_dw.dim_oride_driver_base \n WHERE dt = '{pt}'\n ) c ON b.driver_id = c.driver_id\n'''.format(\n pt='{{ds}}',\n table=table_name\n ),\n schema='oride_dw',\n dag=dag)\n\n# 生成_SUCCESS\ntouchz_data_success = BashOperator(\n\n task_id='touchz_data_success',\n\n bash_command=\"\"\"\n line_num=`$HADOOP_HOME/bin/hadoop fs -du -s {hdfs_data_dir} | tail -1 | awk '{{print $1}}'`\n\n if [ $line_num -eq 0 ]\n then\n echo \"FATAL {hdfs_data_dir} is empty\"\n exit 1\n else\n echo \"DATA EXPORT Successed ......\"\n $HADOOP_HOME/bin/hadoop fs -touchz {hdfs_data_dir}/_SUCCESS\n fi\n \"\"\".format(\n pt='{{ds}}',\n now_day='{{macros.ds_add(ds, +1)}}',\n hdfs_data_dir=hdfs_path + '/country_code=nal/dt={{ds}}'\n ),\n dag=dag)\n\ndependence_dwd_oride_order_skyeye_di_prev_day_task >> \\\ndependence_dwd_oride_order_base_include_test_di_prev_day_task >> \\\ndependence_dim_oride_driver_base_prev_day_task >> \\\nsleep_time >> app_oride_order_skyeye_analysis_d_task >> touchz_data_success\n","sub_path":"oride_dw_code/app/app_oride_order_skyeye_analysis_d.py","file_name":"app_oride_order_skyeye_analysis_d.py","file_ext":"py","file_size_in_byte":8301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"49535288","text":"def compute_z(string):\n n = len(string)\n z = [0] * n\n\n zbox_l, zbox_r, z[0] = 0, 0, n\n for i in range(1, n):\n if i < zbox_r: # i is within a zbox\n k = i - zbox_l\n if z[k] < zbox_r - i:\n z[i] = z[k] # Full optimization\n continue\n zbox_l = i # Partial optimization\n else:\n zbox_l = zbox_r = i # Match from scratch\n while zbox_r < n and string[zbox_r - zbox_l] == string[zbox_r]:\n zbox_r += 1\n z[i] = zbox_r - zbox_l\n return z\n\ns = \"raj\"\ns1=\"maharajadihirajmaharajadihirajmaharajadihirajmaharajadihirajmaharajadihirajmaharajadihirajmaharajadihiraj\"\nz = compute_z(s+\"$\"+s1)\nfor i,v in enumerate(z):\n if v == len(s):\n print(i - 4)","sub_path":"LeetCodeContests/62/zalgo.py","file_name":"zalgo.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"597283970","text":"# encoding=UTF-8\n\nimport requests, json, logging, time\nfrom zentaos import util\nfrom collections import OrderedDict\n\n\nclass TestTask(object):\n def __init__(self, endpoint, cookie):\n self.endpoint = endpoint\n self.cookie = cookie\n self.module_name = 'testtask'\n\n def get_test_task_by_productId(self, productId, **kwargs):\n result = None\n orderDict = OrderedDict()\n orderDict.__setitem__('productID', productId)\n res = requests.get(\n url='{}?{}'.format(self.endpoint, util.super_model_pack(self.module_name, 'getProductTasks', orderDict)),\n headers=self.cookie)\n if str(res.status_code).startswith('2'):\n try:\n content = json.loads(res.content.decode())\n if content.get('status') == 'success':\n result = json.loads(content.get('data'))\n except Exception as e:\n logging.error(e.__traceback__)\n return result\n\n def get_test_task_by_id(self, taskID):\n orderedDict = OrderedDict()\n orderedDict.__setitem__('taskID', taskID)\n res = requests.get(\n url='{}?{}'.format(self.endpoint, util.super_model_pack(self.module_name, 'getById', orderedDict)),\n headers=self.cookie)\n result = None\n if str(res.status_code).startswith('2'):\n try:\n content = json.loads(res.content.decode())\n if content.get('status') == 'success':\n result = json.loads(content.get('data'))\n except Exception as e:\n logging.error(e.__traceback__)\n return result\n\n def create_test_task(self, productID, projectID, name=None, build='trunk', **kwargs):\n data = {'product': productID, 'project': projectID, 'build': build, 'begin': time.strftime('%Y-%m-%d'),\n 'end': time.strftime('%Y-%m-%d')}\n if not name:\n name = 'API_Test_{}'.format(time.strftime('%Y_%m_%d_%H_%M_%S'))\n data.__setitem__('name', name)\n for key, value in kwargs.items():\n data.__setitem__(key, value)\n res = requests.post(url=self.endpoint, data=data,\n params={'m': self.module_name, 'f': 'create', 'product': productID, 'project': projectID,\n 't': 'json'}, headers=self.cookie)\n if str(res.status_code).startswith('2'):\n if 'body{background:white}' in res.content.decode():\n return name\n return None\n\n def link_test_cases(self, taskID, cases):\n count = 0\n data = {}\n for key, value in cases.items():\n data.__setitem__('cases[{}]'.format(count), key)\n data.__setitem__('versions[{}]'.format(key), value)\n count += 1\n res = requests.post(url=self.endpoint, data=data,\n params={'m': self.module_name, 'f': 'linkCase', 'taskID': taskID, 't': 'json'},\n headers=self.cookie)\n if str(res.status_code).startswith('2'):\n try:\n content = json.loads(res.content.decode())\n if content.get('status') == 'success':\n return True\n except Exception as e:\n logging.error(e.__traceback__)\n return False\n\n def start(self, taskID, comment=''):\n res = requests.post(url=self.endpoint, data={'comment': comment},\n params={'taskID': taskID, 'm': self.module_name, 'f': 'start', 't': 'json',\n 'onlybody': 'yes'}, headers=self.cookie)\n if str(res.status_code).startswith('2'):\n if 'body{background:white}' in res.content.decode():\n return taskID\n return None\n\n def close(self, taskID, comment='', report=''):\n res = requests.post(url=self.endpoint, data={'comment': comment, 'report': report},\n params={'taskID': taskID, 'm': self.module_name, 'f': 'close', 't': 'json',\n 'onlybody': 'yes'}, headers=self.cookie)\n if str(res.status_code).startswith('2'):\n if 'body{background:white}' in res.content.decode():\n return taskID\n return None\n\n def delete(self, taskID):\n res = requests.post(url=self.endpoint,\n params={'taskID': taskID, 'm': self.module_name, 'f': 'delete', 'confirm': 'yes'},\n headers=self.cookie)\n if str(res.status_code).startswith('2'):\n if 'body{background:white}' in res.content.decode():\n return taskID\n return None\n\n def batchRunCases(self, taskID, cases): # need use with zentaos - ext testtask\n orderedDict = OrderedDict()\n orderedDict['taskID'] = taskID\n res = requests.post(\n url='{}?{}'.format(self.endpoint, util.super_model_pack('testtask', 'extBatchRun', orderedDict)),\n data=cases, headers=self.cookie)\n if str(res.status_code).startswith('2'):\n return res.content.decode()\n return None\n\n def unlink_test_case(self, taskID, caseID, rowID=None): # need use with zentaos - ext testtask\n if rowID is None:\n orderedDict = OrderedDict()\n orderedDict.__setitem__('taskID', taskID)\n orderedDict.__setitem__('caseID', caseID)\n res = requests.get(url='{}?{}'.format(self.endpoint,\n util.super_model_pack(self.module_name, 'extUnlinkCase',\n orderedDict)), headers=self.cookie)\n else:\n res = requests.get(url=self.endpoint,\n params={'caseID': rowID, 'm': self.module_name, 'f': 'unlinkCase', 'confirm': 'yes',\n 't': 'json'}, headers=self.cookie)\n if str(res.status_code).startswith('2'):\n return json.loads(res.content.decode())\n return None\n\n def update(self):\n pass\n","sub_path":"zentaos/models/testtask.py","file_name":"testtask.py","file_ext":"py","file_size_in_byte":6107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"3461423","text":"from classes.characters import Character\r\n\r\nclass MacGyver(Character):\r\n \"\"\" Class used for MacGyver, inherits the Character class\"\"\"\r\n\r\n def __init__(self, y, x, img, mapping):\r\n Character.__init__(self, y, x, img, mapping)\r\n self.bag = 0\r\n\r\n def set_onmap(self, mapping):\r\n mapping.set_macgyver(self.y_pos, self.x_pos)\r\n\r\n def moving(self, direction):\r\n \"\"\"MacGyver moves from tile to tile depending on the direction chosen by the player\"\"\"\r\n if direction == 'left':\r\n self.x_pos -= 1\r\n elif direction == 'right':\r\n self.x_pos += 1\r\n elif direction == 'bottom':\r\n self.y_pos += 1\r\n elif direction == 'top':\r\n self.y_pos -= 1\r\n","sub_path":"classes/gyver.py","file_name":"gyver.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"236320734","text":"from genesis import Genesis\nimport json\nfrom Orange.data import *\nimport io\nimport gzip\n\n\nDEFAULT_EMAIL = 'anonymous@genialis.com'\nDEFAULT_PASSWD = 'anonymous'\nDEFAULT_URL = 'https://dictyexpress.research.bcm.edu'\n\n\nclass Genapi(object):\n\n \"\"\" Python module that leverages Genesis PyAPI (Python API for the Genesis platform) \"\"\"\n\n def __init__(self, email=DEFAULT_EMAIL, password=DEFAULT_PASSWD, url=DEFAULT_URL, buffer=None ):\n\n self.gen = Genesis(email, password, url)\n self.buffer = buffer\n self.email = email\n\n def fetch_objects(self):\n \"\"\"\n Function downloads all available :obj:`GenData` from DictyExpress database.\n Objects are stored in buffer for further use.\n \"\"\"\n\n projects = self.gen.projects() # gets all available experiments for currently logged in user\n store_experiments = []\n\n for project in list(projects.values()):\n if not project.name == \"dictyExpress BCM\":\n if 'data:etc:' in project.data_types():\n data = project.data(type__startswith='data:etc:')\n for obj in data:\n store_experiments.append(obj)\n\n if self.buffer is not None:\n self.to_buffer(self.email, store_experiments) # store res_objects to buffer\n\n def download(self, object_id):\n\n \"\"\"\n Function downloads data of a chosen experiment from the server. Downloaded data is stored in buffer.\n\n :param object_id: ID of :obj:`GenData` to get from buffer\n :return: Returns data in json like format\n :rtype: 'dict'\n \"\"\"\n if self.buffer is not None:\n if not self.in_buffer(object_id):\n etc = self.from_buffer(self.email, object_id)\n\n response = etc.download('output.etcfile')\n response_gzipped = io.BytesIO(response.content)\n response_content = io.TextIOWrapper(\n gzip.GzipFile(fileobj=response_gzipped),\n encoding=\"utf-8\")\n\n json_object = json.load(response_content)\n\n self.to_buffer(object_id, json_object)\n\n return json_object\n\n else:\n return self.from_buffer(object_id)\n\n def to_table(self, etc_json):\n\n \"\"\"\n :param etc_json: Data in json like format\n :return: function returns Orange table\n :rtype : `Orange.data.Table`\n\n \"\"\"\n\n json_object = etc_json\n\n variables = []\n tp = 1\n for time in json_object['etc']['timePoints']:\n var = ContinuousVariable(\"TP \" + str(tp))\n var.attributes[\"Time\"] = float(time)\n variables.append(var)\n tp += 1\n\n meta_attr = StringVariable.make(\"DDB\")\n domain = Domain(variables, metas=[meta_attr])\n\n table = []\n for row in json_object['etc']['genes']:\n gene = []\n for i in [time for time in json_object['etc']['genes'][row]]:\n gene.append(i)\n gene.append(row)\n table.append(gene)\n\n orangeTable = Table(domain, table)\n\n return orangeTable\n\n def to_buffer(self, addr, objects, version=\"0\", autocommit=True):\n \"\"\"\n\n :param addr: Address where list of :obj:`GenData` will be stored.\n :param objects: list of :obj:`GenData`\n :param version: Default is 0\n :param autocommit: Default is True\n :return:\n \"\"\"\n\n if self.buffer:\n self.buffer.add(addr, objects, version=version, autocommit=autocommit)\n\n def from_buffer(self, addr, get_id=None):\n \"\"\"\n\n :param addr: Address of GenData objects\n :param get_id: ID of :obj:`GenData`\n :return: single :obj:`GenData` if ID is provided. If id is None returns a list of :obj:`GenData`\n \"\"\"\n\n if get_id is None:\n return self.buffer.get(addr)\n else:\n for object in self.buffer.get(addr):\n if object.id == get_id:\n return object\n\n def in_buffer(self, addr):\n \"\"\"\n :param addr: Address of stored :obj:`GenData` list.\n :return: Returns True if buffer contains address else returns False\n \"\"\"\n\n if self.buffer:\n return self.buffer.contains(addr)\n else:\n return False\n","sub_path":"genapi.py","file_name":"genapi.py","file_ext":"py","file_size_in_byte":4368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"610613095","text":"import cv2\n\n# rgb 이미지 불러오기\nrgb_image = cv2.imread('img/iu.jpg')\ndst = cv2.resize(rgb_image, dsize=(100, 100), interpolation=cv2.INTER_AREA)\ndst2 = cv2.resize(rgb_image, dsize=(0, 0), fx=0.3, fy=0.7, interpolation=cv2.INTER_LINEAR)\n\n\n# rgb 이미지 보기\n#cv2.imshow('kakao', rgb_image)\ncv2.imshow('kakao', dst)\ncv2.waitKey(0) \nprint(rgb_image)\n\n","sub_path":"HelloPython/day14/mycv04.py","file_name":"mycv04.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"348706582","text":"\"\"\"\nReuters Corpus Volume I (RCV1) is an archive of over 800,000 manually categorized newswire stories made available by Reuters, Ltd. for research purposes. The dataset is extensively described in:\nLewis, D. D., Yang, Y., Rose, T. G., & Li, F. (2004). RCV1: A new benchmark collection for text categorization research. The Journal of Machine Learning Research, 5, 361-397.\n\nThe feature matrix is a scipy CSR sparse matrix, with 804414 samples and 47236 features. Non-zero values contains cosine-normalized, log TF-IDF vectors.\n\nRef: http://scikit-learn.org/stable/datasets/index.html#rcv1-dataset\n\n\"\"\"\nfrom __future__ import print_function\n\nimport sys\nimport numpy as np\nfrom time import time\nimport logging\n\nfrom sklearn.datasets import fetch_rcv1, dump_svmlight_file\n\nprint(__doc__)\n\n# Display progress logs on stdout\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')\n\ndatahome = '.'\nif len(sys.argv) > 1:\n datahome = sys.argv[1] \n\n# #############################################################################\n# Download the data, if not already on disk and load it as numpy arrays\ndname = 'rcv1'\ndata = fetch_rcv1(subset='all', data_home='.')\n\n\nn_samples, n_features = data.data.shape\nx = data.data\ny = data.target\ntarget_names = data.target_names\nn_classes = target_names.shape[0]\n\nprint(\"Total dataset size:\")\nprint(\"n_samples: %d\" % n_samples)\nprint(\"n_features: %d\" % n_features)\nprint(\"n_classes: %d\" % n_classes)\n\n#save to file\n#np.savez(dname, data= data.data, target=data.target, target_names=data.target_names)\n\n#\n# downgrade to top level classes\n# CCAT, ECAT, GCAT, and MCAT\n#\ncategories=[u'CCAT', u'ECAT', u'GCAT',u'MCAT']\nindexes= [0,0,0,0]\nfor idx, cate in enumerate(categories):\n indexes[idx] = (np.argwhere(data.target_names == cate)[0][0])\n print('%s : %d'%(cate, indexes[idx]))\n\ntopy = np.zeros((n_samples))\nfor rowid, row in enumerate(data.target):\n targets = row.toarray()[0]\n \n for idx, cate in enumerate(categories):\n if targets[indexes[idx]] == 1:\n #match\n topy[rowid] = idx + 1\n break\n\nif np.sum(topy == 0) > 0:\n #something wrong there\n print('Error: %d records have no top categories'%(np.sum(topy==0)))\n\n\ndump_svmlight_file(x, topy, dname + '.svm')\n\n","sub_path":"harp-daal-python/examples/scdemo/src/make_rcv1.py","file_name":"make_rcv1.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"222797152","text":"from django.test import TestCase, Client\nfrom django.template.loader import render_to_string\n\n# Create your tests here.\n\nclass TestIndexView(TestCase):\n\n def test_index_view(self):\n client = Client()\n response = client.get('/')\n self.assertEqual(response.status_code, 200)\n\n with self.assertTemplateUsed('index.html'):\n render_to_string('index.html')","sub_path":"quote_api/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"320510897","text":"import os\nimport json\nimport subprocess\nimport time\n\n# Checks config is present, launches telservice, if no config present, launches the config manager\nif (os.path.isfile(\"config.json\")):\n with open('config.json') as json_file: \n json_config_data_persist = json.load(json_file)\n CREATE_NO_WINDOW = 0x08000000 # Hides app in system tray\n subprocess.Popen('telservice.exe', creationflags=CREATE_NO_WINDOW) # main telservice\n time.sleep(1)\n subprocess.Popen('rmodule.exe', creationflags=CREATE_NO_WINDOW) # application security module\nelse:\n print(\"No config file!\")\n os.startfile('config-generator.exe')\n\n","sub_path":"desktop-application/python-files/launchers/launch-manager.py","file_name":"launch-manager.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"283426489","text":"# ========================================================================================\n# Train and evaluate geometric matching model\n# Author: Jingwei Qu\n# Date: 01 June 2019\n# ========================================================================================\n\nfrom __future__ import print_function, division\nimport torch\nimport torchvision\nimport time\nimport cv2\n\nfrom geometric_matching.geotnf.transformation_tps import GeometricTnf\nfrom geometric_matching.util.net_util import *\nfrom geometric_matching.image.normalization import normalize_image\nfrom geometric_matching.geotnf.point_tnf import PointsToPixelCoords\n\ndef draw_grid(image, cp_norm):\n im_size = torch.Tensor([[240, 240]]).cuda()\n cp = PointsToPixelCoords(P=cp_norm, im_size=im_size)\n cp = cp.squeeze().cpu().numpy() + 50\n for j in range(9):\n cv2.drawMarker(image, (cp[0, j], cp[1, j]), (0, 0, 255), cv2.MARKER_TILTED_CROSS, 12, 2, cv2.LINE_AA)\n\n for j in range(2):\n for k in range(3):\n # vertical grid\n cv2.line(image, (cp[0, j + k * 3], cp[1, j + k * 3]), (cp[0, j + k * 3 + 1], cp[1, j + k * 3 + 1]), (0, 0, 255), 2, cv2.LINE_AA)\n # horizontal grid\n cv2.line(image, (cp[0, j * 3 + k], cp[1, j * 3 + k]), (cp[0, j * 3 + k + 3], cp[1, j * 3 + k + 3]), (0, 0, 255), 2, cv2.LINE_AA)\n\n return image\n\ndef add_watch(watch_images, watch_theta, batch, geoTnf, theta_st, theta_tr, k, l):\n warped_image_st = geoTnf(batch['source_image'][0].unsqueeze(0), theta_st[0].unsqueeze(0))\n warped_image_tr = geoTnf(batch['target_image'][0].unsqueeze(0), theta_tr[0].unsqueeze(0))\n warped_image_sr = geoTnf(warped_image_st, theta_tr[0].unsqueeze(0))\n\n watch_images[k, :, 50:290, 50:290] = batch['source_image'][0]\n watch_images[k + 1, :, 50:290, 50:290] = warped_image_st.detach()\n watch_images[k + 2, :, 50:290, 50:290] = batch['target_image'][0]\n\n watch_images[k + 3, :, 50:290, 50:290] = batch['target_image'][0]\n watch_images[k + 4, :, 50:290, 50:290] = warped_image_tr.detach()\n watch_images[k + 5, :, 50:290, 50:290] = batch['refer_image'][0]\n\n watch_images[k + 6, :, 50:290, 50:290] = batch['source_image'][0]\n watch_images[k + 7, :, 50:290, 50:290] = warped_image_sr.detach()\n watch_images[k + 8, :, 50:290, 50:290] = batch['refer_image'][0]\n\n watch_theta[l*2, :] = theta_st[0].detach()\n watch_theta[l*2+1, :] = theta_tr[0].detach()\n\n return watch_images, watch_theta\n\ndef train_fn(epoch, model, loss_fn, loss_cycle_fn, loss_jitter_fn, lambda_c, lambda_j, optimizer, dataloader,\n triple_generation, geometric_model='tps', use_cuda=True, log_interval=100, vis=None):\n \"\"\"\n Train the model with synthetically training triple:\n {source image, target image, refer image (warped source image), theta_GT} from PF-PASCAL.\n 1. Train the transformation parameters theta_st from source image to target image;\n 2. Train the transformation parameters theta_tr from target image to refer image;\n 3. Combine theta_st and theta_st to obtain theta from source image to refer image, and compute loss between\n theta and theta_GT.\n \"\"\"\n\n geoTnf = GeometricTnf(geometric_model=geometric_model, use_cuda=use_cuda)\n epoch_loss = 0\n if (epoch % 5 == 0 or epoch == 1) and vis is not None:\n stride_images = len(dataloader) / 3\n group_size = 9\n watch_images = torch.ones(group_size * 4, 3, 340, 340).cuda()\n watch_theta = torch.zeros(8, 36).cuda()\n fnt = cv2.FONT_HERSHEY_COMPLEX\n stride_loss = len(dataloader) / 105\n iter_loss = np.zeros(106)\n begin = time.time()\n for batch_idx, batch in enumerate(dataloader):\n ''' Move input batch to gpu '''\n # batch['source_image'].shape & batch['target_image'].shape: (batch_size, 3, 240, 240)\n # batch['theta'].shape-tps: (batch_size, 18)-random or (batch_size, 18, 1, 1)-(pre-set from csv)\n if use_cuda:\n batch = batch_cuda(batch)\n\n ''' Get the training triple {source image, target image, refer image (warped source image), theta_GT}'''\n batch_triple = triple_generation(batch)\n\n ''' Train the model '''\n optimizer.zero_grad()\n loss = 0\n # Predict tps parameters between images\n # theta.shape: (batch_size, 18) for tps, theta.shape: (batch_size, 6) for affine\n theta_st, theta_ts, theta_tr, theta_rt = model(batch_triple) # from source image to target image\n loss_match = loss_fn(theta_st=theta_st, theta_tr=theta_tr, theta_GT=batch_triple['theta_GT'])\n loss_cycle_st = loss_cycle_fn(theta_AB=theta_st, theta_BA=theta_ts)\n loss_cycle_ts = loss_cycle_fn(theta_AB=theta_ts, theta_BA=theta_st)\n loss_cycle_tr = loss_cycle_fn(theta_AB=theta_tr, theta_BA=theta_rt)\n loss_cycle_rt = loss_cycle_fn(theta_AB=theta_rt, theta_BA=theta_tr)\n loss_jitter = loss_jitter_fn(theta_st=theta_st, theta_tr=theta_tr)\n loss = loss_match + lambda_c * (loss_cycle_st + loss_cycle_ts + loss_cycle_tr + loss_cycle_rt) / 4 + lambda_j * loss_jitter\n # loss = loss_match + lambda_c * (loss_cycle_st + loss_cycle_ts + loss_cycle_tr + loss_cycle_rt) / 4\n loss.backward()\n optimizer.step()\n epoch_loss += loss.item()\n if (batch_idx+1) % log_interval == 0:\n end = time.time()\n print('Train epoch: {} [{}/{} ({:.0%})]\\t\\tCurrent batch loss: {:.6f}\\t\\tTime cost ({} batches): {:.4f} s'\n .format(epoch, batch_idx+1, len(dataloader), (batch_idx+1) / len(dataloader), loss.item(), batch_idx + 1, end - begin))\n\n if (epoch % 5 == 0 or epoch == 1) and vis is not None:\n if (batch_idx + 1) % stride_images == 0 or batch_idx == 0:\n watch_images, watch_theta = add_watch(watch_images, watch_theta, batch_triple, geoTnf, theta_st, theta_tr, int((batch_idx + 1) / stride_images) * group_size, int((batch_idx + 1) / stride_images))\n\n # if batch_idx <= 19:\n # watch_images, image_names = add_watch(watch_images, watch_theta, batch_st, batch_tr, geoTnf, theta_st, theta_tr, batch_idx * group_size, batch_idx)\n # if batch_idx == 19:\n # opts = dict(jpgquality=100, title='Epoch ' + str(epoch) + ' source warped_sr target warped_tr refer warped_sr')\n # watch_images[:, :, 50:290, 50:290] = normalize_image(watch_images[:, :, 50:290, 50:290], forward=False)\n # watch_images *= 255.0\n # watch_images = watch_images.permute(0, 2, 3, 1).cpu().numpy().astype(np.uint8)\n # for i in range(watch_images.shape[0]):\n # if i % group_size == 0:\n # cp_norm = watch_theta[int(i / group_size), :18].view(1, 2, -1)\n # watch_images[i] = draw_grid(watch_images[i], cp_norm)\n #\n # cp_norm = watch_theta[int(i / group_size), 18:].view(1, 2, -1)\n # watch_images[i + 1] = draw_grid(watch_images[i + 1], cp_norm)\n #\n # cp_norm = watch_theta[int(i / group_size) + 1, :18].view(1, 2, -1)\n # watch_images[i + 3] = draw_grid(watch_images[i + 3], cp_norm)\n #\n # cp_norm = watch_theta[int(i / group_size) + 1, 18:].view(1, 2, -1)\n # watch_images[i + 4] = draw_grid(watch_images[i + 4], cp_norm)\n #\n # watch_images = torch.Tensor(watch_images.astype(np.float32))\n # watch_images = watch_images.permute(0, 3, 1, 2)\n # vis.image(torchvision.utils.make_grid(watch_images, nrow=3, padding=3), opts=opts)\n\n if (batch_idx + 1) % stride_loss == 0 or batch_idx == 0:\n iter_loss[int((batch_idx + 1) / stride_loss)] = epoch_loss / (batch_idx + 1)\n\n # watch_images = normalize_image(batch_tr['target_image'], forward=False) * 255.0\n # vis.images(watch_images, nrow=8, padding=3)\n\n end = time.time()\n\n # Visualize watch images & train loss\n if (epoch % 5 == 0 or epoch == 1) and vis is not None:\n opts = dict(jpgquality=100, title='Epoch ' + str(epoch) + ' source warped_sr target warped_tr refer warped_sr')\n watch_images[:, :, 50:290, 50:290] = normalize_image(watch_images[:, :, 50:290, 50:290], forward=False)\n watch_images *= 255.0\n watch_images = watch_images.permute(0, 2, 3, 1).cpu().numpy().astype(np.uint8)\n for i in range(watch_images.shape[0]):\n if i % group_size == 0:\n cp_norm = watch_theta[int(i / group_size), :18].view(1, 2, -1)\n watch_images[i] = draw_grid(watch_images[i], cp_norm)\n\n cp_norm = watch_theta[int(i / group_size), 18:].view(1, 2, -1)\n watch_images[i + 1] = draw_grid(watch_images[i + 1], cp_norm)\n\n cp_norm = watch_theta[int(i / group_size) + 1, :18].view(1, 2, -1)\n watch_images[i + 3] = draw_grid(watch_images[i + 3], cp_norm)\n\n cp_norm = watch_theta[int(i / group_size) + 1, 18:].view(1, 2, -1)\n watch_images[i + 4] = draw_grid(watch_images[i + 4], cp_norm)\n\n watch_images = torch.Tensor(watch_images.astype(np.float32))\n watch_images = watch_images.permute(0, 3, 1, 2)\n vis.image(torchvision.utils.make_grid(watch_images, nrow=3, padding=3), opts=opts)\n\n opts_loss = dict(xlabel='Iterations (' + str(stride_loss) + ')',\n ylabel='Loss',\n title='GM ResNet101 ' + geometric_model + ' Training Loss in Epoch ' + str(epoch),\n legend=['Loss'],\n width=2000)\n vis.line(iter_loss, np.arange(106), opts=opts_loss)\n\n epoch_loss /= len(dataloader)\n print('Train set -- Average loss: {:.6f}\\t\\tTime cost: {:.4f}'.format(epoch_loss, end - begin))\n return epoch_loss, end - begin","sub_path":"geometric_matching/util/train_fn_tps_control2.py","file_name":"train_fn_tps_control2.py","file_ext":"py","file_size_in_byte":10017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"338321670","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n Copyright (c) 2021, Ontario Institute for Cancer Research (OICR).\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 Authors:\n Junjun Zhang \n\"\"\"\n\nimport os\nimport sys\nimport yaml\nfrom glob import glob\nfrom typing import List\nfrom click import echo\nfrom .git import Git\nfrom .package import Package\nfrom .utils import locate_nearest_parent_dir_with_file\n\n\nclass Project(object):\n \"\"\"\n Project object keeps all information about the package project\n \"\"\"\n debug: bool = False\n git: Git = None\n root: str = None\n name: str = None\n fullname: str = None\n license: str = None\n repo_type: str = None\n repo_server: str = None\n repo_account: str = None\n cwd: str = None\n current_pkg: Package = None\n pkgs: List[Package] = []\n installed_pkgs: List[Package] = []\n\n def __init__(self, debug=False, project_root=None):\n self.cwd = os.getcwd()\n self.debug = debug\n self.git = Git()\n\n if project_root:\n if os.path.isfile(os.path.join(project_root, '.wfpm')):\n self.root = project_root\n else:\n raise Exception(f\"Specified project root path misses '.wfpm' file: {project_root}\")\n else:\n self.root = locate_nearest_parent_dir_with_file(\n start_dir=self.cwd,\n filename='.wfpm'\n )\n\n if not self.root:\n return # not a project yet, no need to go further\n\n with open(os.path.join(self.root, '.wfpm'), 'r') as c:\n conf = yaml.safe_load(c)\n\n fields = ['project_name', 'repo_type', 'repo_server', 'repo_account']\n if set(fields) - set(conf.keys()):\n raise Exception(f\"Invalid .wfpm file: {os.path.join(self.root, '.wfpm')}, \"\n f\"expected fields: {', '.join(fields)}\")\n else:\n self.name = conf['project_name']\n self.repo_type = conf['repo_type']\n self.repo_server = conf['repo_server']\n self.repo_account = conf['repo_account'].lower()\n self.license = conf.get('license', '')\n\n self._populate_pkgs()\n\n @property\n def fullname(self):\n if self.repo_server and self.repo_account and self.name:\n return f\"{self.repo_server}/{self.repo_account}/{self.name}\"\n\n def __repr__(self):\n return self.fullname\n\n def _populate_pkgs(self):\n pkg_jsons = glob(os.path.join(self.root, '*', 'pkg.json'))\n for pkg_json in pkg_jsons:\n try:\n pkg = Package(pkg_json=pkg_json)\n except Exception as ex:\n echo(f\"Problem encounter, invalid package json: {pkg_json}. {ex}\", err=True)\n echo(\"Please fix the issue before continue.\", err=True)\n sys.exit(1)\n\n self.pkgs.append(pkg)\n\n pkg_dir = os.path.join(os.path.dirname(pkg_json), '')\n if os.path.join(self.cwd, '').startswith(pkg_dir):\n self.current_pkg = pkg\n\n @property\n def installed_pkgs(self):\n installed_pkgs = []\n pkg_jsons = glob(os.path.join(\n self.root, 'wfpr_modules', 'github.com', '*', '*', '*', 'pkg.json')\n )\n\n for pkg_json in pkg_jsons:\n try:\n pkg = Package(pkg_json=pkg_json)\n except Exception as ex:\n echo(f\"Problem encounter, invalid package json: {pkg_json}. {ex}\", err=True)\n echo(\"Please fix the issue before continue.\", err=True)\n sys.exit(1)\n\n installed_pkgs.append(pkg)\n\n return installed_pkgs\n","sub_path":"wfpm/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":4207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"580261783","text":"import torch\nfrom torch import nn, optim\n\n\nclass Client:\n def __init__(self, model, dataloader, loss=\"CrossEntropyLoss\", optimizer=\"SGD\") -> None:\n self.device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n self.model = model.to(self.device)\n self.dataloader = dataloader\n self.Epoch = None\n self.loss = None\n \n if loss == \"CrossEntropyLoss\":\n self.loss_fn = nn.CrossEntropyLoss()\n if optimizer == \"SGD\":\n self.optimizer = optim.SGD(self.model.parameters(), lr=1e-3)\n elif optimizer == \"Adam\":\n self.optimizer = optim.Adam(self.model.parameters(), lr=1e-3)\n\n def train(self, epoch=5):\n size = len(self.dataloader.dataset)\n \n for _ in range(epoch):\n epoch_loss = 0\n for batch, (X, y) in enumerate(self.dataloader):\n X, y = X.to(self.device), y.to(self.device)\n\n # Compute prediction error\n pred = self.model(X)\n loss = self.loss_fn(pred, y)\n\n # Backpropagation\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n epoch_loss += loss.item()\n epoch_loss /= size\n\n self.loss = epoch_loss\n print(f\"Client loss: {epoch_loss:>7f}\")\n\n def test(self):\n size = len(self.dataloader.dataset)\n self.model.eval()\n test_loss, correct = 0, 0\n with torch.no_grad():\n for X, y in self.dataloader:\n X, y = X.to(self.device), y.to(self.device)\n pred = self.model(X)\n test_loss += self.loss_fn(pred, y).item()\n correct += (pred.argmax(1) == y).type(torch.float).sum().item()\n \n test_loss /= size\n correct /= size\n print(f\"Client test error: Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f}\")\n \n # get the global model's parameters from parameter server\n def getParame(self, Epoch, parame):\n self.Epoch = Epoch\n self.model.load_state_dict(parame)\n\n # upload the local model's parameters to parameter server\n def uploadParame(self):\n return self.Epoch, self.model.state_dict(), self.loss","sub_path":"src/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"335736544","text":"# 4869. [파이썬 S/W 문제해결 기본] 4일차 - 종이붙이기 D2\n\nf_list=[1,1]\ndef f(n):\n for i in range(n+1):\n if i==len(f_list):\n f_list.append(f_list[i-1]*i)\n return f_list[n]\n\nfor tc in range(1,int(input())+1):\n n=int(input())//10\n count=0\n for i in range(n//2+1):\n count+=int(f(n-i)/(f(n-i*2)*f(i)))*2**i\n print(count)","sub_path":"SWEA/sol/4869.py","file_name":"4869.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"227258922","text":"#!/usr/bin/env python\nfrom setuptools import setup\n\n# read the contents of your README file\nfrom os import path\n\nthis_directory = path.abspath(path.dirname(__file__))\nwith open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:\n long_description = f.read()\n\n\nsetup(name='hitbtc_wss',\n version='1.0.5',\n description='HitBTC Websocket API Client',\n long_description=long_description,\n long_description_content_type='text/markdown',\n author='Mike Ellertson',\n author_email='mdellertson@gmail.com',\n packages=['hitbtc_wss'],\n classifiers=['Programming Language :: Python :: 3 :: Only'],\n install_requires=['websocket-client'],\n package_data={'': ['*.md', '*.rst']},\n url='https://github.com/mellertson/hitbtc')\n\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"607934420","text":"import json\nfrom requests import request\nfrom redis_cache import SingleCache\nSINGLE = SingleCache()\n\ndef get_all_ships():\n starships = json.loads(SINGLE.cache.get('starships')) if SINGLE.cache.exists('starships') else None\n if starships is None:\n result = request('get', 'https://swapi.dev/api/starships/').json()\n starships = result['results'] \n while result['next']:\n next_url = result['next']\n result = request('get', next_url).json()\n starships.extend(result['results'])\n for ship in starships:\n if ship['hyperdrive_rating'] == 'unknown' or ship['cost_in_credits'] == 'unknown':\n ship['score'] = 0\n else:\n ship['score'] = float(ship['hyperdrive_rating'])/float(ship['cost_in_credits'])\n ship['pilots'] = get_people_name_by_url(ship['pilots'])\n ship['films'] = get_film_name_by_url(ship['films'])\n\n starships.sort(key=lambda ship: ship['score'], reverse=True)\n\n SINGLE.cache.set('starships', json.dumps(starships), ex=1800)\n\n return {'starships': starships}\n\n\ndef get_people(page):\n people = json.loads(SINGLE.cache.get(f'people-page-{page}')) if SINGLE.cache.exists(f'people-page-{page}') else None\n if people is None:\n people = request('get', f'https://swapi.dev/api/people/?page={page}').json()\n\n for person in people['results']:\n person['homeworld'] = get_planet_by_url(person['homeworld'])\n person['species'] = get_species_by_url(person['species'])\n person['vehicles'] = get_vehicles_by_url(person['vehicles'])\n person['starships'] = get_ships_by_url(person['starships'])\n person['films'] = get_film_name_by_url(person['films'])\n\n\n SINGLE.cache.set(f'people-page-{page}', json.dumps(people), ex=300)\n return people\n\n\ndef get_people_name_by_url(url_list):\n people = []\n\n if url_list:\n for url in url_list:\n person = json.loads(SINGLE.cache.get(url)) if SINGLE.cache.exists(url) else None\n\n if person is None:\n person = request('get', url).json()\n SINGLE.cache.set(url, json.dumps(person), ex=3600)\n people.append(person['name'])\n\n return people\n\ndef get_film_name_by_url(url_list):\n films = []\n\n if url_list:\n for url in url_list:\n film = json.loads(SINGLE.cache.get(url)) if SINGLE.cache.exists(url) else None\n\n if film is None:\n film = request('get', url).json()\n SINGLE.cache.set(url, json.dumps(film), ex=3600)\n films.append(film['title'])\n\n return films\n\n\ndef get_planet_by_url(url):\n planet = json.loads(SINGLE.cache.get(url)) if SINGLE.cache.exists(url) else None\n if planet is None:\n planet = request('get', url).json()\n\n SINGLE.cache.set(url, json.dumps(planet), ex=3600)\n\n return planet['name']\n\n\ndef get_vehicles_by_url(url_list):\n vehicles = []\n\n if url_list:\n for url in url_list:\n vehicle = json.loads(SINGLE.cache.get(url)) if SINGLE.cache.exists(url) else None\n if vehicle is None:\n vehicle = request('get', url).json()\n SINGLE.cache.set(url, json.dumps(vehicle), ex=3600)\n vehicles.append(vehicle['name'])\n\n return vehicles\n\ndef get_ships_by_url(url_list):\n ships = []\n\n if url_list:\n for url in url_list:\n ship = json.loads(SINGLE.cache.get(url)) if SINGLE.cache.exists(url) else None\n\n if ship is None:\n ship = request('get', url).json()\n SINGLE.cache.set(url, json.dumps(ship), ex=3600)\n ships.append(ship['name'])\n\n return ships\n\ndef get_species_by_url(url_list):\n species = []\n\n if url_list:\n for url in url_list:\n specie = json.loads(SINGLE.cache.get(url)) if SINGLE.cache.exists(url) else None\n\n if specie is None:\n specie = request('get', url).json()\n SINGLE.cache.set(url, json.dumps(specie), ex=3600)\n species.append(specie['name'])\n\n return species\n","sub_path":"backend/app/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":4145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"370660886","text":"#!/usr/bin/env python3\n#coding=utf-8\nimport Adafruit_PCA9685\nimport RPi.GPIO as GPIO\nimport getch\nimport time\n\n\"\"\" PCA9685 \"\"\" \nclass PCA9685_PWM: # A channel of PCA9685\n def __init__(self, channel, min=-4095, max=4095, freq=60):\n self.__pwm = Adafruit_PCA9685.PCA9685()\n self.__pwm.set_pwm_freq(freq) # adjust the PWM frequency,\n self.__channel = channel # A PCA9685 PWM channel (0~15)\n self.__min = min # Pulse minimum limit\n self.__max = max # Pulse maximum limit\n\n def __limit(self, pulse):\n if pulse >= self.__min and pulse <= self.__max:\n return pulse\n elif pulse < self.__min:\n return self.__min\n elif pulse > self.__max:\n return self.__max\n\n def set_pwm(self, pulse):\n pulse = self.__limit(pulse)\n self.__pwm.set_pwm(self.__channel, 0, pulse)\n return pulse\n def pwm_off(self):\n self.__pwm.set_pwm(self.__channel, 0, 0)\n \n\n\"\"\" DC Motor \"\"\"\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\n\nclass DBH_DC_Motor: # Class for DBH-1 DC motor driver\n def __init__(self, pca9685, enable): # Parameter is used to set the PCA9685 and GPIO channels\n self.__pca9685 = [PCA9685_PWM(pca9685[0]), PCA9685_PWM(pca9685[1])] # Create two objects of PCA9685_PWM class for IN1 and IN2\n self.__gpio = enable # GPIO for EN pin\n self.__rotate_val = 0\n GPIO.setup(self.__gpio, GPIO.OUT)\n self.__stop()\n\n def __stop(self):\n GPIO.output(self.__gpio, GPIO.LOW)\n for channel in self.__pca9685: channel.pwm_off()\n def __forward(self, pulse):\n GPIO.output(self.__gpio, GPIO.HIGH)\n self.__pca9685[0].set_pwm(pulse)\n self.__pca9685[1].pwm_off()\n print(\"forward\")\n def __backward(self, pulse):\n GPIO.output(self.__gpio, GPIO.HIGH)\n self.__pca9685[0].pwm_off()\n self.__pca9685[1].set_pwm(pulse)\n print(\"backward\")\n\n def rotate(self, rotate_val):\n if rotate_val == 0:\n self.__stop()\n elif rotate_val > 0:\n self.__forward(abs(rotate_val))\n elif rotate_val < 0:\n self.__backward(abs(rotate_val))\n self.__rotate_val = rotate_val\n\n\n\"\"\" Define \"\"\"\nmotor=DBH_DC_Motor([0,1],17)\n\nKEY_UP = 65\nKEY_DOWN = 66\nKEY_LEFT = 68\nKEY_RIGHT = 67\n\ndef limit(pulse, min, max ):\n if pulse >= min and pulse <= max:\n return pulse\n elif pulse < min:\n return min\n elif pulse > max:\n return max\n\n\"\"\" main \"\"\"\n\nrotate_val = 0\n\ntry:\n while True: \n rotate_val=limit(rotate_val,-4095,4095)\n motor.rotate(rotate_val)\n print(f\"rotate_val= {rotate_val}\")\n\n keycode = ord(getch.getch()) \n if keycode == 27 and ord(getch.getch()) == 91:\n keycode = ord(getch.getch())\n if keycode == KEY_UP:\n rotate_val+=1\n elif keycode == KEY_DOWN:\n rotate_val-=1\n elif keycode == KEY_LEFT:\n rotate_val-=50\n elif keycode == KEY_RIGHT:\n rotate_val+=50\n elif keycode == ord(' '):\n rotate_val = 0\n\nexcept KeyboardInterrupt:\n rotate_val = 0\n\nfinally:\n motor.rotate(0)\n GPIO.cleanup()\n print(\"\")\n","sub_path":"dc_motor/dbh-1_pwm.py","file_name":"dbh-1_pwm.py","file_ext":"py","file_size_in_byte":3245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"587095443","text":"#!/usr/bin/env python3\n\n# example:\n# python summarize_submission.py --tsv submission.tsv --details details.txt --write_tsvs\n# python summarize_submission.py --tsv submission.tsv --details details.txt\n\n# If --write_tsvs is added as an option, it writes the following TSVs, which are subsets of the submission.tsv:\n# missing_submission.tsv: This file contains records (that is, entities or rows in the TSV) that are missing from the details output, which typically means the chunk timed-out.\n# valid_submission.tsv: This file contains valid records that failed because they were in a chunk with invalid entities. This TSV should be able to be submitted as-is without changes.\n# invalid_submission.tsv: This file contains invalid records that failed because of a formatting error. These records each need reformatting before re-submitting.\n# The error messages for invalid records are printed when the script is run.\n\n# To Run interactively\n# Copy and paste the summarize_submission function into ipython, e.g.:\n# res = summarize_submission('submission.tsv','details.txt',write_tsvs=True)\n\nimport argparse, json, ntpath\nimport pandas as pd\n\nparser = argparse.ArgumentParser(description=\"Summarize TSV submission details.\")\nparser.add_argument('-t', '--tsv', required=True, help=\"Filename of the submission TSV\")\nparser.add_argument('-d', '--details', required=True, help=\"Filename of the submission details.\")\nparser.add_argument('-w', '--write_tsvs', help=\"Do you want to write TSVs? 'True' or 'False'\", action='store_true')\nargs = parser.parse_args()\n\n\n# Group entities in details into succeeded (successfully created/updated) and failed valid/invalid\ndef summarize_submission(tsv,details,write_tsvs):\n with open(details, 'r') as file:\n f = file.read().rstrip('\\n')\n chunks = f.split('\\n\\n')\n invalid = []\n messages = []\n valid = []\n succeeded = []\n responses = []\n results = {}\n chunk_count = 1\n for chunk in chunks:\n d = json.loads(chunk)\n if 'code' in d and d['code'] != 200:\n entities = d['entities']\n response = str('Chunk ' + str(chunk_count) + ' Failed: '+str(len(entities))+' entities.')\n responses.append(response)\n for entity in entities:\n sid = entity['unique_keys'][0]['submitter_id']\n if entity['valid']: #valid but failed\n valid.append(sid)\n else: #invalid and failed\n message = entity['errors'][0]['message']\n messages.append(message)\n invalid.append(sid)\n print('Invalid record: '+sid+'\\n\\tmessage: '+message)\n elif 'code' not in d:\n responses.append('Chunk ' + str(chunk_count) + ' Timed-Out: '+str(d))\n else:\n entities = d['entities']\n response = str('Chunk ' + str(chunk_count) + ' Succeeded: '+str(len(entities))+' entities.')\n responses.append(response)\n for entity in entities:\n sid = entity['unique_keys'][0]['submitter_id']\n succeeded.append(sid)\n chunk_count += 1\n results['valid'] = valid\n results['invalid'] = invalid\n results['messages'] = messages\n results['succeeded'] = succeeded\n results['responses'] = responses\n submitted = succeeded + valid + invalid # 1231 in test data\n #get records missing in details from the submission.tsv\n df = pd.read_csv(tsv, sep='\\t',header=0)\n missing_df = df.loc[~df['submitter_id'].isin(submitted)] # these are records that timed-out, 240 in test data\n missing = list(missing_df['submitter_id'])\n results['missing'] = missing\n\n # Find the rows in submitted TSV that are not in either failed or succeeded, 8 time outs in test data, 8*30 = 240 records\n if write_tsvs is True:\n print(\"Writing TSVs: \")\n valid_df = df.loc[df['submitter_id'].isin(valid)] # these are records that weren't successful because they were part of a chunk that failed, but are valid and can be resubmitted without changes\n invalid_df = df.loc[df['submitter_id'].isin(invalid)] # these are records that failed due to being invalid and should be reformatted\n sub_name = ntpath.basename(tsv)\n missing_file = 'missing_' + sub_name\n valid_file = 'valid_' + sub_name\n invalid_file = 'invalid_' + sub_name\n missing_df.to_csv(missing_file, sep='\\t', index=False, encoding='utf-8')\n valid_df.to_csv(valid_file, sep='\\t', index=False, encoding='utf-8')\n invalid_df.to_csv(invalid_file, sep='\\t', index=False, encoding='utf-8')\n print('\\t' + missing_file)\n print('\\t' + valid_file)\n print('\\t' + invalid_file)\n\n return results\n\nsummarize_submission(args.tsv,args.details,args.write_tsvs)\n","sub_path":"expansion/summarize_submission.py","file_name":"summarize_submission.py","file_ext":"py","file_size_in_byte":4787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"368817225","text":"class Resturant:\n\n def __init__(self, resturant_name, cuisine_type):\n self.resturant_name = resturant_name\n self.cuisine_type = cuisine_type\n\n def describe_resturant(self):\n print(f\"Name: {self.resturant_name.title()}\")\n print(f\"Type: {self.cuisine_type.title()}\")\n\n def open_resturant(self):\n print(f\"{self.resturant_name.title()} is now open.\")\n\n\nlowy = Resturant(\"Lowy\", \"small\")\ncodez = Resturant(\"Codez\", \"medium\")\ntop_score = Resturant(\"Top Score\", \"large\")\n\n\nlowy.describe_resturant()\nprint()\ncodez.describe_resturant()\nprint()\ntop_score.describe_resturant()\n","sub_path":"Python/python-crash-course/try-it-yourself/chapter9/three_resturants.py","file_name":"three_resturants.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"269693056","text":"import re\n\n__author__ = \"Alfonso E. Romero\"\n__email__ = \"aeromero@cs.rhul.ac.uk\"\n__copyright__ = \"Copyright (c) 2013, Alfonso E. Romero\"\n__license__ = \"GPL\"\n\n\nclass IndexedReadOnlyFile(object):\n \"\"\" We provide a mechanism to easily access a set of blocks from\n a text file. We define a block as a set of lines starting with\n a string, matching a certain `regex`, and ending either with the\n following block, or with the EOF.\n\n Once initialized, the method `get_keys()` is available, returning\n the set of valid keys. To access the list of lines from an object\n \"obj\" of this class, we can now make obj[key]\n \"\"\"\n def __init__(self, file_name, regex):\n self.file_name = file_name\n self.regex = re.compile(regex)\n self.key_to_offset = self.__preload_cache()\n\n def get_keys(self):\n \"\"\" Return the set of keys which are accessible from this file.\n \"\"\"\n return self.key_to_offset.keys()\n\n def __getitem__(self, k):\n \"\"\" Returns the list of items (file lines) associated with\n a certain key. The line corresponding to the key is not\n returned (you should call `get_line_for_key` instead).\n If the key is not a valid key an empty line is returned.\n \"\"\"\n if k in self.key_to_offset:\n with open(self.file_name, 'r') as input_f:\n input_f.seek(self.key_to_offset[k], 0)\n output = []\n for line in input_f:\n line_strip = line.strip()\n if line_strip:\n output.append(line_strip)\n else:\n break\n return output\n else:\n return []\n\n def __preload_cache(self):\n \"\"\" Preloads the internal cache\n \"\"\"\n with open(self.file_name, 'r') as input_f:\n return dict((line.rstrip(), input_f.tell())\n for line in iter(input_f.readline, '')\n if self.regex.match(line))\n","sub_path":"gfam/indexed_file.py","file_name":"indexed_file.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"488804764","text":"# -*- coding:utf-8 -*-\n\n# 程序启动画面\n\n\"\"\"\n多大数应用程序启动时都会在程序完全启动时显示一个启动画面,在程序完全启动后消失。\n程序启动画面可以显示一些有关产品的信息,让用户在等待程序启动的同时了解有关产品的\n功能,也是一个宣传的方式。\nQSplashScreen 类提供了在程序启动过程中显示的启动画面的功能。本实例实现一个出现\n程序启动画面的例子。\n当运行程序时,在显示屏的中央出现一个启动画面,经过一段时间,应用程序完成初始化工\n作后,启动画面隐去,出现程序的主窗口界面,如下图所示。\n\n\"\"\"\n\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import *\nimport sys\nclass MainWindow(QMainWindow):\n\tdef __init__(self,parent=None):\n\t\tsuper(MainWindow,self).__init__(parent)\n\t\tself.setWindowTitle(\"Splash Example\")\n\t\tedit=QTextEdit()\n\t\tedit.setText(\"Splash Example\")\n\t\tself.setCentralWidget(edit)\n\t\tself.resize(600,450)\n\t\tQThread.sleep(1)\n\napp=QApplication(sys.argv)\nsplash=QSplashScreen(QPixmap(\"image/06.png\"))\nsplash.show()\napp.processEvents()\nwindow=MainWindow()\nwindow.show()\nsplash.finish(window)\napp.exec_()\n\n\n\"\"\"\n第 19 行利用 QPixmap 对象创建一个 QSplashScreen 对象。\n第 20 行调用 show()函数显示此启动图片。\n第 21 行调用 processEvents()使程序在显示启动画面的同时仍能响应鼠标等其他事件。\n第 22,23 行正常创建主窗体对象,并调用 show()函数显示。\n第 24 行调用 QSplashScreen 类的 finish()函数,表示在主窗体对象初始化完成后,结束启\n动画面。\n第 26 行正常地调用 exec_()函数。\n由于启动画面一般在当程序初始化时间较长的情况下出现,本实例中为了使程序初始化时间\n加长以显示启动画面,在主窗体的构造函数中调用 QThread.sleep()函数,使主窗口程序在\n初始化时休眠几秒钟\n\"\"\"\n\n","sub_path":"quick/python/qt4/26demo/23.py","file_name":"23.py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"22258100","text":"import numpy as np\nimport io\nimport base64\nfrom . import util\nimport copy\nfrom collections import defaultdict\nimport json\n\n# this file contains classes that define wrapper APIs for common data in the iris environment\n# for example, Models (predictive model) or Dataframes\n\n# wrapper for vega types (nothing special here, just an indicator to let frontent know this is vega data)\nclass IrisVega:\n type=\"Vega\"\n\n# define a vega schema for a bar chart\nclass IrisBar(IrisVega):\n def __init__(self, name, keys, data, bar_label=\"label\", value_label=\"value\"):\n self.name = name\n self.bar_label = bar_label\n self.value_label = value_label\n self.spec = {\n \"mark\": \"bar\",\n \"encoding\": {\n \"x\": {\"field\": self.bar_label, \"type\": \"nominal\"},\n \"y\": {\"field\": self.value_label, \"type\": \"quantitative\"}\n }\n }\n data_vals = []\n for i,k in enumerate(keys):\n obj = {}\n obj[self.bar_label] = k\n obj[self.value_label] = data[i]\n data_vals.append(obj)\n self.data = { \"values\": data_vals }\n\n# a wrapper for sklearn models\n# unlike sklean model classes, iris models keep track of the data over which they are defined\n# TODO: model.model is a bit weird\nclass IrisModel:\n type=\"Model\"\n # \"model\" is a sklearn model class\n def __init__(self, model, X, y, name=None):\n self.dataframe_X = X\n self.dataframe_y = y\n self.X = X.to_matrix()\n self.y = y.to_matrix()\n self.y = self.y.reshape(self.y.shape[0])\n self.model = model\n self.name = name\n def fit(self):\n self.model.fit(self.X, self.y)\n\n# simple wrapper for files in the iris environment\n# TODO: not good to read in all file content by default\n# TODO: should store full path\nclass IrisFile:\n type=\"File\"\n def __init__(self, name, content):\n self.name = name.split(\"/\")[-1]\n self.content = content\n\n# defines API for dataframes in Iris\n# TODO: this API is very important, so needs a lot of work\nclass IrisDataframe:\n type=\"DataFrame\"\n # \"column_names\" is ordered list of names associated with each column\n # \"column_types\" is ordered list of types associated with each column\n # \"data\" is a list of lists or ndarray (matrix) that holds the data\n # \"type_convert_data\" indicates whether the Dataframe should attempt automatic type inference\n def __init__(self, column_names=[], column_types=[], data=[], type_convert_data=False):\n self.column_names = column_names\n self.column_types = column_types\n if type_convert_data:\n self.data = self.convert_data(data)\n else:\n self.data = data\n self.cat2index = defaultdict(dict)\n\n # produce a data representation that the frontend can understand and display\n def generate_spreadsheet_data(self):\n # column data listing columns and types # TODO: key, name currently redundant\n column_data = [{\"key\":name, \"name\":name, \"type\":self.column_types[i]} for i,name in enumerate(self.column_names)]\n row_data = []\n # each row will be a dictionary mapping column name to value\n for row in self.data:\n row_data.append({self.column_names[i]:util.json_encode_df_type(d) for i,d in enumerate(row)})\n return json.dumps({\"column_data\":column_data, \"row_data\":row_data})\n\n # get a single column from the dataframe\n # TODO: likely unnecessary give dataframe-centric functions\n def get_column(self, name):\n indexes = {name:i for i, name in enumerate(self.column_names)}\n return np.array([row[indexes[name]] for row in self.data])\n\n # return matrix representation of underlying data\n def to_matrix(self):\n return np.array(self.data)#.T\n\n # copy a dataframe (only the provided columns)\n # \"conditions\" is an optional list of functions that can filter rows from the copied frame\n # to be included in the copy, a row must pass all condition functions\n # condition function: row => Bool\n def copy_frame(self, columns, conditions=[]):\n new_frame = copy.copy(self)\n new_frame.column_names = list(columns)\n new_frame.data = []\n new_frame.cat2index = {}\n indexes = {name:i for i, name in enumerate(self.column_names)}\n for i in range(0, len(self.data)):\n if all([f(self.data[i]) for f in conditions]):\n new_frame.data.append(list([self.data[i][indexes[c]] for c in new_frame.column_names]))\n for i,name in enumerate(new_frame.column_names):\n new_frame.cat2index[i] = dict(self.cat2index[indexes[name]])\n new_frame.column_types[i] = str(self.column_types[indexes[name]])\n return new_frame\n\n # map a function over the list of columns\n # function takes row[i][j] and can return anything\n # this function happens in place! so usually make a copy of the frame first\n def map_columns(self, columns, func):\n indexes = {name:i for i, name in enumerate(self.column_names)}\n columns_to_map = [indexes[column] for column in columns]\n types = defaultdict(set)\n for i in range(0, len(self.data)):\n for j in range(0, len(self.data[i])):\n if j in columns_to_map:\n new_v = func(self.data[i][j])\n types[j].add(util.detect_type(new_v))\n self.data[i][j] = new_v\n current_types = [x for x in self.column_types]\n # if the function produces a consistent type across the data in each column, then adjust the type label\n for i,col_typ in enumerate(current_types):\n if len(types[i]) == 1:\n current_types[i] = list(types[i])[0]\n self.column_types = current_types\n return self\n\n # convert a column to a new type\n # \"name\" is the name of the column\n # \"type_\" is the new type, for now either \"String\", \"Number\", or \"Categorical\"\n # this changes a dataframe in place!\n def change_type(self, name, type_):\n cat2index = {}\n def convert_type(value, type_):\n if type_ == \"String\":\n return str(value)\n elif type_ == \"Number\":\n return float(value)\n elif type_ == \"Categorical\":\n if not value in cat2index:\n cat2index[value] = len(cat2index)\n return cat2index[value]\n indexes = {name:i for i, name in enumerate(self.column_names)}\n for row in self.data:\n row[indexes[name]] = convert_type(row[indexes[name]], type_)\n self.column_types[indexes[name]] = type_\n self.cat2index[indexes[name]] = cat2index\n return self\n\n # create a copy of a dataframe with the columns in question removed\n def remove_column(self, names):\n return self.copy_frame([x for x in self.column_names if not x in names])\n\n # select rows across the dataframe where corresponding values in a column match an operation\n # e.g., \"filter dataframe to all rows with petal-length less than 2\"\n # creates a new copy of the dataframe\n def select_data(self, column, operation):\n indexes = {name:i for i, name in enumerate(self.column_names)}\n col_i = indexes[column]\n # capture the column index in a closure\n def selector(row):\n if(operation(row[col_i])):\n return True\n return False\n return self.copy_frame(self.column_names, conditions=[selector])\n\n # process an initial csv file and transform types\n # TODO: add error handling\n # TODO: probably let models handle categorical logic? think about this?\n def convert_data(self, data):\n new_data = []\n cat2index = defaultdict(dict)\n for j,line in enumerate(data):\n if line == '': continue # empty last line after new line\n old_row = util.split_line(line)\n new_row = []\n for i,value in enumerate(old_row):\n if self.column_types[i] == \"Number\":\n new_row.append(float(value))\n elif self.column_types[i] == \"Categorical\":\n if not value in cat2index[i]:\n cat2index[i][value] = len(cat2index[i])\n new_row.append(cat2index[i][value])\n else:\n new_row.append(value)\n new_data.append(new_row)\n self.cat2index = cat2index\n return new_data\n\n # export a dataframe to a string representation\n # TODO: this is really brittle, need to escape commas in quoted strings etc.\n def to_csv(self, file_path):\n header = \",\".join(self.column_names)\n data = \"\\n\".join([\",\".join([str(x) for x in row]) for row in self.data])\n with open(file_path, \"w\") as f:\n f.write(header+\"\\n\"+data)\n\n# a wrapper ior Iris functions\n# the reason we need this is that, by defauly, if an iris command returns another iris command\n# this will be interpreted as passing control to that function, e.g., calling it\nclass FunctionWrapper:\n def __init__(self, function, name=\"anonymous func\"):\n self.function = function\n self.name = name\n\n# references point to data in the iris environment\nclass EnvReference:\n def __init__(self, name):\n self.name = name\n def get_value(self, iris):\n return iris.env[self.name]\n","sub_path":"backend/iris/iris_objects.py","file_name":"iris_objects.py","file_ext":"py","file_size_in_byte":9391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"151800915","text":"import click, json, sh, threading, random, shutil, os, time\nfrom socket import *\n\n# Configure command line options\nDEFAULT_PORT_NUM = 6000\nJOB_NUMBERS = range(0, 10)\n\n@click.option(\"--port_number\", \"-p\", \"port_number\",\n default=DEFAULT_PORT_NUM,\n help=\"The port the master is listening on, default \" + str(DEFAULT_PORT_NUM))\n\ndef main():\n # Remove old job folders\n remove_directory(\"var\")\n remove_directory(\"./test_output_directory_a/\")\n remove_directory(\"./test_output_directory_b/\")\n output_dir = \"./test_output_directory_X/\"\n for j in JOB_NUMBERS:\n output_dir = change_second_to_last_index(output_dir, j)\n remove_directory(output_dir)\n\n # Temp job to send to master.\n # Values can (and should!) be changed\n job_dict_0 = {\n \"message_type\": \"new_master_job\",\n \"input_directory\": \"./input/sample1/\",\n \"output_directory\": \"./test_output_directory_a/\",\n \"mapper_executable\": \"./exec/word_count/map.py\",\n \"reducer_executable\": \"./exec/word_count/reduce.py\",\n \"num_mappers\": 4,\n \"num_reducers\": 2\n }\n \n\n job_dict_1 = {\n \"message_type\": \"new_master_job\",\n \"input_directory\": \"./input/sample1/\",\n \"output_directory\": \"./test_output_directory_b/\",\n \"mapper_executable\": \"./exec/grep/map.py\",\n \"reducer_executable\": \"./exec/grep/reduce.py\",\n \"num_mappers\": 4,\n \"num_reducers\": 2\n }\n\n send_job(job_dict_0)\n send_job(job_dict_1)\n #test_fault_tolerance(job_dict_0, job_dict_1) Not done implementing yet\n\ndef send_job(job_dict, port_number=DEFAULT_PORT_NUM):\n message = json.dumps(job_dict)\n # Send the data to the port that master is on\n try:\n sock = socket(AF_INET, SOCK_STREAM)\n sock.connect((\"localhost\", port_number))\n sock.sendall(str.encode(message))\n sock.close()\n except error:\n print(\"Failed to send job to master.\")\n\ndef test_fault_tolerance(job_dict_0, job_dict_1):\n new_random_workers_thread()\n start_new_jobs_thread(job_dict_0)\n start_new_jobs_thread(job_dict_1)\n\ndef start_new_jobs_thread(job_dict):\n thread = threading.Thread(target=new_jobs, args=(job_dict))\n thread.daemon = True\n thread.start()\n\ndef new_jobs(job_dict):\n for j in JOB_NUMBERS:\n # Cycle through output directory numbers\n job_dict[\"output_directory\"] = change_second_to_last_index(job_dict[\"output_directory\"], j)\n job_dict[\"num_mappers\"] = random.randint(0, 10)\n job_dict[\"num_mappers\"] = random.randint(0, 10)\n time.sleep(random.randint(0, 3))\n send_job(job_dict)\n\ndef start_new_daemon_thread(thread_target):\n thread = threading.Thread(target=thread_target)\n thread.daemon = True\n thread.start()\n\ndef change_second_to_last_index(string, new_char):\n str_list = list(string)\n str_list[-2] = str(new_char)\n return \"\".join(str_list)\n\ndef remove_directory(dir):\n if os.path.isdir(dir):\n shutil.rmtree(dir)\n\n'''\ndef new_random_workers():\n for x in range(1, 5):\n exe = sh.Command.bake(\"python worker.py\", args=(6000, 6000 + x))\n exe()\n'''\n\nif __name__ == \"__main__\":\n main()","sub_path":"send_job.py","file_name":"send_job.py","file_ext":"py","file_size_in_byte":3162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"560891773","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def minDepth(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n if not root:\n return 0\n\n depth = 0\n rootNode = [root]\n while rootNode:\n childNode = []\n \n depth = depth + 1\n \n for node in rootNode:\n if (not node.left) and (not node.right):\n return depth\n \n for root in rootNode:\n if root.left:\n childNode.append(root.left)\n\n if root.right:\n childNode.append(root.right)\n\n rootNode = childNode\n","sub_path":"minimum_depth_of_binary_tree.py","file_name":"minimum_depth_of_binary_tree.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"86430629","text":"# -*- coding: utf-8 -*-\n# -----------------------------------------------------------------------------\n# Author : yongchan jeon (Kris) poucotm@gmail.com\n# File : vlg_obfusc.py\n# Create : 2019-12-31 18:27:01\n# Editor : sublime text3, tab size (4)\n# -----------------------------------------------------------------------------\n\nimport sublime\nimport re\nimport os\nimport token, tokenize\n\n## _________________________________________________________\n## PythonObfusc _____________________________________________\n\nEXPFUNC = ['__init__','active_group','active_panel','active_sheet','active_sheet_in_group','active_view','active_view_in_group','active_window','add','add_all',\\\n 'add_on_change','add_regions','applies_to_primary_view_only','arch','begin','buffer_id','cache_path','cancel','change_count','classify','clear','clear_on_change',\\\n 'command_history','confirm','contains','cover','create_output_panel','decode_value','description','destroy_output_panel','em_width','empty','encode_value','encoding',\\\n 'end','erase','erase_regions','erase_status','error_message','expand_by_class','expand_variables','extract_scope','extract_variables','file_name','find','find_all',\\\n 'find_by_class','find_by_selector','find_open_file','find_output_panel','find_resources','focus_group','focus_sheet','focus_view','fold','folders','full_line','get',\\\n 'get_clipboard','get_macro','get_regions','get_sheet_index','get_status','get_tabs_visible','get_view_index','has','hide_popup','id','initial_text','input','insert',\\\n 'installed_packages_path','intersection','intersects','is_applicable','is_auto_complete_visible','is_checked','is_dirty','is_enabled','is_loading','is_menu_visible',\\\n 'is_minimap_visible','is_popup_visible','is_primary','is_read_only','is_scratch','is_sidebar_visible','is_status_bar_visible','is_visible','layout_extent','layout_to_text',\\\n 'layout_to_window','line','line_endings','line_height','lines','list_items','load_binary_resource','load_resource','load_settings','log_commands','log_input',\\\n 'log_result_regex','lookup_symbol_in_index','lookup_symbol_in_open_files','match_selector','message_dialog','name','new_file','next_input','num_groups','ok_cancel_dialog',\\\n 'on_activated','on_activated_async','on_clone','on_clone_async','on_close','on_deactivated','on_deactivated_async','on_hover','on_load','on_load_async','on_modified',\\\n 'on_modified_async','on_new','on_new_async','on_post_save','on_post_save_async','on_post_text_command','on_post_window_command','on_pre_close','on_pre_save',\\\n 'on_pre_save_async','on_query_completions','on_query_context','on_selection_modified','on_selection_modified_async','on_text_command','on_window_command','open_file',\\\n 'overwrite_status','packages_path','panels','Phantom','PhantomSet','placeholder','platform','preview','project_data','project_file_name','Region','replace',\\\n 'reset_reference_document','rowcol','run','run_command','save_settings','scope_name','score_selector','sel','set','set_clipboard','set_encoding','set_line_endings',\\\n 'set_menu_visible','set_minimap_visible','set_name','set_overwrite_status','set_project_data','set_read_only','set_reference_document','set_scratch','set_sheet_index',\\\n 'set_sidebar_visible','set_status','set_status_bar_visible','set_syntax_file','set_tabs_visible','set_timeout','set_timeout_async','set_view_index','set_viewport_position',\\\n 'settings','sheets','sheets_in_group','show','show_at_center','show_input_panel','show_popup','show_popup_menu','show_quick_panel','size','split_by_newlines','status_message',\\\n 'style','style_for_scope','substr','subtract','symbols','text_point','text_to_layout','text_to_window','unfold','update','update_popup','validate','version','view',\\\n 'viewport_extent','viewport_position','views','views_in_group','visible_region','want_event','window','window_to_layout','window_to_text','windows','word','yes_no_cancel_dialog']\n\nHEADRRE = re.compile(r'^#.*\\n')\nDRCTVRE = re.compile(r'^#`(?P[\\w]+)[\\s]*(?P[\\w\\.]*)[\\s]*\\n')\n\n# Q3STRRE = re.compile(r'(?P\\\"\\\"\\\"|\\'\\'\\').*?(?[\\'\\\"]).*?(?[a-zA-Z_][\\w]*)[\\t ]*(?=\\()')\nFUNCTRE = re.compile(r'\\b(?P[a-zA-Z_][\\w]*)\\b')\n\nSPACERE = re.compile(r'(?<=\\w)\\s*(?=\\()')\nIMPRTRE = re.compile(r'\\bimport[\\s]+(?P[\\w]+)')\nPARENRE = re.compile(r'\\(.*\\)')\nDFVARRE = re.compile(r'\\b(?P[a-zA-Z_][\\w\\.]*)[\\t ]*(?=[\\=][^\\=])')\nVARBLRE = re.compile(r'\\b(?P[a-zA-Z_][\\w\\.]*)\\b')\n\n\nclass PythonObfusc():\n\n # hash settings\n HASHSTR = \"\"\n HASHNUM = 0\n\n ## get_text _________________________________________________\n\n @staticmethod\n def get_text(fname):\n \"\"\" get header, directives, content \"\"\"\n heads = ''\n rtext = ''\n headb = True\n excpl = []\n addfl = []\n addvl = []\n protc = False\n with open(fname, 'r', encoding=\"utf8\") as fpr:\n for line in fpr:\n drctm = DRCTVRE.match(line)\n if headb and drctm:\n drcts = drctm.group('directive')\n if drcts == 'protect':\n protc = True\n elif drcts == 'except':\n excpl.append(drctm.group('content'))\n elif drcts == 'addfun':\n addfl.append(drctm.group('content'))\n elif drcts == 'addvar':\n addvl.append(drctm.group('content'))\n heads += line\n else:\n headm = HEADRRE.match(line)\n if headb and headm:\n heads += line\n else:\n headb = False\n rtext += line\n return heads, protc, excpl, addfl, addvl, rtext\n\n ## tokenize _________________________________________________\n\n @staticmethod\n def tokenize(fname):\n \"\"\" remove comments, get strings \"\"\"\n rtext = ''\n q3str = []\n q1str = []\n with open(fname, 'r', encoding=\"utf8\") as fpr:\n ptype = token.INDENT\n lastn = -1\n lastc = 0\n tokgn = tokenize.generate_tokens(fpr.readline)\n for ttype, ttext, (slin, scol), (elin, ecol), ltext in tokgn:\n if slin > lastn:\n lastc = 0\n if scol > lastc:\n rtext += ' ' * (scol - lastc)\n if ttype == token.STRING and ptype == token.INDENT:\n # remove Docstring\n pass\n elif ttype == tokenize.COMMENT:\n # remove Comment\n pass\n elif ttype == token.STRING:\n if ttext[0:3] == '\"\"\"' or ttext[0:3] == \"'''\":\n q3str.append(ttext)\n rtext += '!' + '-' * (len(ttext)-2) + '!'\n else:\n q1str.append(ttext)\n rtext += '~' + '-' * (len(ttext)-2) + '~'\n else:\n rtext += ttext\n ptype = ttype\n lastc = ecol\n lastn = elin\n # remove empty lines\n rtext = re.sub(re.compile(r\"\\s*[\\r\\n]\"), \"\\n\", rtext)\n return rtext, q3str, q1str\n\n ## apply_hash _______________________________________________\n\n @staticmethod\n def apply_hash(fsig, mode, s):\n global HASHSTR, HASHNUM\n fsign = \"\"\n stlen = len(HASHSTR)\n for idx in range(0, len(fsig)):\n alp = False\n for sidx in range(0, stlen):\n if fsig[idx] == HASHSTR[sidx]:\n if mode:\n hidx = (idx + sidx + HASHNUM + (10 * s)) % stlen\n else: # reverse\n hidx = (sidx + (stlen - idx - HASHNUM - (10 * s))) % stlen\n fsign += HASHSTR[hidx]\n alp = True\n if not alp:\n fsign += fsig[idx]\n return fsign\n\n ## get_setting ______________________________________________\n\n @staticmethod\n def get_setting():\n return sublime.load_settings('pobfusc.sublime-settings')\n\n ## obfuscate ________________________________________________\n\n @staticmethod\n def obfuscate(fname, optdir, optcmt, protect=False, postfix='_obfc', optlist=False):\n \"\"\" obfuscate a file w/ options \"\"\"\n\n global HASHSTR, HASHNUM\n\n # read a header and directives\n heads, protc, excpl, addfl, addvl, codes = PythonObfusc.get_text(fname)\n\n ## obfuscate as runnable ____________________________________\n if not protc and not protect:\n\n # remove comments, get strings\n codes, q3str, q1str = PythonObfusc.tokenize(fname)\n\n # getting HASH type 0\n HASHSTR = PythonObfusc.get_setting().get('hash_str0', '')\n HASHNUM = PythonObfusc.get_setting().get('hash_num', 0)\n\n # remove space abc ()\n codes = re.sub(SPACERE, '', codes)\n\n # get import list\n impts = set()\n for m in IMPRTRE.finditer(codes):\n imps = m.group('import')\n impts.add((imps+'.'))\n imptl = list(impts)\n\n # get function names\n funcs = set()\n for m in DFFUNRE.finditer(codes):\n func = m.group('func')\n if not func in excpl and len(func) > 2:\n funcs.add(func)\n for addf in addfl:\n funcs.add(addf)\n funcl = list(funcs)\n\n # get variable names\n varis = set()\n codev = re.sub(PARENRE, '()', codes)\n for m in DFVARRE.finditer(codev):\n vari = m.group('var')\n obfo = True\n for imps in imptl:\n if vari.startswith(imps):\n obfo = False\n break\n if obfo:\n varilen = len(vari)\n varit = varis.copy()\n for varc in varit:\n if varilen > len(varc):\n if vari.startswith((varc+'.')):\n obfo = False\n break\n elif varilen < len(varc):\n if varc.startswith(vari+'.'):\n varis.remove(varc)\n break\n if obfo and not vari in funcl and not vari in excpl and len(vari) > 2:\n varis.add(vari)\n for addv in addvl:\n varis.add(addv)\n varil = list(varis)\n\n # change function names\n for m in FUNCTRE.finditer(codes):\n func = m.group('func')\n if func in funcl and not func in EXPFUNC:\n obfc = PythonObfusc.apply_hash(func, optdir, 0)\n codes = codes[:m.start()] + obfc + codes[m.end():]\n\n # change variable names\n len_codes = len(codes)\n for m in VARBLRE.finditer(codes):\n vari = m.group('var')\n varilen = len(vari)\n for varc in varil:\n varclen = len(varc)\n befolen = len(codes)\n if varc == vari:\n eles = [i for i in varc.split('.') if i != '']\n obfc = PythonObfusc.apply_hash(eles[-1], optdir, 0)\n repls = varc[:-len(obfc)] + obfc\n codes = codes[:m.start()] + repls + codes[m.end():]\n elif varilen > varclen and vari.startswith(varc+'.'):\n eles = [i for i in varc.split('.') if i != '']\n obfc = PythonObfusc.apply_hash(eles[-1], optdir, 0)\n repls = varc[:-len(obfc)] + obfc + vari[varclen:]\n codes = codes[:m.start()] + repls + codes[m.end():]\n aftrlen = len(codes)\n if befolen != aftrlen:\n raise RuntimeError('obfuscate length mismatch')\n\n # restore quoted strings\n for i, m in enumerate(Q3REPRE.finditer(codes)):\n codes = codes[:m.start()] + q3str[i] + codes[m.end():]\n for i, m in enumerate(Q1REPRE.finditer(codes)):\n codes = codes[:m.start()] + q1str[i] + codes[m.end():]\n\n ## obfuscate as protect mode ________________________________\n else:\n\n # encrypt (protect) - overwrite/ignore changing names and removing comments\n HASHSTR = PythonObfusc.get_setting().get('hash_str1', '')\n HASHNUM = PythonObfusc.get_setting().get('hash_num', 0) + ord(os.path.basename(fname)[0][0])\n\n codee = ''\n nline = 0\n textl = re.compile(r\".*[\\r\\n]|.*$\").findall(codes)\n for _txt in textl:\n codee += PythonObfusc.apply_hash(_txt, optdir, nline)\n nline += 1\n codes = codee\n\n # file write\n fname_c = fname + postfix\n with open(fname_c, \"w\", newline=\"\", encoding=\"utf8\") as fpw:\n fpw.write(heads)\n fpw.write(codes)\n\n return\n","sub_path":"main/pyt_obfusc.py","file_name":"pyt_obfusc.py","file_ext":"py","file_size_in_byte":13505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"259990931","text":"import matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport numpy as np\nfrom PIL import Image\nimport pickle\nimport os\nimport h_gen\nimport threading\n\n\ndef to_categorical(label_s, nb_classes):\n \"\"\" One hot encode a vector, or a list of list of labels\"\"\"\n try:\n l = len(label_s)\n vector = np.zeros((l, nb_classes))\n for i in range(l):\n vector[i, int(label_s[i])] = 1\n\n except TypeError:\n\n vector = np.zeros(nb_classes)\n vector[label_s] = 1\n return vector\n\n\ndef display_from_meta(dic):\n \"\"\" Given the metadata of an image, we plot everything we can concerning\n this image.\"\"\"\n rectangles = []\n points = []\n first = False\n\n if \"rectangles\" in dic:\n rectangles = dic[\"rectangles\"]\n if \"head_tail\" in dic:\n points = dic[\"head_tail\"]\n if \"ht_first\" in dic:\n first = dic[\"ht_first\"]\n display_image(dic[\"path\"], rectangles, points, first)\n\n\ndef display_image(path, rectangles=[], points=[], first=False):\n im = np.array(Image.open(path), dtype=np.uint8)\n\n # Create figure and axes\n fig, ax = plt.subplots(1)\n\n # Display the image\n ax.imshow(im)\n\n for i, rec in enumerate(rectangles):\n # Create a Rectangle patch\n rect = patches.Rectangle((rec[\"x\"], rec[\"y\"]), rec[\"width\"], rec[\"height\"],\n linewidth=1, edgecolor='r', facecolor='none')\n\n if first and i == 0:\n rect = patches.Rectangle((rec[\"x\"], rec[\"y\"]), rec[\"width\"], rec[\"height\"],\n linewidth=1, edgecolor='b', facecolor='none')\n\n # Add the patch to the Axes\n ax.add_patch(rect)\n\n for point in points:\n # Create a Rectangle patch filled\n rect = patches.Rectangle((point[\"x\"] - 2, point[\"y\"] - 2), 4, 4,\n linewidth=3, edgecolor='b', facecolor='none')\n # Add the patch to the Axes\n ax.add_patch(rect)\n\n plt.show()\n\n\ndef save(variable, path):\n with open(path, \"wb\") as f:\n pickle.dump(variable, f, pickle.HIGHEST_PROTOCOL)\n\n\ndef save_array(arr, fname):\n np.save(fname, arr)\n\n\ndef load(path):\n with open(path, \"rb\") as f:\n variable = pickle.load(f)\n return variable\n\n\ndef load_array(fname):\n return np.load(fname + \".npy\")\n\n\n# Create a directory if it doesn't exist\ndef mk(directory):\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n\ndef split_train_test(nb_images, train_dir):\n \"\"\" Use case : split_train_test(5,\"boats_id_train/\")\"\"\"\n temp = train_dir.find(\"train\")\n test_dir = train_dir[:temp] + \"test\" + train_dir[temp + 5:]\n\n if not os.path.exists(test_dir):\n os.makedirs(test_dir)\n\n classes = os.listdir(train_dir)\n\n train_dir = [train_dir + x + \"/\" for x in classes]\n test_dir = [test_dir + x + \"/\" for x in classes]\n\n for folder in test_dir:\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n for train_class, test_class in zip(train_dir, test_dir):\n files = os.listdir(train_class)[:nb_images]\n for file in files:\n copyfile(train_class + file, test_class + file)\n os.remove(train_class + file)\n\n\ndef display_mask(m, mask=None):\n im = np.array(Image.open(m[\"path\"]), dtype=np.uint8)\n if mask is None:\n mask = h_gen.get_mask(m)\n im2 = Image.fromarray(mask * 255)\n im2 = im2.resize((m[\"width\"], m[\"height\"]), Image.ANTIALIAS)\n plt.imshow(im)\n plt.imshow(im2, alpha=0.2)\n plt.show()\n\n\nclass threadsafe_iter:\n \"\"\"Takes an iterator/generator and makes it thread-safe by\n serializing call to the `next` method of given iterator/generator.\n \"\"\"\n\n def __init__(self, it):\n self.it = it\n self.lock = threading.Lock()\n\n def __iter__(self):\n return self\n\n def __next__(self):\n with self.lock:\n return self.it.__next__()\n\n\ndef apply_augmentations(batch, image_data_generator):\n for i in range(batch.shape[0]):\n batch[i] = image_data_generator.random_transform(batch[i])\n batch[i] = image_data_generator.standardize(batch[i])\n return batch\n","sub_path":"fish/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"376565894","text":"# -*- coding:utf-8 -*-\n\nfrom PyQt5 import QtCore, QtWidgets\n\n\nclass Thread1(QtCore.QThread):\n s1 = QtCore.pyqtSignal(int)\n\n def __init__(self):\n QtCore.QThread.__init__(self)\n self.count = 0\n\n def run(self):\n for i in range(1, 21):\n self.count += 1\n QtCore.QThread.sleep(1)\n self.s1.emit(self.count)\n\n\nclass Thread2(QtCore.QThread):\n s2 = QtCore.pyqtSignal(str)\n\n def __init__(self):\n QtCore.QThread.__init__(self)\n self.count = 0\n\n def run(self):\n self.exec_()\n\n def on_change(self, i):\n self.s2.emit(\"Thread2 is received: %s\" % i)\n\n\nclass MyWindow(QtWidgets.QWidget):\n def __init__(self):\n try:\n QtWidgets.QWidget.__init__(self)\n self.label_1 = QtWidgets.QLabel()\n self.label_2 = QtWidgets.QLabel()\n self.button = QtWidgets.QPushButton(\"Запустить обмен\")\n self.vbox = QtWidgets.QVBoxLayout()\n self.vbox.addWidget(self.label_1)\n self.vbox.addWidget(self.label_2)\n self.vbox.addWidget(self.button)\n self.setLayout(self.vbox)\n\n self.thread1 = Thread1()\n self.thread2 = Thread2()\n self.button.clicked.connect(self.on_click)\n self.thread1.s1.connect(self.on_show1,QtCore.Qt.QueuedConnection)\n self.thread1.s1.connect(self.thread2.on_change) #сигнал s1 соединен с методом on_change другого потока\n self.thread2.s2.connect(self.on_show2, QtCore.Qt.QueuedConnection)\n except Exception as err:\n print(err)\n\n def on_click(self):\n try:\n self.thread1.start()\n self.thread2.start()\n self.button.setDisabled(True)\n except Exception as err:\n print(err)\n\n def on_show1(self, i):\n try:\n self.label_1.setText(str(i))\n except Exception as err:\n print(err)\n\n def on_show2(self, str):\n self.label_2.setText(str)\n\n\nif __name__ == \"__main__\":\n import sys\n\n app = QtWidgets.QApplication(sys.argv)\n\n window = MyWindow()\n window.resize(300, 300)\n window.show()\n\n sys.exit(app.exec_())\n","sub_path":"SignalsInThreads.py","file_name":"SignalsInThreads.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"478998702","text":"#! /user/bin/env python3\n# -*- coding:utf-8 -*-\n'''\nclass后面紧接着是类名,即Student,类名通常是大写开头的单词,紧接着是(object),\n表示该类是从哪个类继承下来的,继承的概念我们后面再讲,\n通常,如果没有合适的继承类,就使用object类,这是所有类最终都会继承的类。\n'''\nclass Student(object):\n #注意:特殊方法“init”前后有两个下划线!!!\n #注意到__init__方法的第一个参数永远是self,表示创建的实例本身,\n # 因此,在__init__方法内部,就可以把各种属性绑定到self,因为self就指向创建的实例本身。\n def __init__(self,name,code):\n self.name=name\n self.code=code\n def other_function(self,name,code):\n #就是第一个参数永远是实例变量self\n self.hehe=\"baidu\"#任何地方植入变量\n print(name,code)\n return \"谢谢使用\"\nvar=Student('lilang','89')\nprint(var.other_function(var.name,var.code))\nprint(var.hehe)\n#访问限制\nprint(dir(Student))","sub_path":"类.py","file_name":"类.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"519112907","text":"from functools import partial\r\nfrom six.moves import xrange\r\n\r\nfrom ortools.constraint_solver import pywrapcp\r\nfrom ortools.constraint_solver import routing_enums_pb2\r\n\r\nimport sys\r\nimport json5\r\n\r\ndef create_data_model(raw_data):\r\n # km\r\n # _locations = [\r\n # (4, 4), # depot\r\n # (8, 0), # locations to visit\r\n # (2, 0),\r\n # ]\r\n # # 转换成 m\r\n # data['locations'] = [(l[0] * 1000, l[1] * 1000) for l in _locations]\r\n raw_data['num_locations'] = len(raw_data['locations'])\r\n \r\n # 吨\r\n # _demands = [0, # depot\r\n # 1, 1] # 1, 2\r\n \r\n # # 千克\r\n # data['demands'] = [l * 1000 for l in _demands]\r\n\r\n # 车的数量及最大载重\r\n _capacity = [3000]\r\n raw_data['vehicle_capacity'] = [l * 1000 for l in raw_data['vehicle_capacity']]\r\n raw_data['num_vehicles'] = len(raw_data['vehicle_capacity'])\r\n\r\n # 每个配送点下货所需时间(分钟)\r\n # data['time_per_location'] = 5\r\n\r\n # 每个配送点的时间窗口(分钟)\r\n # data['time_windows'] = \\\r\n # [(0, 0), # depot\r\n # (0, 10000), (0, 8500)]\r\n\r\n # 速度(m/min)\r\n # data['vehicle_speed'] = 10 * 60 / 3.6\r\n \r\n raw_data['depot'] = 0\r\n \r\n # 最大里程(m)\r\n # data['max_dis_per_vehicle'] = 35 * 1000;\r\n\r\n # 最大工作时间\r\n raw_data['max_time_per_vehicle'] = 8 * 60\r\n\r\n return raw_data\r\n\r\n\r\n# 计算两点曼哈顿距离\r\ndef manhattan_distance(position_1, position_2):\r\n return (abs(position_1[0] - position_2[0]) +\r\n abs(position_1[1] - position_2[1]))\r\n\r\n\r\ndef create_distance_evaluator(data):\r\n _distances = {}\r\n # 预处理距离矩阵\r\n for from_node in xrange(data['num_locations']):\r\n _distances[from_node] = {}\r\n for to_node in xrange(data['num_locations']):\r\n if from_node == to_node:\r\n _distances[from_node][to_node] = 0\r\n else:\r\n _distances[from_node][to_node] = (manhattan_distance(\r\n data['locations'][from_node], data['locations'][to_node]))\r\n\r\n\r\n def distance_evaluator(manager, from_node, to_node):\r\n \"\"\"Returns the manhattan distance between the two nodes\"\"\"\r\n return _distances[manager.IndexToNode(from_node)][manager.IndexToNode(\r\n to_node)]\r\n\r\n return distance_evaluator\r\n\r\n\r\ndef add_distance_dimension(routing, distance_evaluator_index, data):\r\n distance = 'Distance'\r\n routing.AddDimension(\r\n distance_evaluator_index,\r\n 0, # null slack\r\n data['max_dis_per_vehicle'], # 车辆最大里程\r\n True,\r\n distance)\r\n distance_dimension = routing.GetDimensionOrDie(distance)\r\n # 使最长里程尽可能短\r\n distance_dimension.SetGlobalSpanCostCoefficient(100)\r\n\r\n\r\ndef create_demand_evaluator(data):\r\n _demands = data['demands']\r\n\r\n def demand_evaluator(manager, from_node):\r\n \"\"\"Returns the demand of the current node\"\"\"\r\n return _demands[manager.IndexToNode(from_node)]\r\n\r\n return demand_evaluator\r\n\r\n\r\ndef add_capacity_constraints(routing, manager, data, demand_evaluator_index):\r\n routing.AddDimensionWithVehicleCapacity(\r\n demand_evaluator_index,\r\n 0, # Null slack\r\n data['vehicle_capacity'],\r\n True, # start cumul to zero\r\n 'Capacity')\r\n\r\n\r\ndef create_time_evaluator(data):\r\n def service_time(data, node):\r\n # 每个服务点的下货时间\r\n return data['time_per_location']\r\n\r\n def travel_time(data, from_node, to_node):\r\n # 路径的用时\r\n if from_node == to_node:\r\n travel_time = 0\r\n else:\r\n travel_time = manhattan_distance(data['locations'][\r\n from_node], data['locations'][to_node]) / data['vehicle_speed']\r\n return travel_time\r\n\r\n # 时间矩阵\r\n _total_time = {}\r\n for from_node in xrange(data['num_locations']):\r\n _total_time[from_node] = {}\r\n for to_node in xrange(data['num_locations']):\r\n if from_node == to_node:\r\n _total_time[from_node][to_node] = 0\r\n else:\r\n _total_time[from_node][to_node] = int(\r\n service_time(data, from_node) + travel_time(\r\n data, from_node, to_node))\r\n\r\n def time_evaluator(manager, from_node, to_node):\r\n return _total_time[manager.IndexToNode(from_node)][manager.IndexToNode(\r\n to_node)]\r\n\r\n return time_evaluator\r\n \r\n\r\ndef add_time_window_constraints(routing, manager, data, time_evaluator):\r\n time = 'Time'\r\n routing.AddDimension(\r\n time_evaluator,\r\n data['max_time_per_vehicle'], # allow waiting time\r\n data['max_time_per_vehicle'], # maximum time per vehicle\r\n False, # don't force start cumul to zero since we are giving TW to start nodes\r\n time)\r\n time_dimension = routing.GetDimensionOrDie(time)\r\n\r\n # 对各个 location 加入时间窗口\r\n for location_idx, time_window in enumerate(data['time_windows']):\r\n if location_idx == 0:\r\n continue\r\n index = manager.NodeToIndex(location_idx)\r\n time_dimension.CumulVar(index).SetRange(time_window[0], time_window[1])\r\n routing.AddToAssignment(time_dimension.SlackVar(index))\r\n\r\n for vehicle_id in xrange(data['num_vehicles']):\r\n index = routing.Start(vehicle_id)\r\n time_dimension.CumulVar(index).SetRange(data['time_windows'][0][0],\r\n data['time_windows'][0][1])\r\n routing.AddToAssignment(time_dimension.SlackVar(index))\r\n\r\n # 选择性加入,让车尽早出发\r\n # for i in range(data['num_vehicles']):\r\n # routing.AddVariableMinimizedByFinalizer(\r\n # time_dimension.CumulVar(routing.Start(i)))\r\n # routing.AddVariableMinimizedByFinalizer(\r\n # time_dimension.CumulVar(routing.End(i)))\r\n\r\ndef print_solution(data, manager, routing, assignment): # pylint:disable=too-many-locals\r\n \"\"\"Prints assignment on console\"\"\"\r\n result = {}\r\n # print('Objective: {}'.format(assignment.ObjectiveValue()))\r\n\r\n total_distance = 0\r\n total_load = 0\r\n total_time = 0\r\n capacity_dimension = routing.GetDimensionOrDie('Capacity')\r\n time_dimension = routing.GetDimensionOrDie('Time')\r\n dropped = []\r\n for order in xrange(0, routing.nodes()):\r\n index = manager.NodeToIndex(order)\r\n if assignment.Value(routing.NextVar(index)) == index:\r\n dropped.append(order)\r\n # print('dropped orders: {}'.format(dropped))\r\n\r\n result['dropped'] = dropped\r\n \r\n routes = []\r\n result['routes'] = routes\r\n\r\n for vehicle_id in xrange(data['num_vehicles']):\r\n index = routing.Start(vehicle_id)\r\n plan_output = 'Route for vehicle {}:\\n'.format(vehicle_id)\r\n \r\n route = {}\r\n route['vehicle_idx'] = vehicle_id\r\n sub_route = []\r\n route['sub_route'] = sub_route\r\n\r\n distance = 0\r\n while not routing.IsEnd(index):\r\n load_var = capacity_dimension.CumulVar(index)\r\n time_var = time_dimension.CumulVar(index)\r\n plan_output += ' {0} Load({1}) Time({2},{3}) ->'.format(\r\n manager.IndexToNode(index),\r\n assignment.Value(load_var),\r\n assignment.Min(time_var), assignment.Max(time_var))\r\n \r\n # 地点,装货,出发时间\r\n sub_route.append({\r\n 'from': manager.IndexToNode(index), \r\n 'time_window': [assignment.Min(time_var), assignment.Max(time_var)]\r\n }) \r\n\r\n previous_index = index\r\n index = assignment.Value(routing.NextVar(index))\r\n distance += routing.GetArcCostForVehicle(previous_index, index,\r\n vehicle_id)\r\n load_var = capacity_dimension.CumulVar(index)\r\n time_var = time_dimension.CumulVar(index)\r\n plan_output += ' {0} Load({1}) Time({2},{3})\\n'.format(\r\n manager.IndexToNode(index),\r\n assignment.Value(load_var),\r\n assignment.Min(time_var), assignment.Max(time_var))\r\n \r\n sub_route.append({\r\n 'from': manager.IndexToNode(index), \r\n 'time_window': [assignment.Min(time_var), assignment.Max(time_var)]\r\n })\r\n \r\n plan_output += 'Distance of the route: {}m\\n'.format(distance)\r\n plan_output += 'Load of the route: {}\\n'.format(\r\n assignment.Value(load_var))\r\n plan_output += 'Time of the route: {}min\\n'.format(\r\n assignment.Value(time_var))\r\n # print(plan_output)\r\n total_distance += distance\r\n total_load += assignment.Value(load_var)\r\n total_time += assignment.Value(time_var)\r\n\r\n route['route_dis'] = distance\r\n route['route_load'] = assignment.Value(load_var)\r\n\r\n if len(route['sub_route']) > 2:\r\n routes.append(route)\r\n \r\n\r\n # print('Total Distance of all routes: {}m'.format(total_distance))\r\n # print('Total Load of all routes: {}'.format(total_load))\r\n # print('Total Time of all routes: {}min'.format(total_time))\r\n\r\n result['total_distance'] = total_distance\r\n result['total_load'] = total_load\r\n result['total_time'] = total_time\r\n\r\n print(result)\r\n\r\n\r\ndef main(raw_data):\r\n data = create_data_model(raw_data)\r\n manager = pywrapcp.RoutingIndexManager(data['num_locations'],\r\n data['num_vehicles'], data['depot'])\r\n routing = pywrapcp.RoutingModel(manager)\r\n\r\n # distance dimension\r\n distance_evaluator_index = routing.RegisterTransitCallback(\r\n partial(create_distance_evaluator(data), manager))\r\n routing.SetArcCostEvaluatorOfAllVehicles(distance_evaluator_index)\r\n add_distance_dimension(routing, distance_evaluator_index, data)\r\n\r\n # capacity constraint\r\n demand_evaluator_index = routing.RegisterUnaryTransitCallback(\r\n partial(create_demand_evaluator(data), manager))\r\n add_capacity_constraints(routing, manager, data, demand_evaluator_index)\r\n\r\n # Time Window constraint\r\n time_evaluator_index = routing.RegisterTransitCallback(\r\n partial(create_time_evaluator(data), manager))\r\n add_time_window_constraints(routing, manager, data, time_evaluator_index)\r\n\r\n search_parameters = pywrapcp.DefaultRoutingSearchParameters()\r\n search_parameters.first_solution_strategy = (\r\n routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC) # pylint: disable=no-member\r\n # Solve the problem.\r\n assignment = routing.SolveWithParameters(search_parameters)\r\n if assignment:\r\n print_solution(data, manager, routing, assignment)\r\n else:\r\n print(\"error\")\r\n \r\nif __name__ == '__main__':\r\n data = sys.argv[1]\r\n data = json5.loads(data)\r\n # print(data)\r\n main(data)","sub_path":"solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":10915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"454810474","text":"from numpy import *\r\nimport scipy.linalg\r\nimport scipy.stats\r\r\n\r\n#the math used in this is heavily inspired by the article:\r\n#A Python Implementation of Chan's TDoA algorithm\r\n#for Ultrasonic Positioning and Tracking\r\n\r\n#otherwise, the methods and implementation are written by Thomas Schouten\r\n\r\n\r\nmicPos = array([[ 1., 0.],\r\n\t\t[-1., 0.],\r\n\t\t[-1.,-1.]])\r\nc = 340.29\r\nn = 3\r\n\r\ndef testPos(x,y):\t#used to test the algorithm\r\n\ttime = empty((n,1))\r\n\tfor j in range(n):\r\n\t\td = ((micPos[j,0]-x)**2+(micPos[j,1]-y)**2)**.5\r\n\t\ttime[j,0] = d/c\r\n\r\n\treturn getPosFromTimes(time)\r\n\r\ndef getPosFromTimes(time):\t#the main method to call, this takes a matrix of detected times, and return position data\r\n\tposT = concatenate((micPos, time),1)\r\n\tdD = getDeltaDistance(posT)\r\n\tpos = findPos(dD)\r\n\tif len(pos) == 2:\r\n\t\tr0 = pos[0][1]\r\n\t\tr1 = pos[1][1]\r\n\t\tif r0 < r1:\r\n\t\t\tpos = pos[1]\r\n\t\telse:\r\n\t\t\tpos = pos[0]\r\n\telif len(pos) == 1:\r\n\t\tpos = pos[0]\r\n\treturn pos\r\n\t\r\ndef findPos(dD):\t#this is where the majority of the localization algorithm resides\r\n\tP = dD[1:3,0:2] - dD[0,0:2]\r\n\tA = -linalg.inv(P)\r\n\tR = dD[1:3,2]\r\n\tR2 = R[:]**2\r\n\tM = dD[:,0:2]\r\n\tK = dD[:,0]**2+dD[:,1]**2\r\n\tB = (R2 - K[1:3] + K[0]) / 2\r\n\tE = A.dot(R)\r\n\tF = A.dot(B)\r\n\ta = 1 - (E.dot(E))\r\n\tb = 2 * (M[0].dot(E) - F.dot(E))\r\n\tc = 2 * (M[0].dot(F)) - F.dot(F) - K[0]\r\n\tdiscr = b * b - 4 * a * c\r\n\tposlist = []\r\n\tif discr >= 0:\r\n\t\th = discr**.5\r\n\t\tfor i in (h, -h):\r\n\t\t\tR0 = (i - b) / (2 * a)\r\n\t\t\tif R0 >= 0:\r\n\t\t\t\tT = E * R0 + F\r\n\t\t\t\tposlist.append((squeeze(T), R0)) \t\r\n\treturn poslist\r\r\r\n\r\ndef getDeltaDistance(posT):\t#this establishes a proper matrix for the algorithm, by getting the change in distance rather than time\r\n\tA = posT[posT[:,2].argsort()]\r\n\tA[:,2] -= A[:,2].min()\r\n\tA[:,2] = A[:,2]*c\r\n\treturn A","sub_path":"local.py","file_name":"local.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"282842365","text":"from flask import Flask, render_template, request, abort\nfrom models import db, whooshee, Minwon, set_queryTopic, district_stats, monthly_topic_stats, init_distructNum\nfrom konlpy.tag import Mecab\nimport sqlite3\nimport pandas as pd\n\nfrom sklearn.externals import joblib\n\n\n\nlda = joblib.load(\"minwon_lda.pkl\")\nquery_tf = joblib.load('minwon_query_tf.pkl')\n\n\nmecab = Mecab()\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.config['WHOOSHEE_MIN_STRING_LEN'] = 2\ndb.init_app(app)\nwhooshee.init_app(app)\n\ncon = sqlite3.connect(\"data.db\")\ncur = con.cursor()\ncur.execute(\"SELECT date FROM minwon_collection order by date desc limit 1\")\nlatest = cur.fetchone()\nstarting = latest[0].replace(latest[0][3],str(int(latest[0][3])-1))\nquery = \"SELECT id,d_num,topic,date FROM minwon_collection WHERE date > \\\"{0}\\\"\".format(starting)\ndata = pd.read_sql(query,con)\ncon.close()\ndata.d_num = data.d_num.map(lambda x :init_distructNum(x))\nprint(len(data),\"불러오기 완료\")\n\n@app.route('/')\ndef begin():\n # whooshee.reindex()\n return render_template(\"index.html\")\n\n@app.route('/results', methods=['POST'])\ndef results():\n\n if request.method == 'POST':\n search = request.form.get('search','None')\n if len(search) < 2:\n search='None'\n if search=='None':\n abort(403)\n\n search_ = search+\" \"+ \" \".join([_[0] for _ in mecab.pos(search) if (_[1].startswith(\"N\")\n or _[1].startswith(\"SL\")\n or _[1].startswith(\"SN\")\n ) and len(_[0])>1])\n\n topic = set_queryTopic(search_,lda,query_tf)\n\n minwons = Minwon.query.whooshee_search(search_, limit=100).order_by(Minwon.date.desc()).all()\n\n stats = district_stats(data,topic)\n\n\n return render_template(\"results.html\",search=search,opinions=minwons,num=len(minwons),topic=topic,stats=stats)\n\n else:\n abort(403)\n\n\n@app.route('/view_detail/')\ndef view_detail(id):\n con = sqlite3.connect(\"data.db\")\n cur = con.cursor()\n query = \"SELECT * FROM minwon_indexed WHERE id = {0}\".format(id)\n cur.execute(query)\n result = cur.fetchone()\n con.close()\n\n return render_template(\"view_detail.html\",r=result)\n\n\n\n\n@app.route('/monthly_data', methods=[\"POST\"])\ndef draw_monthly_graph():\n if request.method == \"POST\":\n name = request.form.get(\"name\")\n topic = request.form.get(\"topic\")\n\n\n json_result = monthly_topic_stats(data, name, int(topic))\n\n\n\n\n\n\n\n return json_result\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"web/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"81822018","text":"\"\"\"\nauthor: hxtkyne\nsource: https://github.com/hxtkyne\nreference: deep learning with python\ndate: 2018-03-03\ndescription: use pre-trained models for dogs_vs_cats problem (fine-tuning problem)\n\"\"\"\n\n# fine-tuning:解冻冻结模型的前几个top layer,添加部分模型,然后进行同时训练\n# 注:只有在classifier已经训练好的基础上才可能fine-tune微调top layers,否则\n# 误差会随着网络的传播更大,最后破坏已经训练好的layers的抽象性\n# 步骤:\n#(1)添加已经pre-trained network即base network\n#(2)冻结base network\n#(3)添加并训练the part we added(必须提前训练好classifier)\n#(4)解冻base network中的某些layers\n#(5)同时训练这些layers+ part we add\n# 前3步在之前特征提取的教程中已经完成\n# 为什么不训练更多的卷积层?\n#(1)越靠前的卷积层能够编码更通用,更可用的特征,而更高层的层则表示特定的特征(越针对特定的问题或者数据集)\n#(2)the more parameters we training, 更可能overfit(因为数据集太小了)\n\nimport os\nimport numpy as np\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.applications import VGG16\nfrom keras import layers\nfrom keras import optimizers\nfrom keras import models\n\ntrain_dir = \"../data/dog_vs_cat/dog_vs_cat_small/train\"\nvalidation_dir = \"../data/dog_vs_cat/dog_vs_cat_small/validation\"\ntest_dir = \"../data/dog_vs_cat/dog_vs_cat_small/test\"\n\nconv_base = VGG16(weights='imagenet', include_top=False, input_shape=(150,150,3))\nconv_base.trainable = True\n\nset_trainable = False\nfor layer in conv_base.layers:\n\tif layer.name == 'block5_conv1':\n\t\tset_trainable = True\n\tif set_trainable:\n\t\tlayer.trainable = True\n\telse:\n\t\tlayer.trainable = False\n\n# 这样的学习率设置一般不能太大,否则容易破环fine-tune层的表示能力\nmodel = models.Sequential()\nmodel.add(conv_base)\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(256, activation='relu'))\nmodel.add(layers.Dense(1, activation='sigmoid'))\n\ntrain_datagen = ImageDataGenerator(\n\trescale = 1./255,\n\trotation_range = 40,\n\twidth_shift_range = 0.2,\n\theight_shift_range = 0.2,\n\tshear_range = 0.2,\n\tzoom_range = 0.2,\n\thorizontal_flip = True,\n\tfill_mode = 'nearest')\n\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = train_datagen.flow_from_directory(\n\ttrain_dir,\n\ttarget_size=(150,150),\n\tbatch_size=32,\n\tclass_mode='binary')\n\nvalidation_generator = test_datagen.flow_from_directory(\n\tvalidation_dir,\n\ttarget_size=(150,150),\n\tbatch_size=32,\n\tclass_mode='binary')\n\nmodel.compile(loss='binary_crossentropy',\n\toptimizer=optimizers.RMSprop(lr=1e-5),\n\tmetrics=['acc'])\n\nhistory = model.fit_generator(\n\ttrain_generator,\n\tsteps_per_epoch=100,\n\tepochs=10,\n\tvalidation_data=validation_generator,\n\tvalidation_steps=50)\n\nmodel.save('keraslesson5_4.h5')\n\n\n","sub_path":"keraslesson5_4.py","file_name":"keraslesson5_4.py","file_ext":"py","file_size_in_byte":2857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"209252947","text":"import time\nimport json\nfrom . import DomoResource, api_operation\nfrom common.util import build_request\nfrom operator import itemgetter\n\nclass Project(object):\n\n def __init__(self, **kwargs):\n self.created = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(kwargs.get('created', 0) / 1000))\n self.due = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(kwargs.get('dueDate', 0) / 1000))\n self.id = kwargs.get('id')\n self.name = kwargs.get('projectName')\n self.lists = kwargs.get('lists')\n self.members = kwargs.get('members')\n\nclass Task(object):\n\n def __init__(self, **kwargs):\n self.archived = kwargs.get('archived')\n self.created = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(kwargs.get('created', 0) / 1000))\n self.due = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(kwargs.get('dueDate', 0) / 1000))\n self.id = kwargs.get('id')\n self.name = kwargs.get('taskName')\n self.priority = kwargs.get('priority')\n self.ownerId = kwargs.get('primaryTaskOwner')\n self.listId = kwargs.get('projectListId')\n self.status = kwargs.get('status')\n self.tags = ', '.join([str(tag.get('tag')) for tag in kwargs.get('tags')])\n\n def set_project(self, project):\n self.projectCreated = project.created\n self.projectDue = project.due\n self.projectId = project.id\n self.projectName = project.name\n\n list = next((x for x in project.lists if x.get('id') == self.listId), None)\n self.listName = list.get('name')\n self.listType = list.get('type')\n self.listOrder = list.get('listOrder')\n\n def set_owner(self, members):\n member = next((x for x in members if x.get('id') == self.ownerId), None)\n self.ownerName = member.get('displayName')\n self.ownerEmail = member.get('detail').get('email')\n self.ownerIsDomo = \"@domo\" in self.ownerEmail\n\n\n\nclass ProjectCompiled(DomoResource):\n \"\"\" Domo Projects & Tasks \"\"\"\n\n @api_operation(\n title='All Project Tasks',\n url='/api/projects//compiled'\n )\n def get(self,project_id):\n \"\"\" Get a compiled JSON of all project's tasks \"\"\"\n\n args = self.parser.parse_args()\n\n project_json, status = _get_project_detail(project_id, args)\n project = Project(**project_json)\n\n member_list, status = _get_project_members(project.members, args)\n task_list, status = _get_project_tasks(project_id, args)\n\n tasks = []\n for task in task_list:\n task_args = args.copy()\n new_task = Task(**task)\n new_task.set_project(project)\n new_task.set_owner(member_list)\n new_task.latestComment, new_task.commentCount = _get_task_comments(new_task, task_args)\n new_task.likes = _get_task_likes(new_task, task_args)\n\n tasks.append(new_task)\n\n return [task.__dict__ for task in tasks]\n\n\ndef _get_project_detail(id, args):\n \"\"\" Get project details \"\"\"\n\n url = '/api/content/v1/projects/{}'.format(id)\n return build_request(url, args)\n\n\ndef _get_project_tasks(id, args):\n \"\"\" Get task details \"\"\"\n\n url = '/api/content/v1/projects/{}/tasks'.format(id)\n return build_request(url, args)\n\n\ndef _get_project_members(members, args):\n \"\"\" Call User endpoint for project members \"\"\"\n\n url = '/api/content/v3/users'\n args['id'] = ','.join([str(m) for m in members])\n args['includeDetails'] = True\n return build_request(url, args)\n\ndef _get_task_comments(task, args):\n \"\"\" Return comment count & latest comment \"\"\"\n\n url = '/api/social/v2/events'\n args['includeReplies'] = True\n args['task'] = task.id\n response, status = build_request(url, args)\n\n comments = [comment for comment in response if comment.get('objectType') == 'Reply']\n\n latest_comment = {}\n if comments:\n latest_comment = sorted(comments, key=itemgetter('time'), reverse=True)[0]\n\n return latest_comment.get('detail', {}).get('body', {}).get('text', None), len(comments)\n\ndef _get_task_likes(task, args):\n \"\"\" Return like count \"\"\"\n\n url = '/api/social/v2/interactions/like'\n args['ids'] = 'task:{}'.format(task.id)\n\n response, status = build_request(url, args)\n return len(response)\n","sub_path":"resources/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":4285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"166549674","text":"from sqlalchemy import *\nfrom sqlalchemy.sql import func\nimport buildapi.model.meta as meta\nfrom buildapi.model.util import get_time_interval\nfrom pylons.decorators.cache import beaker_cache\nfrom decimal import *\nimport re, simplejson, datetime\n\ndef IdleJobsQuery(starttime, endtime):\n \"\"\"Constructs the sqlalchemy query for fetching all idlejobs jobs in the specified time interval.\n Input: starttime - start time, UNIX timestamp (in seconds)\n endtime - end time, UNIX timestamp (in seconds)\n Output: query\n \"\"\"\n bldrs = meta.status_db_meta.tables['builders']\n blds = meta.status_db_meta.tables['builds']\n q = select([bldrs.c.name.label('name'),\n blds.c.starttime.label('starttime'),\n blds.c.endtime.label('endtime'),\n ],\n and_(\n bldrs.c.id==blds.c.builder_id,\n bldrs.c.category.like('%idle%'),\n blds.c.starttime>datetime.date.fromtimestamp(starttime).strftime(\"%Y%m%d\"),\n blds.c.endtimeblds.c.starttime\n ),\n )\n return q\n\ndef GetTimeStamp(date_time):\n return int(date_time.strftime(\"%s\"))\n\ndef GetIdleJobsReport(starttime=None, endtime=None, int_size=0):\n \"\"\"Get test metrics for idlejobs jobs in a given time interval\n Input: starttime - start time (UNIX timestamp in seconds), if not specified, endtime minus 24 hours\n endtime - end time (UNIX timestamp in seconds), if not specified, starttime plus 24 hours\n current time (if starttime is not specified either)\n int_size - break down results per interval (in seconds), if specified\n Output: idlejobs report\n \"\"\"\n starttime, endtime = get_time_interval(starttime, endtime)\n q = IdleJobsQuery(starttime, endtime)\n q_results = q.execute()\n report = IdleJobsReport(starttime, endtime, int_size)\n\n for r in q_results:\n this_row = {\n 'starttime': GetTimeStamp(r['starttime']),\n 'endtime' : GetTimeStamp(r['endtime']),\n }\n report.add(r['name'], this_row)\n return report\n\n\nclass IdleJobsReport(object):\n def __init__(self, starttime, endtime, int_size=0, builders=None):\n self.starttime = starttime\n self.endtime = endtime\n self.total = 0\n self.builders = builders or []\n self.int_size = int_size\n self.int_no = int((self.endtime - self.starttime-1)/self.int_size) +1 if self.int_size else 1\n self.builder_intervals = {}\n self.builder_intervals['Total'] = [0]*self.int_no\n self.totals = {}\n self.totals['Total'] = 0\n\n def get_interval_timestamp(self, int_idx):\n return self.starttime + int_idx*self.int_size\n\n def get_interval_indices(self, stime, etime):\n t = stime - self.starttime if stime > self.starttime else 0\n first_interval = int(t/self.int_size) if self.int_size else 0\n t = etime - self.starttime if etime > self.starttime else 0\n last_interval = int(t/self.int_size) if self.int_size else 0\n return range(first_interval, last_interval+1)\n\n def add(self, builder, row):\n int_idxs = self.get_interval_indices(row['starttime'], row['endtime'])\n if builder not in self.builders:\n self.builders.append(builder)\n self.builder_intervals[builder] = [0]*self.int_no\n self.totals[builder] = 0\n\n self.totals[builder] += row['endtime']-row['starttime']\n self.totals['Total'] += row['endtime']-row['starttime']\n for i in int_idxs:\n self.builder_intervals[builder][i] += 1\n self.builder_intervals['Total'][i] += 1\n self.total+=1\n return True\n\n def jsonify(self):\n json_obj = {\n 'starttime': self.starttime,\n 'endtime': self.endtime,\n 'int_size': self.int_size,\n 'total': self.total,\n 'builders': { }\n }\n for builder in self.builders:\n json_obj['builders'][builder] = {\n 'intervals': self.builder_intervals[builder],\n 'total compute time': int(self.totals[builder]),\n }\n\n return simplejson.dumps(json_obj)\n\n","sub_path":"buildapi/model/idlejobs.py","file_name":"idlejobs.py","file_ext":"py","file_size_in_byte":4378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"606013051","text":"from __future__ import print_function\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\n#In this first part, we just prepare our data (mnist) \n#for training and testing\nimport sys\n#import keras\nfrom tensorflow.keras.datasets import mnist\n\n#load the MNIST dataset from tensorflow\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\nnum_pixels = X_train.shape[1] * X_train.shape[2]\nX_train = X_train.reshape(X_train.shape[0], num_pixels).T\nX_test = X_test.reshape(X_test.shape[0], num_pixels).T\ny_train = y_train.reshape(y_train.shape[0], 1)\ny_test = y_test.reshape(y_test.shape[0], 1)\nX_train = X_train.astype('float32')\nX_test = X_test.astype('float32')\ny_train = y_train.astype('float32')\ny_test = y_test.astype('float32')\nX_train = X_train / 255\nX_test = X_test / 255 # avoid the weights getting too big\n\n\n#We want to have a binary classification: digit 0 is classified 1 and \n#all the other digits are classified 0\n\ny_new = np.zeros(y_train.shape)\ny_new[np.where(y_train==0.0)[0]] = 1\ny_train = y_new\n\ny_new = np.zeros(y_test.shape)\ny_new[np.where(y_test==0.0)[0]] = 1\ny_test = y_new\n\n\ny_train = y_train.T\ny_test = y_test.T\n\n\n# #Display one image and corresponding label \n'''\ni = 3\nprint('y[{}]={}'.format(i, y_train[:,i]))\nplt.imshow(X_train[:,i].reshape(28,28), cmap = matplotlib.cm.binary)\nplt.axis(\"off\")\nplt.show()\n'''\n#user input the number of iterations,if no input, set defualt number 500, learning rate 0.7\nif len(sys.argv) < 2:\n iterations = 500\n lr = 0.7\n\n#if there is only one input, check if it's iteration number or learning rate \nelif len(sys.argv) < 3:\n if float(sys.argv[1]) <10:\n lr = sys.argv[1]\n iterations = 500\n else:\n iterations = int(sys.argv[1])\n lr = 0.7\n\nelse: \n if float(sys.argv[1])>10: #check if the first input is iteration number\n iterations = int(sys.argv[1])\n lr = float(sys.argv[2])\n else:\n lr = float(sys.argv[1])\n iterations = int(sys.argv[2])\n \n\nclass NeuralNetwork:\n def __init__(self, x_train, y_train, iterations,lr):\n #read the whole dataset into class\n self.input = x_train\n self.y = y_train\n\n # initialize four parameters\n self.w1 = np.random.normal(0.01, 1, (64,self.input.shape[0])) *0.01\n self.w2 = np.random.normal(0.01, 1, (1,64)) *0.01\n self.b1 = np.random.normal(0.01, 1, (64,1)) *0.01\n self.b2 = 0.01\n\n self.epoch = iterations\n self.lr = lr \n\n def feedforward(self):\n self.Z1 = np.dot(self.w1, self.X_train_to_go) + self.b1 #Z1 = W1*X + b1\n self.A1 = self.get_sigmoid(self.Z1,'false') #A1 = sigmoid(Z1)\n self.Z2 = np.dot(self.w2,self.A1) + self.b2 #Z2 = W2*A1 +b2\n self.A2 = self.get_sigmoid(self.Z2,'false') #A2 = sigmoid(Z2)\n loss = self.get_loss(self.A2, self.y_train_to_go,'false')\n return loss\n\n def backprop(self):\n # application of the chain rule to find derivative of the loss function with respect to weights2 and weights1\n self.dj_dA2 = self.get_loss(self.A2,self.y_train_to_go,'true')\n self.dA2_dZ2 = self.get_sigmoid(self.Z2,'true')\n self.dZ2_dw2 = self.A1\n self.delta2 = self.dj_dA2*self.dA2_dZ2\n self.dj_dw2 = (1.0/self.m)*np.matmul(self.delta2,np.transpose(self.dZ2_dw2)) #the derivative of w2 \n\n self.dZ2_dA1 = self.w2\n self.dA1_dZ1 = self.get_sigmoid(self.Z1,'true')\n self.dZ1_dw1 = self.X_train_to_go\n self.delta1 = np.matmul(np.transpose(self.dZ2_dA1),self.delta2)*self.dA1_dZ1\n self.dj_dw1 = (1.0/self.m)*np.matmul(self.delta1, self.dZ1_dw1.transpose()) #THE derivative of w1\n\n\n self.dj_db2 = (1.0/self.m)*np.sum(self.delta2) # the derivative of b2\n self.dj_db1 = (1.0/self.m)*np.sum(self.delta1,axis=1).reshape((64,1)) #the derivative of b1\n\n '''\n self.dZ2 = self.A2 - self.y_train_to_go\n self.dw2 = (1.0/self.m)*np.matmul(self.dZ2,self.A1.transpost())\n self.b2 = (1.0/self.m)*np.sum(self.dZ2)\n\n self.dZ1 = self.A1 - \n self.dw1 = \n '''\n\n \n # update the weights with the derivative (slope) of the loss function\n self.w1 -= lr*self.dj_dw1\n self.w2 -= lr*self.dj_dw2\n self.b1 -= lr*self.dj_db1\n self.b2 -= lr*self.dj_db2\n return self.w1, self.w2, self.b1, self.b2\n\n #Let start our work: creating a neural network\n #First, we just use a single neuron. \n\n def get_sigmoid(self, Z, backward):\n sig = 1/(1 + np.exp(-Z))\n\n if backward == 'false': # if not backward\n return sig\n else:\n return sig*(1-sig) \n\n def get_loss(self, A, y_gt, backward):\n if backward == 'false':\n loss = -(1.0/y_gt.shape[1]) * np.sum(y_gt*np.log(A+1e-8) + (1-y_gt)*np.log(1-A+1e-8))\n else:\n #loss = -(1.0/self.m) * np.sum(y_gt/A - (1-y_gt)/(1-A))\n loss = - np.divide(y_gt,A+1e-8) + np.divide((1-y_gt),(1-A)+1e-8)\n return loss\n\n #####TO COMPLETE\n def training(self):\n #Now, we shuffle the training set\n samples_num = self.input.shape[1] #number of examples\n\n np.random.seed(138)\n shuffle_index = np.random.permutation(samples_num)\n X_train, y_train = self.input[:,shuffle_index], self.y[:,shuffle_index]\n\n X_train_to_go, y_train_to_go = self.input[:,:int(2*samples_num/3)], self.y[:,:int(2*samples_num/3)]\n np.random.seed(138)\n shuffle_index_1 = np.random.permutation(int(2*samples_num/3))\n self.X_train_to_go, self.y_train_to_go = X_train_to_go[:,shuffle_index_1], y_train_to_go[:,shuffle_index_1]\n\n X_val, y_val = self.input[:,int(2*samples_num/3):], self.y[:,int(2*samples_num/3):]\n np.random.seed(138)\n shuffle_index_2 = np.random.permutation(int(samples_num/3))\n X_val, y_val = X_val[:,shuffle_index_2], y_val[:,shuffle_index_2]\n\n\n self.m = self.X_train_to_go.shape[1]\n training_loss_history=[]\n validation_loss_history=[]\n train_accuracy_history=[]\n validation_accuracy_history = []\n\n for i in range(self.epoch):\n \n # forward propagation\n loss_train = self.feedforward()\n training_loss_history.append(loss_train)\n acc_train = self.get_accuracy(self.A2,self.y_train_to_go)\n train_accuracy_history.append(acc_train)\n \n # back propagation\n w1,w2,b1,b2 = self.backprop()\n\n #test on the validation set\n y_val_predicted = self.classify(X_val)\n loss_val = self.get_loss(y_val_predicted,y_val,'false')\n validation_loss_history.append(loss_val)\n\n acc_val = self.get_accuracy(y_val_predicted,y_val)\n validation_accuracy_history.append(acc_val)\n\n print(\"Epoch\" + str(i) + \": validation accuracy \" + str(acc_val) + '\\n' +\" training loss: \"+ str(loss_train)+\"validation loss:\" + str(loss_val))\n\n return np.array(training_loss_history),np.array(validation_loss_history),np.array(train_accuracy_history),np.array(validation_accuracy_history)\n\n\n def classify(self,x_test):\n A = self.get_sigmoid(np.dot(self.w1,x_test) + self.b1,'false')\n y_test_predicted = self.get_sigmoid(np.dot(self.w2,A) + self.b2,'false')\n return np.round(y_test_predicted)\n\n def get_accuracy(self,y_test_predicted,y_test):\n y_test_predicted = np.round(y_test_predicted)\n acc = (np.sum((y_test_predicted == y_test).astype(int)))/y_test_predicted.shape[1]\n return acc\n\n\n\nnn = NeuralNetwork(X_train, y_train, iterations,lr)\nloss_train,loss_val,acc_train,acc_val = nn.training()\n\nplt.figure(1)\nplt.title('loss_train vs loss_val')\nloss_train_plt, = plt.plot(loss_train, \"r\")\nloss_val_plt, = plt.plot(loss_val, \"b\")\nplt.legend([loss_train_plt, loss_val_plt], [\"Train loss\", \"Validation loss\"])\nplt.savefig('loss.png')\n\nplt.figure(2)\nplt.title('acc_train vs acc_val')\nacc_train_plt, = plt.plot(acc_train, \"r\")\nacc_val_plt, = plt.plot(acc_val, \"b\")\nplt.legend([acc_train_plt, acc_val_plt], [\"Train accuracy\", \"Validation accuracy\"])\nplt.savefig('accuracy.png')\n\nplt.show()\n\n\n\ny_test_hat = nn.classify(X_test)\ntest_acc = nn.get_accuracy(y_test_hat,y_test)\nprint(\"the accuracy on test set is:\"+str(test_acc))\n\n","sub_path":"one_hidden_layer.py","file_name":"one_hidden_layer.py","file_ext":"py","file_size_in_byte":8356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"425543528","text":"from collections import Counter\nfrom copy import deepcopy\n\nfrom aocframework import AoCFramework\nfrom operator import attrgetter\nclass Day(AoCFramework):\n test_cases = ()\n def go(self):\n raw = self.puzzle_input.rstrip()\n raw_split = self.linesplitted\n field=[]\n\n class IntersectionTurns:\n LEFT=0\n STRAIGHT = 1\n RIGHT = 2\n class Directions:\n show={0:\">\",1:\"^\",2:\"<\",3:\"v\"}\n RIGHT = 0\n UP = 1\n LEFT = 2\n DOWN = 3\n class Tracks:\n HORIZONTAL = '-'\n VERTICAL = '|'\n DIAGONAL1='\\\\'\n DIAGONAL2='/'\n INTERSECTION = '+'\n\n class Cart:\n interturn=0\n pos = (0,0)\n dir = Directions.RIGHT\n crashed = False\n def __init__(self,pos,dir):\n self.pos=pos\n self.dir = dir\n\n def __repr__(self):\n return f\"{Directions.show[self.dir]} @ {self.pos}\"\n def turn_on_intersection(self):\n if self.interturn == IntersectionTurns.LEFT:\n self.dir = (self.dir + 1) % 4\n self.interturn = IntersectionTurns.STRAIGHT\n elif self.interturn == IntersectionTurns.STRAIGHT:\n self.interturn = IntersectionTurns.RIGHT\n elif self.interturn == IntersectionTurns.RIGHT:\n self.dir = (self.dir - 1) % 4\n self.interturn = IntersectionTurns.LEFT\n\n def move(self):\n nonlocal field,carts\n x,y = self.pos\n if self.dir == Directions.RIGHT:\n x+=1\n elif self.dir == Directions.UP:\n y-=1\n elif self.dir == Directions.LEFT:\n x-=1\n elif self.dir == Directions.DOWN:\n y+=1\n self.pos = (x,y)\n if field[y][x]== Tracks.DIAGONAL1 and (self.dir==Directions.UP or self.dir==Directions.DOWN):\n self.dir = (self.dir + 1) % 4\n elif field[y][x]== Tracks.DIAGONAL1 and (self.dir==Directions.RIGHT or self.dir==Directions.LEFT):\n self.dir = (self.dir - 1) % 4\n elif field[y][x]== Tracks.DIAGONAL2 and (self.dir==Directions.UP or self.dir==Directions.DOWN):\n self.dir = (self.dir - 1) % 4\n elif field[y][x]== Tracks.DIAGONAL2 and (self.dir==Directions.RIGHT or self.dir==Directions.LEFT):\n self.dir = (self.dir + 1) % 4\n elif field[y][x]==Tracks.INTERSECTION:\n self.turn_on_intersection()\n\n carts = set()\n # save field\n for row in raw_split:\n field.append(list(row))\n for y in range(len(field)):\n for x in range(len(field[0])):\n if field[y][x] == '^':\n carts.add(Cart((x,y),Directions.UP))\n field[y][x]='|'\n elif field[y][x] == 'v':\n carts.add(Cart((x,y),Directions.DOWN))\n field[y][x]='|'\n elif field[y][x] == '>':\n carts.add(Cart((x, y), Directions.RIGHT))\n field[y][x] = '-'\n elif field[y][x] == '<':\n carts.add(Cart((x, y), Directions.LEFT))\n field[y][x] = '-'\n\n def simulate(step):\n sorted_carts = sorted(carts,key=attrgetter('pos'))\n crashed_carts = []\n crashed = False\n for cart in sorted_carts:\n cart.move()\n cart_positions = Counter(cart.pos for cart in carts)\n if len(cart_positions.most_common()) != len(carts):\n crashed_carts=[cart for cart in carts if cart.pos == cart_positions.most_common()[0][0]]\n print(cart_positions.most_common()[0])\n crashed = True\n for cart in crashed_carts:\n carts.remove(cart)\n if crashed:\n print(carts)\n\n for i in range(100000):\n # with open(f'frame{i}.txt','w') as frame:\n # actual_field = deepcopy(field)\n # for cart in carts:\n # x,y = cart.pos\n # if cart.dir == Directions.RIGHT:\n # actual_field[y][x] = '>'\n # elif cart.dir == Directions.LEFT:\n # actual_field[y][x] = '<'\n # elif cart.dir == Directions.UP:\n # actual_field[y][x] = '^'\n # elif cart.dir == Directions.DOWN:\n # actual_field[y][x] = 'V'\n # field_repr = '\\n'.join(''.join(row) for row in actual_field)\n # frame.write(field_repr)\n simulate(i)\n if len(carts)==1:\n print(carts)\n break\n\nDay()\n","sub_path":"aoc2018/d13/foo2.py","file_name":"foo2.py","file_ext":"py","file_size_in_byte":5028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"487637190","text":"# Find divisor of two or more integers, which are not all zero,\n# is the largest positive integer that divides each of the integers.\n\nfrom lesson_3.Get_divisors import get_divisors\n\n\ndef in_list(num, list_of_numbers):\n return num in list_of_numbers\n\n\n\ndef greater_common_divisor(num_1, num_2):\n divisors_num_1 = get_divisors(num_1)\n divisors_num_2 = get_divisors(num_2)\n\n result = []\n for num in divisors_num_1:\n if in_list(num, divisors_num_2):\n result.append(num)\n return max(result)\n\n\nprint(greater_common_divisor(24, 48))","sub_path":"lesson_4/GCD.py","file_name":"GCD.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"252541181","text":"from django.shortcuts import render, redirect\nfrom .models import Registration\nfrom django.contrib import messages\nfrom .models import Quote\ndef index(request):\n return render(request, 'exam2/index.html')\n\ndef registration(request):\n if request.method == \"POST\":\n validated_person = Registration.objects.register(request.POST)\n if 'errors' in validated_person:\n for validation_error in validated_person['errors']:\n messages.error(request, validation_error)\n if 'the_person' in validated_person:\n messages.success(request, 'registered successfully!')\n return redirect('/')\n\ndef login(request):\n if request.method == \"POST\":\n validated_user = Registration.objects.login(request.POST)\n if 'errors' in validated_user:\n for error in validated_user['errors']:\n messages.error(request, error)\n return redirect('/')\n if 'logged' in validated_user:\n request.session['logged'] = validated_user['logged']\n request.session['loginuser'] = validated_user['loginuser']\n return redirect('/home')\n return redirect('/')\n\ndef home(request):\n context = {\n 'favorites':Quote.objects.filter(users__id=request.session['logged']),\n 'otherquotes':Quote.objects.exclude(users__id=request.session['logged'])\n }\n return render(request, 'exam2/quotes.html', context)\n\ndef add_quote(request):\n if request.method == \"POST\":\n quoteadded = Quote.objects.addquote(request.POST)\n if 'errors' in quoteadded:\n for error in quoteadded['errors']:\n messages.error(request, error)\n return redirect('/home')\n if 'quote' in quoteadded:\n return redirect('/home')\n\ndef add_to_fav(request, id):\n # bring = Quote.objects.get(id=id)\n # context = {\n # 'id' : id,\n # 'bring' : bring,\n # 'posted' : Registration.objects.filter(userquote__id=draw.id).exclude(creator__id=draw.id)\n # }\n quote = Quote.objects.get(id=id)\n user = Registration.objects.get(id=request.session['logged'])\n quote.users.add(user)\n return redirect('/home')\n\ndef remove_list(request, id):\n quote = Quote.objects.get(id=id)\n user = Registration.objects.get(id=request.session['logged'])\n # pop = Quote.objects.filter(users__id=request.session['logged']).get(id=id)\n quote.users.remove(user)\n return redirect('/home')\ndef post(request, id):\n bring = Quote.objects.get(id = id)\n posts = Quote.objects.all()\n\n context = {\n 'id' : id,\n 'bring' : bring,\n 'posts' : posts\n }\n\n request.session['count'] = Quote.objects.count()\n # if 'count' not in request.session:\n # request.session['count']= 0\n # else:\n # request.session['count']= request.session['count'] +\n return render(request, 'exam2/post.html', context)\n\ndef logout(request):\n del request.session['logged']\n del request.session['loginuser']\n return redirect('/')\n","sub_path":"apps/exam2/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"531450121","text":"# -*- coding: utf-8 -*-\nfrom django.db import models\nimport logging\n\ntry:\n import json\nexcept:\n import simplejson as json\n\nPARAM_GROUP = (('weibo', \"WeiBo\"),\n ('site', \"网站\"),\n )\n\nclass ParameterDefine(models.Model):\n \"\"\"需要配置的参数定义。\"\"\"\n class Meta:\n db_table = 'param_define'\n verbose_name_plural = '参数定义'\n verbose_name = '参数定义'\n\n group = models.CharField(max_length=10,\n default=\"weibo\",\n choices= PARAM_GROUP,\n verbose_name=\"参数分组\",\n help_text='可以定义不同类型的参数分组,例如,围脖的参数,网站的参数,广告的参数等。'\n )\n uuid = models.CharField(max_length=32, primary_key=True, \n verbose_name=\"参数名称\", \n help_text='在网站代码里面,需要使用到此名称。 例如:site_title, site_keywords。')\n \n details = models.TextField(verbose_name=\"参数说明\",\n help_text='在配置页面会显示,参数的描述。',\n blank=True)\n\n input_type = models.CharField(max_length=12,\n verbose_name=\"参数的类型\",\n choices=(('text', \"text\"),\n ('textarea', \"textarea\"),\n ('select', \"select\"),\n # ('checkbox', \"checkbox\"),\n ), \n help_text='参数的输入类型',\n default='text',\n ) \n\n default_val = models.TextField(max_length=512,\n verbose_name=\"默认值\", \n help_text='参数的默认值',\n blank=True)\n\n view_order = models.IntegerField(verbose_name=\"显示排序\", \n help_text='在参数配置页面的位置(升序排列). 如果多个参数位置相同,按照创建时间排序。',\n default=0)\n \n update_time = models.DateTimeField('update time', auto_now=True)\n create_time = models.DateTimeField('create time', auto_now_add=True)\n \n @staticmethod\n def load_param_group(group):\n ps = ParameterDefine.objects.filter(group=group).order_by(\"view_order\", \"-create_time\") #.order_by(\"-create_time\")\n return ps\n \n @property\n def default_value(self):\n if self.input_type == 'select':\n return self.default_val.split(\"\\n\")[0]\n else:\n return self.default_val\n \n @property\n def value_choices(self):\n return ((e, e) for e in self.default_val.split(\"\\n\"))\n \n def get_field(self):\n from django.forms.fields import Field, ChoiceField\n from django.forms.widgets import Textarea\n \n cls = Field\n attrs = {'required':False,\n 'initial':self.default_value,\n 'help_text': self.details,\n 'label': self.uuid,\n }\n \n if self.input_type == 'select':\n attrs['choices'] = self.value_choices\n cls = ChoiceField\n if self.input_type == 'textarea':\n #attrs['rows'] = '6'\n #attrs['cols'] = '80'\n attrs['widget'] = Textarea({'rows':6, 'cols':80})\n \n return cls(**attrs)\n \n def __unicode__(self):\n return self.uuid\n \nclass ParameterValue(models.Model):\n \"\"\"参数的具体配置至。\"\"\"\n \n class Meta:\n db_table = 'param_value'\n verbose_name_plural = '网站参数'\n verbose_name = '网站参数'\n\n site_url = models.CharField(max_length=255, unique=True, \n verbose_name=\"网站地址\", \n help_text='配置的唯一地址,需要使用这个地址做Cache清理操作,一定要配置正确。例如:http://www.littlefun.net/apps/yuanfen/sina')\n \n group = models.CharField(max_length=10,\n default=\"weibo\",\n choices= PARAM_GROUP,\n verbose_name=\"参数分组\",\n help_text='可以定义不同类型的参数分组,例如,围脖的参数,网站的参数,广告的参数等。'\n )\n values = models.TextField(verbose_name=\"参数值\",\n help_text='参数的具体值')\n \n update_time = models.DateTimeField('update time', auto_now=True)\n create_time = models.DateTimeField('create time', auto_now_add=True)\n \n \n def edit_param(self):\n from Weibo.settings import APP_ROOT\n return \"\"\"修改参数\"\"\" \\\n % (APP_ROOT, self.id)\n \n edit_param.allow_tags = True\n #edit_param.verbose_name = \"文件下载\"\n #edit_param.verbose_name = \"告警类型\"\n \n @property\n def dict_values(self):\n v = {}\n try:\n v = json.loads(self.values)\n except:\n pass\n return v\n \n def clean_site_cache(self):\n pass\n \n def update_values(self, vals):\n new_values = self.dict_values\n new_values.update(vals)\n self.values = json.dumps(new_values) \n \n def __unicode__(self):\n return self.site_url\n \n def __str__(self):\n return self.site_url\n \n\t\nclass Question(models.Model):\n \"\"\"问题列表\"\"\"\n \n class Meta:\n db_table = 'weibo_question'\n verbose_name_plural = '问答题目'\n verbose_name = '问答题目'\n \n group_name = models.CharField(max_length=50,\n\t\t\t\t\t\t\t\t default=\"weibo\",\n verbose_name=\"问题分组\",\n help_text='问题名称'\n )\n\t\t\t\t\t\t\t\t \n input_type = models.CharField(max_length=12,\n verbose_name=\"问题类型\",\n choices=(('single', \"single\"),\n ('select', \"select\"),\n ), \n help_text='问题类型',\n default='single',\n ) \n\t\t\t\t\t\t\t\t \n values = models.TextField(verbose_name=\"问题描述\",\n help_text='问题描述')\n\t\t\t\t\t\t\t \n view_order = models.IntegerField(verbose_name=\"显示排序\", \n help_text='问题的排序',\n default=0)\t\t\t \n\t\t\t\t\t\t\t \n update_time = models.DateTimeField('update time', auto_now=True)\n create_time = models.DateTimeField('create time', auto_now_add=True)\n\nclass Answer(models.Model):\n \"\"\"问题列表\"\"\"\n \n class Meta:\n db_table = 'weibo_answer'\n verbose_name_plural = '问答答案'\n verbose_name = '问答答案'\n \n group_name = models.CharField(max_length=50,\n\t\t\t\t\t\t\t\t default=\"weibo\",\n verbose_name=\"问题分组\",\n help_text='问题名称'\n )\n\t\t\t\t\t\t\t\t \n values = models.TextField(verbose_name=\"问题答案\",\n help_text='问题答案')\n\t\t\t\t\t\t\t \n view_order = models.IntegerField(verbose_name=\"显示排序\", \n help_text='问题的排序',\n default=0)\t\t\t \n\t\t\t\t\t\t\t \n update_time = models.DateTimeField('update time', auto_now=True)\n create_time = models.DateTimeField('create time', auto_now_add=True)\t\n\t","sub_path":"other_projects/python/WeiboAds/src/Weibo/params/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"450092266","text":"import gtest\nfrom game.items import spawn_item, Item, get_items\n\n\nasync def test_use_no_args(ctx: gtest.Context):\n p = ctx.player()\n response = await p('item use')\n assert response.text == 'Player#1: Nieprawidłowy argument. Komenda przyjmuje nazwę przedmiotu lub jego numer na liście.'\n\n\nasync def test_use_by_number_but_player_has_no_items(ctx: gtest.Context):\n p = ctx.player()\n response = await p('item use 1')\n assert response.text == 'Player#1: Na liście nie ma przedmiotu z takim numerem.'\n\n\nasync def test_use_by_name_but_player_has_no_items(ctx: gtest.Context):\n p = ctx.player()\n response = await p('item use Maska Tengu')\n assert response.text == 'Player#1: Nie posiadasz takiego przedmiotu.'\n\n\nasync def test_use_by_name_but_player_has_no_such_item(ctx: gtest.Context):\n p = ctx.player()\n spawn_item(p.model, template_id='powerup_trainingtime_dexterity')\n response = await p('item use Maska Tengu')\n assert response.text == 'Player#1: Nie posiadasz takiego przedmiotu.'\n\n\nasync def test_use_owned_item(ctx: gtest.Context):\n p = ctx.player()\n spawn_item(p.model, template_id='pawulonik')\n response = await p('item use pawulonik')\n assert response.text == 'Player#1: Wyposażyłeś się w **Pawulonik**.'\n\n\nasync def test_use_chooses_item_with_best_condition(ctx: gtest.Context):\n p = ctx.player()\n for condition in [3, 60, 20]:\n spawn_item(p.model, template_id='pawulonik', condition=condition)\n await p('item use pawulonik')\n for item in get_items(p.model):\n assert item.equipped == (item.condition == 60)\n\n\nasync def test_use_on_equipped_item(ctx: gtest.Context):\n p = ctx.player()\n spawn_item(p.model, template_id='pawulonik')\n await p('item use pawulonik')\n response = await p('item use pawulonik')\n assert response.text == 'Player#1: Schowałeś **Pawulonik**.'\n\n\nasync def test_use_item_requiring_training_without_training(ctx: gtest.Context):\n p = ctx.player()\n spawn_item(p.model, template_id='powerup_trainingtime_dexterity')\n response = await p('item use powerup_trainingtime_dexterity')\n assert response.text == 'Player#1: Przedmiot może być użyty tylko w czasie trwania treningu umiejętności **dexterity**.'\n\n\nasync def test_use_item_requiring_training_with_training(ctx: gtest.Context):\n p = ctx.player()\n await p('me train dexterity')\n spawn_item(p.model, template_id='powerup_trainingtime_dexterity')\n response = await p('item use powerup_trainingtime_dexterity')\n assert response.text == 'Player#1: Wypiłeś **Łówstwospust**.'\n\n\nasync def test_use_unknown_item(ctx: gtest.Context):\n p = ctx.player()\n response = await p('item use mader')\n assert response.text == 'Player#1: Nieznany przedmiot.'\n\n\nasync def test_use_not_applicable(ctx: gtest.Context):\n p = ctx.player()\n spawn_item(p.model, template_id='armor_tengu_mask')\n response = await p('item use Maska Tengu')\n assert response.text == 'Player#1: Nie możesz użyć tego przedmiotu.'\n","sub_path":"tests/item_use.py","file_name":"item_use.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"608485098","text":"#!/usr/bin/env python\n\nfrom setuptools import find_packages\nfrom distutils.core import setup\nimport py2exe\n\nconfig = {\n 'version': '1.0',\n\t'description': 'Downloads shit from the uni heidelberg moodle installation',\n 'url': 'https://github.com/cessor/scrape',\n 'download_url': 'https://github.com/cessor/scrape',\n 'author': 'Johannes Hofmeister',\n\t'author_email': 'scrape@spam.cessor.de',\n 'install_requires': [],\n\t'py_modules' : ['scrape'],\n 'packages': find_packages(),\n 'scripts': [],\n 'name': 'scrape',\n\t'console' : [\"scrape.py\"]\n}\n\nsetup(**config)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"349637587","text":"#!/usr/bin/env python\n# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://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\"\"\"Uploads a conversion using hashed email address instead of GCLID.\"\"\"\n\n\nimport argparse\nimport hashlib\nimport re\nimport sys\n\nfrom google.ads.googleads.client import GoogleAdsClient\nfrom google.ads.googleads.errors import GoogleAdsException\n\n\n# [START upload_conversion_with_identifiers]\ndef main(\n client,\n customer_id,\n conversion_action_id,\n email_address,\n conversion_date_time,\n conversion_value,\n order_id,\n):\n \"\"\"The main method that creates all necessary entities for the example.\n\n Args:\n client: An initialized GoogleAdsClient instance.\n customer_id: The client customer ID string.\n conversion_action_id: The ID of the conversion action to upload to.\n email_address: The email address for the conversion.\n conversion_date_time: The date and time of the conversion.\n conversion_value: The value of the conversion.\n order_id: The unique ID (transaction ID) of the conversion.\n \"\"\"\n # [START create_conversion]\n conversion_action_service = client.get_service(\"ConversionActionService\")\n # Gets the conversion action resource name.\n conversion_action_resource_name = conversion_action_service.conversion_action_path(\n customer_id, conversion_action_id\n )\n click_conversion = client.get_type(\"ClickConversion\")\n click_conversion.conversion_action = conversion_action_resource_name\n click_conversion.conversion_date_time = conversion_date_time\n click_conversion.conversion_value = conversion_value\n click_conversion.currency_code = \"USD\"\n\n # Sets the order ID if provided.\n if order_id:\n click_conversion.order_id = order_id\n\n # Creates a user identifier using the hashed email address, using the\n # normalize and hash method specifically for email addresses. If using a\n # phone number, use the \"_normalize_and_hash\" method instead.\n user_identifier = client.get_type(\"UserIdentifier\")\n # Creates a SHA256 hashed string using the given email address, as\n # described at https://support.google.com/google-ads/answer/9888656.\n user_identifier.hashed_email = normalize_and_hash_email_address(\n email_address\n )\n # Optional: Specifies the user identifier source.\n user_identifier.user_identifier_source = (\n client.enums.UserIdentifierSourceEnum.FIRST_PARTY\n )\n # Adds the user identifier to the conversion.\n click_conversion.user_identifiers.append(user_identifier)\n # [END create_conversion]\n\n # Creates the conversion upload service client.\n conversion_upload_service = client.get_service(\"ConversionUploadService\")\n # Uploads the click conversion. Partial failure should always be set to\n # True.\n response = conversion_upload_service.upload_click_conversions(\n customer_id=customer_id,\n conversions=[click_conversion],\n # Enables partial failure (must be true).\n partial_failure=True,\n )\n\n # Prints any partial errors returned.\n if response.partial_failure_error:\n print(\n \"Partial error encountered: \"\n f\"{response.partial_failure_error.message}\"\n )\n\n # Prints the result.\n result = response.results[0]\n # Only prints valid results. If the click conversion failed then this\n # result will be returned as an empty message and will be falsy.\n if result:\n print(\n \"Uploaded conversion that occurred at \"\n f\"{result.conversion_data_time} \"\n f\"to {result.conversion_action}.\"\n )\n # [END upload_conversion_with_identifiers]\n\n\n# [START normalize_and_hash]\ndef normalize_and_hash_email_address(email_address):\n \"\"\"Returns the result of normalizing and hashing an email address.\n\n For this use case, Google Ads requires removal of any '.' characters\n preceding \"gmail.com\" or \"googlemail.com\"\n\n Args:\n email_address: An email address to normalize.\n\n Returns:\n A normalized (lowercase, removed whitespace) and SHA-265 hashed string.\n \"\"\"\n normalized_email = email_address.lower()\n email_parts = normalized_email.split(\"@\")\n # Checks whether the domain of the email address is either \"gmail.com\"\n # or \"googlemail.com\". If this regex does not match then this statement\n # will evaluate to None.\n is_gmail = re.match(r\"^(gmail|googlemail)\\.com$\", email_parts[1])\n\n # Check that there are at least two segments and the second segment\n # matches the above regex expression validating the email domain name.\n if len(email_parts) > 1 and is_gmail:\n # Removes any '.' characters from the portion of the email address\n # before the domain if the domain is gmail.com or googlemail.com.\n email_parts[0] = email_parts[0].replace(\".\", \"\")\n normalized_email = \"@\".join(email_parts)\n\n return normalize_and_hash(normalized_email)\n\n\ndef normalize_and_hash(s):\n \"\"\"Normalizes and hashes a string with SHA-256.\n\n Private customer data must be hashed during upload, as described at:\n https://support.google.com/google-ads/answer/7474263\n\n Args:\n s: The string to perform this operation on.\n\n Returns:\n A normalized (lowercase, removed whitespace) and SHA-256 hashed string.\n \"\"\"\n return hashlib.sha256(s.strip().lower().encode()).hexdigest()\n # [END normalize_and_hash]\n\n\nif __name__ == \"__main__\":\n # GoogleAdsClient will read the google-ads.yaml configuration file in the\n # home directory if none is specified.\n googleads_client = GoogleAdsClient.load_from_storage(version=\"v14\")\n\n parser = argparse.ArgumentParser(\n description=\"Imports offline call conversion values for calls related \"\n \"to your ads.\"\n )\n # The following argument(s) should be provided to run the example.\n parser.add_argument(\n \"-c\",\n \"--customer_id\",\n type=str,\n required=True,\n help=\"The Google Ads customer ID.\",\n )\n parser.add_argument(\n \"-a\",\n \"--conversion_action_id\",\n type=str,\n required=True,\n help=\"The ID of the conversion action to upload to.\",\n )\n parser.add_argument(\n \"-e\",\n \"--email_address\",\n type=str,\n required=True,\n help=\"The email address for the conversion.\",\n )\n parser.add_argument(\n \"-d\",\n \"--conversion_date_time\",\n type=str,\n required=True,\n help=\"The date time at which the conversion occurred. Must be after \"\n \"the click time, and must include the time zone offset. The format is \"\n \"'yyyy-mm-dd hh:mm:ss+|-hh:mm', e.g. '2019-01-01 12:32:45-08:00'.\",\n )\n parser.add_argument(\n \"-v\",\n \"--conversion_value\",\n type=float,\n required=True,\n help=\"The value of the conversion.\",\n )\n parser.add_argument(\n \"-o\",\n \"--order_id\",\n type=str,\n help=\"the unique ID (transaction ID) of the conversion.\",\n )\n args = parser.parse_args()\n\n try:\n main(\n googleads_client,\n args.customer_id,\n args.conversion_action_id,\n args.email_address,\n args.conversion_date_time,\n args.conversion_value,\n args.order_id,\n )\n except GoogleAdsException as ex:\n print(\n f\"Request with ID '{ex.request_id}'' failed with status \"\n f\"'{ex.error.code().name}' and includes the following errors:\"\n )\n for error in ex.failure.errors:\n print(f\"\\tError with message '{error.message}'.\")\n if error.location:\n for field_path_element in error.location.field_path_elements:\n print(f\"\\t\\tOn field: {field_path_element.field_name}\")\n sys.exit(1)\n","sub_path":"examples/remarketing/upload_conversion_with_identifiers.py","file_name":"upload_conversion_with_identifiers.py","file_ext":"py","file_size_in_byte":8337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"530691747","text":"# -*- coding: future_fstrings -*-\n\n# Friendly Telegram (telegram userbot)\n# Copyright (C) 2018-2020 The Authors\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\nimport random\nimport logging\nfrom .. import loader, utils\n\nlogger = logging.getLogger(__name__)\n\ndef register(cb):\n cb(UpvoteMod())\nUPVOTE = \" __ \\n _ /_ |\\n _| |_ | |\\n|_ _| | |\\n |_| | |\\n |_| \\n\\n\"\nRANDOM_MESSAGE = [\"I completely agree\", \"I strongly agree\", \"I agree entirely\", \"I absolutely agree\", \"Point well taken!\",\n \"I very much agree\", \"I am in full agreement\", \"I would have to agree with you\", \"I am in complete agreement\",\n \"Couldn't agree more\", \"I wholeheartedly agree\", \"I quite agree with you\", \"I fully support this\"]\n\nclass UpvoteMod(loader.Module):\n \"\"\"Upvote module\"\"\"\n strings = {\"name\": \"Upvote\"}\n def __init__(self):\n self.config = loader.ModuleConfig(\"RANDOM_UPVOTES\", RANDOM_MESSAGE, \"Random upvote messages\")\n \n async def upcmd(self, message):\n \"\"\".up gives an upvote\"\"\"\n upvoteMessage = random.choice(RANDOM_MESSAGE)\n await utils.answer(message,\"\\u206a\" + utils.escape_html(UPVOTE) + upvoteMessage + \"\")","sub_path":"upvote.py","file_name":"upvote.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"76612080","text":"from threading import Semaphore, Thread\nfrom queue import Queue\nfrom time import sleep\n\n\ndef producer(que, sem):\n while True:\n print('que size is {}'.format(que.qsize()))\n sleep(1)\n que.put(1)\n\n\ndef consumer(que, sem):\n while True:\n print(que.get())\n\n\nif __name__ == '__main__':\n sem = Semaphore(30)\n que = Queue(3)\n prods = [Thread(target=producer, args=(que, sem)) for _ in range(4)]\n cons = [Thread(target=consumer, args=(que, sem)) for _ in range(2)]\n\n for c in cons:\n c.start()\n\n for pr in prods:\n pr.start()\n\n\n","sub_path":"threading_patterns_hw/prod_cons_semaphore.py","file_name":"prod_cons_semaphore.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"350014019","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.core.cache import caches\n\nfrom common_utils.cache import LRUCache\n\n\ndefault_cache = caches['default']\n\n\ndef get_cache():\n\tcache = default_cache.get('hitcount_cache')\n\tif not cache:\n\t\tcache = LRUCache(maxsize=1000)\n\treturn cache\n\n\ndef set_cache(cache):\n\tdefault_cache.set('hitcount_cache', cache)\n\n\ndef set_hitcount(object_id, content_type_id, count):\n\tcache = get_cache()\n\tcache[object_id, content_type_id] = count\n\tset_cache(cache)\n","sub_path":"hitcount/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"233118574","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/10/25 16:35\n# @Author : mrwuzs\n# @Site :\n# @File : test_02_allocation_domain_administrator.py\n# @Software: PyCharm\nimport pytest\nimport allure\n\nfrom time import sleep\nfrom public.common import datainfo\nfrom public.common.publicfunction import *\nfrom public.appmodel import useraction\nfrom public.pages import sysUorgMgrPage\n\n@allure.feature(\"域管理\")\nclass TestAllDomainAdmin():\n \"\"\"域添加域管理员\"\"\"\n\n @allure.story(\"域添加域管理员\")\n @pytest.mark.flaky(reruns=globalparam.RENUM)\n def test_allocation_domain_admin(self,login_admin):\n dr = login_admin\n datas = datainfo.get_xls_to_dict(\"user.xlsx\", \"Sheet1\")[\"创建域管理员\"]\n upage = sysUorgMgrPage.SysUorgMgrPage(dr)\n ua = useraction.UserAction(dr)\n ua.allocation_domain_administrator(datas[\"mgrname\"], datas[\"username\"])\n # 校验已分配域管理角色\n upage.open_uorgmgrpage()\n upage.input_select_user(datas[\"username\"])\n sleep(2)\n character = dr.get_text(\n \"css->.ng-scope:nth-child(4) > .wordBreak\")\n add_image(dr,\"域添加域管理员\")\n assert character == \"1\"\n # self.assertTrue(dr.element_exist(\"\"]), \"用户未创建成功,请查看日志\")\n\n\nif __name__ == \"__main__\":\n pytest.main([\"-s\", \"test_02_allocation_domain_administrator.py\"])\n","sub_path":"testcase/test_02_allocation_domain_administrator.py","file_name":"test_02_allocation_domain_administrator.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"34592148","text":"# LSTM model generation based on the passed params\n# Shekoofeh Azizi @ UBC-RCL 19-Feb-2017\n\nimport numpy\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nfrom keras.layers import MaxPooling1D, AveragePooling1D\nimport keras.optimizers as kerasOpt\nimport matplotlib.pyplot as plt\nimport scipy.io as spio\n\nplt.ion()\n\ndirec = '/home/shekoofeh/data/LSTM_Keras/Datasets/Series'\n#direc = '/media/sf_Host_Share/tscRF_LSTM/MATLAB/Data Preparation/Datasets/Series'\ndataset = 'tsc_Sliding'\n\n# Initializing a few constant param\nsl = 100\nbatch_size = 100\nn_epoch = 2\nlearning_rate = 0.001\n\n# Load data\nprint(\"Loading is inputs ......\")\n\ndatadir = direc + '/' + dataset + '/'\n\nX_train = spio.loadmat(datadir+'D_TRAIN.mat')\nY_train = spio.loadmat(datadir+'L_TRAIN.mat')\nX_test = spio.loadmat(datadir+'D_TEST.mat')\nY_test = spio.loadmat(datadir+'L_TEST.mat')\n\nx_train = X_train['D_TRAIN'][:, 0:sl]\ny_train = Y_train['L_TRAIN'][:, 0]\nx_test = X_test['D_TEST'][:, 0:sl]\ny_test = Y_test['L_TEST'][:, 0]\n\n# reshape input to be [samples, time steps, features]\ntrainX = numpy.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))\ntestX = numpy.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))\n\nprint(\"Input is loaded, scaled and reshaped. \")\n\n# create the model\nprint(\"Defining the Model ..... \")\nmodel = Sequential()\nmodel.add(AveragePooling1D(pool_length=2, input_shape=(sl, 1)))\nmodel.add(LSTM(output_dim=sl/2, return_sequences=True, dropout_W=0.2, dropout_U=0.2, stateful=False, init='glorot_normal', activation='softsign'))\nmodel.add(AveragePooling1D(pool_length=2))\nmodel.add(LSTM(sl/4, dropout_W=0.2, dropout_U=0.2, return_sequences=False, init='glorot_normal', activation='softsign'))\n#model.add(AveragePooling1D(pool_length=2))\n#model.add(LSTM(sl/8, dropout_W=0.2, dropout_U=0.2, return_sequences=False, init='glorot_normal', activation='softsign'))\nmodel.add(Dense(1, activation='sigmoid', init='glorot_normal'))\n\nprint(\"Compiling the Model ..... \")\n#optimizer = kerasOpt.adam(lr=learning_rate, beta_1=0.8, beta_2=0.999, epsilon=1e-08, decay=0.0004)\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\nprint(model.summary())\nhistory = model.fit(trainX, y_train, validation_split=0.5, nb_epoch=n_epoch, batch_size=batch_size, shuffle=True)\n\n# list all data in history\nprint(history.history.keys())\n# summarize history for accuracy\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'validation'], loc='upper left')\nfig = plt.gcf()\nfig.savefig('Accuracy_plus_8.pdf')\nplt.show()\nplt.close()\n# summarize history for loss\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'validation'], loc='upper left')\nfig = plt.gcf()\nfig.savefig('Cost_plus_8.pdf')\nplt.show()\nplt.close()\n\nprint(\"Model is saved. \")\nmodel.save(datadir+'my_model_plus_8.h5')\n\n\nprint(\"Model Evaluation using test data... \")\n# Final evaluation of the model\nscores = model.evaluate(testX, y_test, verbose=0)\ny_predict = model.predict(testX, batch_size=batch_size, verbose=0)\nresults = {'softmax_output': y_predict , 'softmax_scores': scores, 'history': history.history}\nspio.savemat('RESULTS_TEST_plus_1.mat', {'results': results})\nprint(\"Accuracy: %.2f%%\" % (scores[1]*100))\n\n","sub_path":"backlog/LSTMdownsampled.py","file_name":"LSTMdownsampled.py","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"611570255","text":"\r\nimport random\r\n\r\nr = [random.randint(-99, 99) for _ in range(100)]\r\nprint(f'Массив: {r}')\r\n\r\nmin_index = 0\r\n\r\nfor i in r:\r\n if r[min_index] > i:\r\n min_index = r.index(i)\r\n\r\nif r[min_index] >= 0:\r\n print(f'В массиве нет отрицательных элементов')\r\nelse:\r\n print(f'В массиве минимальный отрицательный элемент: {r[min_index]}.',\r\n f'Находится в массиве на позиции {min_index}')\r\n","sub_path":"задание 5 к уроку 3.py","file_name":"задание 5 к уроку 3.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"518802430","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n\nclass Plotting():\n\n #def scatterplot(days, Y, predictedY):\n\n \"\"\"draws the scatterplot which shows the difference between predicted and actual Y.\"\"\"\n @staticmethod\n def scatterPlot(Y, predY):\n X = np.arange(0, len(Y))\n\n plt.xlim((min(X), max(X)))\n plt.xlabel('day')\n plt.ylabel('patients')\n plt.scatter(X, Y, c='red', label='Y')\n plt.scatter(X, predY, c='blue', label='predicted Y')\n plt.legend()\n plt.show()\n","sub_path":"plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"238887255","text":"# coding: utf-8\n\n# In[ ]:\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n# 1. Major Minor Rest contribution\ndef kde_den(data, cov=0.25):\n from scipy.stats import gaussian_kde\n density = gaussian_kde(data)\n xs = np.linspace(0,8,200)\n density.covariance_factor = lambda : cov\n density._compute_covariance()\n return density\n\ndef draw_kdes(dlM, dlm, dlo, dlt, ax\n , nevents\n , lw=1.5\n , excess=False):\n\n dM = kde_den(dlM)\n dm = kde_den(dlm)\n do = kde_den(dlo)\n dtot = kde_den(dlt)\n\n xs=np.linspace(-0.7,0.7,51)\n if excess:\n i_positive = np.linspace(0.0,0.6,26)\n dM_curve = dM(xs) - np.concatenate((dM(i_positive)[::-1], dM(i_positive[1:])))\n dm_curve = dm(xs) - np.concatenate((dm(i_positive)[::-1], dm(i_positive[1:])))\n do_curve = do(xs) - np.concatenate((do(i_positive)[::-1], do(i_positive[1:])))\n dtot_curve = dtot(xs) - np.concatenate((dtot(i_positive)[::-1], dtot(i_positive[1:])))\n else:\n dM_curve = dM(xs)\n dm_curve = dm(xs)\n do_curve = do(xs)\n dtot_curve = dtot(xs)\n\n nM = len(dlM)\n nm = len(dlm)\n no = len(dlo)\n ntot = len(dlt)\n\n\n Mlabel=\"Major \\n\" +r\"$N_{g}(N_{e})$\" + \" = {}({})\".format(nM, nevents[0])\n mlabel=\"Minor \\n\" +r\"$N_{g}(N_{e})$\" + \" = {}({})\".format(nm, nevents[1])\n olabel=\"Rest \\n\" +r\"$N_{g}$\" + \" = {}\".format(no)\n totlabel=\"Total\\n\" +r\"$N_{g}$\" + \" = {}\".format(ntot)\n ax.plot(xs, dM_curve*nM/ntot, label=Mlabel, lw=lw, color=\"r\")\n ax.plot(xs, dm_curve*nm/ntot, label=mlabel, lw=lw, color=\"g\")\n ax.plot(xs, do_curve*no/ntot, label=olabel, lw=lw, color=\"b\")\n ax.plot(xs, dtot_curve, label=totlabel, lw=lw, color=\"black\")\n\n ax.set_ylim([0, 1.15*ax.get_ylim()[1]])\n\n\ndef kde_sci(mpgs\n ,mstar_cut_hard = 5e9\n ,mcut=1e10\n ,fname=\"figs/test\"\n ,base='./'\n ,nbins=21\n ,kde=True\n ,hist=True\n ,shade=True\n ,norm_hist=False\n ,pallette=\"muted\"\n ,ylim=None\n ,per_event=True\n ,per_galaxy=True\n ,detected=True\n ,maj_ratio = 4\n ,excess=True\n ,img_scale=1.0\n ,examplegal=None):\n\n\n fontsize_ticks = 6 * img_scale\n fontsize_name = 8 * img_scale\n fontsize_tick_label = 8 * img_scale\n fontsize_legend = 5 * img_scale\n\n from matplotlib.ticker import NullFormatter\n\n l_dl_e = []\n l_mr_e = []\n l_mass_e = []\n\n s_dl_e = []\n s_mr_e = []\n s_mass_e = []\n\n l_dlt_g=[]\n l_dlo_g=[]\n l_dlM_g=[]\n l_dlm_g=[]\n l_mass_g=[]\n\n s_dlt_g=[]\n s_dlo_g=[]\n s_dlM_g=[]\n s_dlm_g=[]\n s_mass_g=[]\n\n\n M_changed = 0\n m_changed = 0\n no_merger_count = 0\n count = 0\n Maj_small = 0\n for i, gal in enumerate(mpgs):\n mgal = gal.data[\"mstar\"][0]\n if mgal > mstar_cut_hard:\n delta_lambda_tot = np.average(gal.data['lambda_r'][:5]) - np.average(gal.data['lambda_r'][-5:])\n delta_lambda_major = 0\n delta_lambda_minor = 0\n\n # Large\n if mgal > mcut:\n if hasattr(gal, \"merger\"):\n if gal.merger is not None:\n l_dl_e.extend(gal.merger.delta_l)\n l_mr_e.extend(gal.merger.mr)\n for dl, mr in zip(gal.merger.delta_l, gal.merger.mr):\n if (mr < maj_ratio) and (dl > -1):\n delta_lambda_major = delta_lambda_major + dl\n if (mr > maj_ratio) and (dl > -1):\n delta_lambda_minor = delta_lambda_minor + dl\n\n delta_lambda_other = delta_lambda_tot - delta_lambda_major - delta_lambda_minor\n l_dlt_g.append(delta_lambda_tot)\n l_dlo_g.append(delta_lambda_other)\n l_dlM_g.append(delta_lambda_major)\n l_dlm_g.append(delta_lambda_minor)\n # small\n else:\n #s_mass_g.append(mgal)\n if hasattr(gal, \"merger\"):\n if gal.merger is not None:\n s_dl_e.extend(gal.merger.delta_l)\n s_mr_e.extend(gal.merger.mr)\n for dl, mr in zip(gal.merger.delta_l, gal.merger.mr):\n if (mr < maj_ratio) and (dl > -1):\n delta_lambda_major = delta_lambda_major + dl\n if (mr > maj_ratio) and (dl > -1):\n delta_lambda_minor = delta_lambda_minor + dl\n\n delta_lambda_other = delta_lambda_tot - delta_lambda_major - delta_lambda_minor\n s_dlt_g.append(delta_lambda_tot)\n s_dlo_g.append(delta_lambda_other)\n s_dlM_g.append(delta_lambda_major)\n s_dlm_g.append(delta_lambda_minor)\n\n l_dlt_g = np.array(l_dlt_g)\n l_dlo_g = np.array(l_dlo_g)\n l_dlM_g = np.array(l_dlM_g)\n l_dlm_g = np.array(l_dlm_g)\n\n s_dlt_g = np.array(s_dlt_g)\n s_dlo_g = np.array(s_dlo_g)\n s_dlM_g = np.array(s_dlM_g)\n s_dlm_g = np.array(s_dlm_g)\n\n # detected\n l_dlM_g = l_dlM_g [l_dlM_g !=0]\n l_dlm_g = l_dlm_g [l_dlm_g !=0]\n\n s_dlM_g = s_dlM_g [s_dlM_g !=0]\n s_dlm_g = s_dlm_g [s_dlm_g !=0]\n\n l_dl_e = np.array(l_dl_e)\n l_mr_e = np.array(l_mr_e)\n\n s_dl_e = np.array(s_dl_e)\n s_mr_e = np.array(s_mr_e)\n\n fig, axs = plt.subplots(3, sharex=True)\n fig.set_size_inches(4.75,7)\n plt.subplots_adjust(hspace=0.01)\n\n all_dlM_g = np.concatenate((l_dlM_g,s_dlM_g))\n all_dlm_g = np.concatenate((l_dlm_g,s_dlm_g))\n all_dlo_g = np.concatenate((l_dlo_g,s_dlo_g))\n all_dlt_g = np.concatenate((l_dlt_g,s_dlt_g))\n\n draw_kdes(all_dlM_g,\n all_dlm_g,\n all_dlo_g,\n all_dlt_g,\n axs[0],\n [sum(s_mr_e < maj_ratio) + sum(l_mr_e < maj_ratio),\n sum(s_mr_e > maj_ratio) + sum(l_mr_e > maj_ratio),\n len(all_dlo_g)],\n excess=excess)\n\n draw_kdes(l_dlM_g,\n l_dlm_g,\n l_dlo_g,\n l_dlt_g,\n axs[1],\n [sum(l_mr_e < maj_ratio),\n sum(l_mr_e > maj_ratio),\n len(l_dlo_g)],\n excess=excess)\n\n draw_kdes(s_dlM_g,\n s_dlm_g,\n s_dlo_g,\n s_dlt_g,\n axs[2],\n [sum(s_mr_e < maj_ratio),\n sum(s_mr_e > maj_ratio),\n len(s_dlo_g)],\n excess=excess)\n\n axs[0].set_xlim([-0.6,0.6])\n for ax in axs:\n ax.xaxis.grid()\n leg = ax.legend(fontsize=fontsize_legend)\n leg.get_frame().set_alpha(0.5)\n ax.yaxis.set_major_formatter(NullFormatter())\n ax.set_ylabel(\"relative probability\", fontsize=fontsize_tick_label)\n\n axs[2].set_xlabel(r\"$\\Delta \\lambda_{R_{eff}}$\", fontsize=fontsize_tick_label, family=\"Liberation Sans\")\n axs[2].tick_params(labelsize=fontsize_ticks)\n axs[2].set_xlim([-0.7,0.6])\n #axs[0].legend(fontsize=12)\n\n axs[0].text(0.05, 0.87, \"(A)\", weight=\"bold\", transform=axs[0].transAxes, fontsize=fontsize_name)\n axs[0].text(0.15, 0.87, \"All\",transform=axs[0].transAxes, fontsize=fontsize_name)\n axs[1].text(0.05, 0.87, \"(B) \", weight=\"bold\",transform=axs[1].transAxes, fontsize=fontsize_name)\n axs[1].text(0.15, 0.87, r\"$log_{10}M_{\\star} > $ \" +\"{:.1f}\".format(np.log10(mcut))\n , fontsize=fontsize_name\n , transform=axs[1].transAxes)\n axs[2].text(0.05, 0.87, \"(C) \", weight=\"bold\",transform=axs[2].transAxes, fontsize=fontsize_name)\n axs[2].text(0.15, 0.87, r\"$log_{10}M_{\\star} < $ \" +\"{:.1f}\".format(np.log10(mcut))\n , fontsize=fontsize_name\n , transform=axs[2].transAxes)\n\n if examplegal is not None:\n dls = examplegal.merger.delta_l\n mrs = examplegal.merger.mr\n\n for dl, mr in zip(dls, mrs):\n if mr < maj_ratio:\n axs[0].scatter(dl, [0.15], facecolor='r', edgecolor=\"w\", marker=\"d\", s=40, zorder=20)\n else:\n axs[0].scatter(dl, [0.15], facecolor='g', edgecolor=\"w\", marker=\"d\", s=40, zorder=20)\n\n dl_tot = examplegal.data[\"lambda_r\"][0] - examplegal.data[\"lambda_r\"][-1]\n axs[0].scatter(dl_tot, [0.15], facecolor='black', edgecolor=\"w\", marker=\"d\", s=40, zorder=20)\n dl_o = dl_tot - sum(examplegal.merger.delta_l)\n axs[0].scatter(dl_o, 0.15, facecolor='b', edgecolor=\"w\", marker=\"d\", s=40, zorder=20)\n\n # legend\n axs[0].scatter(0.21, 1, facecolor='none', edgecolor=\"black\", marker=\"d\", s=40)\n axs[0].text(0.24, 0.95, \"example galaxy\", fontsize=8)\n print(\"Example gal\")\n\n\n plt.savefig(fname + \"{:.1f}.png\".format(np.log10(mcut)), dpi=200, bbox_inches=\"tight\")\n plt.savefig(fname + \"{:.1f}.pdf\".format(np.log10(mcut)), bbox_inches='tight') # eps does NOT support transparency!\n plt.savefig(fname + \"{:.1f}.eps\".format(np.log10(mcut)), bbox_inches='tight')\n plt.savefig(fname + \"{:.1f}.svg\".format(np.log10(mcut)), bbox_inches='tight')\n\n plt.close()\n\n\n# 2. Lambda Vs. Ellipticity\ndef plot_density_map(axmain, x, y, xmin, xmax, ymin, ymax,\n levels=None, color=True, cmap=\"winter\",\n surf=False, bw_method=\"silverman\",\n d_alpha=1.0):\n import scipy.stats as st\n # Draw main density map\n xx, yy = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]\n positions = np.vstack([xx.ravel(), yy.ravel()])\n\n values = np.vstack([x, y])\n kernel = st.gaussian_kde(values, bw_method=bw_method)\n f = np.reshape(kernel(positions).T, xx.shape)\n # , [0.2, 2, 3, 5, 10, 16] custom contour levels.\n f /= max(f.ravel())\n\n# ains = inset_axes(axmain, width='5%', height='60%', loc=5)\n if surf:\n cfset = axmain.contourf(xx, yy, f,\n levels=levels,\n cmap=cmap,\n alpha = d_alpha)#,\n\n else:\n cfset = axmain.contour(xx, yy, f,\n levels=levels,\n cmap=cmap,\n alpha = d_alpha,\n linewidths=0.6)\n\n return cfset\ndef plot_sami(ax, data, contour=True, scatter=False):\n x = data['ellp']\n y = data['r1']\n\n xmin, xmax = -0.05, 0.8\n ymin, ymax = -0.05, 0.8\n\n if contour:\n plot_densiy_map(ax, x, y, xmin, xmax, ymin, ymax,\n N=4,\n levels=None, color=False, cmap=\"spring\")\n if scatter:\n ax.scatter()\n\ndef density_map(x, y, sort=True):\n from scipy.stats import gaussian_kde\n xy = np.vstack([x,y])\n z = gaussian_kde(xy)(xy)\n z /= max(z)\n\n idx = z.argsort()\n xx, yy = x[idx], y[idx]\n z = z[idx]\n\n #im = ax.scatter(xx, yy, c=z, s=50, edgecolor='')\n return xx,yy,z\n\ndef do_plot(x,y, obsdata,\n do_scatter=True,\n contour_label=False,\n surf = False,\n img_scale = 1.0,\n twocolors=['#4c72b0', '#c44e52'],\n den_cmap = \"YlGnBu_r\",\n levels=None,\n fname_vs_e = \"./figs/lambda_vs_e_z0\",\n d_alpha=1.0,\n sizeOfFont=12,\n label=\"This work\",\n label2=\"\",\n title=\"\",\n ):\n import scipy.stats as st\n\n fontsize_ticks = 6 * img_scale\n fontsize_tick_label = 8 * img_scale\n fontsize_legend = 5 * img_scale\n img_size_single_column =2.25 * img_scale\n\n from matplotlib import rc, font_manager\n\n ticks_font = None\n\n xmin = ymin = -0.05\n xmax = ymax = 0.9\n\n fig, axmain=plt.subplots(1)\n\n fig.set_size_inches(img_size_single_column,\n img_size_single_column)\n\n axmain.set_xlim(xmin, xmax)\n axmain.set_ylim(ymin, ymax)\n # suppress last tick\n axmain.set_xticks(np.arange(0, xmax, 0.1))\n axmain.set_yticks(np.arange(0, ymax, 0.1))\n axmain.set_xlabel(r\"$\\epsilon_{R_{eff}}$\", fontsize=fontsize_tick_label, family=\"Liberation Sans\")\n axmain.set_ylabel(r\"$\\lambda_{R_{eff}}$\", fontsize=fontsize_tick_label)#, family=\"Liberation Sans\")\n axmain.tick_params(axis='both', which='major', labelsize=fontsize_ticks)\n# for label in axmain.get_xticklabels():\n# label.set_fontproperties(ticks_font)\n# for label in axmain.get_yticklabels():\n# label.set_fontproperties(ticks_font)\n #axmain.set_xticklabels(axmain.get_xticks(), family=\"helvetica\")\n #axmain.set_yticklabels(axmain.get_yticks(), family=\"helvetica\")\n\n # S/R demarcation line\n sr_line_xx = np.arange(90)*0.01\n # Simple demarkation (Emsellem 2011)\n sr_line_yy = 0.31 * np.sqrt(sr_line_xx)\n axmain.plot(sr_line_xx, sr_line_yy, '--', lw=1, color='black')\n\n # Draw main density map\n if surf:\n fname_vs_e = fname_vs_e + \"_srf\"\n elif contour_label:\n fname_vs_e = fname_vs_e + \"_cl\"\n try:\n nlevels = str(len(levels))\n except:\n nlevels = \"default\"\n fname_vs_e = fname_vs_e + \"_\" + nlevels\n\n if 1 == 2:\n cfset = plot_density_map(axmain, x, y, xmin, xmax, ymin, ymax,\n levels=levels,\n cmap=den_cmap,\n surf=True,\n d_alpha=d_alpha)\n\n if 1==1:\n xx,yy,z = density_map(x, y)\n axmain.scatter(xx, yy, c=z, s=15, edgecolor='',\n cmap=den_cmap, rasterized=False,\n alpha=1.0, label=label)\n\n if do_scatter:\n scatter = axmain.scatter(x,y, s=7,\n facecolor=twocolors[0],\n edgecolor='none',\n alpha= 0.7,\n label=label)\n fname_vs_e = fname_vs_e + \"_sct\"\n\n if 1 == 3:\n cfset = plot_density_map(axmain, x, y, xmin, xmax, ymin, ymax,\n levels=levels,\n cmap=\"winter\",\n surf=False,\n d_alpha=d_alpha)\n # My data\n if contour_label:\n axmain.clabel(cfset, inline=1, fontsize=7)\n\n #Observation data\n if obsdata is not None:\n axmain.scatter(obsdata[:,0], obsdata[:,1],\n s=40,\n color=twocolors[1],\n marker=\".\",\n lw=1,\n alpha=0.8,\n edgecolor='none',\n label=label2)\n\n # Legend\n if 1 == 2:\n handles, labels = axmain.get_legend_handles_labels()\n #Create custom artists\n thisArtist = plt.Line2D((0,1),(0,0), color='k', marker='o', linestyle='')\n #Create legend from custom artist/label lists\n handles.append(thisArtist)\n labels.append(label)\n axmain.legend(handles, labels,\n loc=2,\n borderaxespad=0.,\n labelspacing=1.2,\n fontsize=fontsize_legend)\n else:\n axmain.legend(loc=2,\n borderaxespad=0.,\n labelspacing=1.2,\n fontsize=fontsize_legend)\n\n plt.savefig(fname_vs_e + \".pdf\", bbox_inches='tight')\n plt.savefig(fname_vs_e + \".png\", bbox_inches='tight', dpi=200)\n axmain.set_title(title)\n plt.close()\n\ndef truncate_colormap(cmap_name, minval=0.0, maxval=1.0, n=100):\n \"\"\"\n Use only part of color maps\n \"\"\"\n import matplotlib.colors as colors\n cmap = plt.get_cmap(cmap_name)\n new_cmap = colors.LinearSegmentedColormap.from_list(\n 'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),\n cmap(np.linspace(minval, maxval, n)))\n return new_cmap\n\n# 3. Lambda evolution\n\nfrom astropy.cosmology import WMAP7, z_at_value\n\n#class Merger():\n# pass\n\ndef aexp2zred(aexp):\n return [1.0/a - 1.0 for a in aexp]\n\ndef zred2aexp(zred):\n return [1.0/(1.0 + z) for z in zred]\n\ndef lbt2aexp(lts):\n import astropy.units as u\n zreds = [z_at_value(WMAP7.lookback_time, ll * u.Gyr) for ll in lts]\n return [1.0/(1+z) for z in zreds]\n\n\ndef age2zred(lts):\n import astropy.units as u\n zreds = [z_at_value(WMAP7.age, ll * u.Gyr) for ll in lts]\n return zreds\n\ndef l_at_smoothed_r(gal, npix_per_reff=5):\n import analysis.Major_Minor_accretion as mma\n n_valid_points = sum(gal.data[\"reff\"] > 0)\n new_l_arr = np.zeros(n_valid_points)\n new_reff = mma.smooth(gal.data[\"reff\"])#[gal.data[\"reff\"] > 0])\n for i in range(n_valid_points):\n try:\n lambdar = gal.data[\"lambda_arr\"][i]\n ind_org = npix_per_reff - 1\n #i_new = # 0-indexed.\n ind_new = new_reff[i]/gal.data[\"reff\"][i] * ind_org\n il = np.fix(ind_new).astype(int)\n ir = il + 1\n if ir >= len(lambdar):\n new_l_arr[i] = lambdar[-1]\n else:\n new_l_arr[i] = lambdar[il]*(ir-ind_new) + lambdar[ir]*(ind_new-il)\n #new_l_arr[i] = lambdar[il]*(ir-ind_org) + lambdar[ir]*(ind_org-il)\n except:\n new_l_arr[i] = gal.data[\"lambda_arr\"][i] # = 0 with bad measurements.\n return new_l_arr\n\n\ndef density_map(x, y, sort=True):\n from scipy.stats import gaussian_kde\n xy = np.vstack([x,y])\n z = gaussian_kde(xy)(xy)\n z /= max(z)\n\n idx = z.argsort()\n xx, yy = x[idx], y[idx]\n z = z[idx]\n\n #im = ax.scatter(xx, yy, c=z, s=50, edgecolor='')\n return xx,yy,z\n\n\ndef modify_ticks(zreds, aexps, ax, ax2, nout_ini, nout_fi):\n modify_ticks1(zreds, aexps, ax, nout_ini, nout_fi)\n modify_ticks2(zreds, aexps, ax2, nout_ini, nout_fi)\n\ndef modify_ticks1(zreds, aexps, ax, nout_ini, nout_fi, fontsize=12):\n nbins = 40 # along the y-axis.\n nnouts = nout_fi - nout_ini + 1\n\n # For a given list of nouts,\n # calculate a nice-looking set of zreds AND lookback times\n zz_target = [0, 0.5, 1.0, 2.0, 3.0]#[::-1]\n x_tick_pos =np.array([187, 120, 87, 54, 37]) - nout_ini\n #x_tick_pos = np.searchsorted(zreds[::-1], zz_target)[::-1]# + nout_ini# + nout_min\n # searchsorted requires arrays be in ascending order.\n\n ax.set_xlabel(\"Redshift\", fontsize=fontsize, family=\"Liberation Sans\")\n ax.set_xlim([0, nnouts])\n\n ax.set_xticks(x_tick_pos)#[::-1])\n ax.set_xticklabels(labels = [\"{:0.1f}\".format(z) for z in zz_target])\n\n\ndef modify_ticks2(zreds, aexps, ax2, nout_ini, nout_fi):\n nbins = 40 # along the y-axis.\n nnouts = nout_fi - nout_ini + 1\n\n # For a given list of nouts,\n # calculate a nice-looking set of zreds AND lookback times\n zz_target = [0, 0.2, 0.5, 1.0, 2.0, 3.0]#[::-1]\n x_tick_pos = np.searchsorted(zreds[::-1], zz_target)[::-1]# + nout_ini# + nout_min\n # searchsorted requires arrays be in ascending order.\n\n # at z = 3, lbt = 11.5243, age of universe = 2.18844\n u_age_targets=[3,5,8,10,13]\n u_age_target_str=[\"{:.0f}\".format(l) for l in u_age_targets]\n z_targets_u_age = age2zred(u_age_targets)\n u_age_pos = np.searchsorted(zreds[::-1], z_targets_u_age)[::-1]\n\n ax2.set_xticks(u_age_pos)\n ax2.set_xticklabels(labels = u_age_target_str)\n ax2.set_xlabel(\"Age of the universe (Gyr)\", family=\"Liberation Sans\")\n\n\ndef plot_lambda_evol3(mpgs, fig, axs, nout_ini, nout_fi,\n wdir_info='./',\n density = \"none\",\n cmap =\"jet\",\n img_scale=1.0,\n sizeOfFont=9):\n\n fontsize_ticks = 6 * img_scale\n fontsize_tick_label = 8 * img_scale\n fontsize_legend = 5 * img_scale\n\n from matplotlib import rc, font_manager\n fontProperties = {'family':'Liberation Sans',\n 'weight' : 'normal', 'size' : sizeOfFont}\n ticks_font = font_manager.FontProperties(family='Liberation Sans', style='normal',\n size=sizeOfFont, weight='normal', stretch='normal')\n rc('text', usetex=True)\n rc('font',**fontProperties)\n\n\n nnouts = nout_fi - nout_ini + 1\n ngals_tot = len(mpgs)\n lambda_evol_all = np.zeros([ngals_tot, nnouts])\n\n # Starting nouts of galaxies are different.\n # But all end at nout = 187.\n for igal, gal in enumerate(mpgs):\n for inout, nout in enumerate(gal.nouts):\n lambda_evol_all[igal][nout - nout_ini] = gal.data['lambda_r'][inout]\n\n\n # change ticks\n zreds=[]\n aexps=[]\n\n # Only nout_ini < nout < nout_fi values are taken.\n # So are the x ticks.\n import load\n for nout in range(nout_ini, nout_fi + 1):\n info = load.info.Info(nout=nout, base=wdir_info, load=True)\n aexps.append(info.aexp)\n zreds.append(info.zred)\n aexps = np.array(aexps)\n zreds = np.array(zreds)\n\n modify_ticks1(zreds, aexps, axs[2], nout_ini, nout_fi, fontsize=fontsize_tick_label)\n\n if density == \"hexbin\":\n xx = np.tile(np.arange(nnouts), ngals_tot)\n all_data = lambda_evol_all.ravel()\n ind_ok = all_data > 0.01\n #xx,yy,z = density_map(xx[ind_ok], all_data[ind_ok])\n for ax in axs:\n im = ax.hexbin(xx[ind_ok], all_data[ind_ok],\n gridsize=int(nnouts/3),\n bins=None,\n cmap=cmap)\n yticks_ok=[0.0, 0.2, 0.4, 0.6, 0.8]\n ax.set_ylim([-0.1, 0.9])\n ax.set_yticks([0.0, 0.2, 0.4, 0.6, 0.8])\n ax.set_yticklabels([str(yy) for yy in yticks_ok])\n ax.set_ylabel(r\"$\\lambda_{R_{eff}}$\", fontsize=fontsize_tick_label, family=\"Liberation Sans\")\n ax.tick_params(axis='both', which='major', labelsize=fontsize_ticks, family=\"Liberation Sans\")\n\n elif density == \"kernel\":\n xx = np.tile(np.arange(nnouts), ngals_tot)\n all_data = lambda_evol_all.ravel()\n\n ind_ok = all_data > 0.01\n lambda_range=[0.01, 0.8]\n xx,yy,z = density_map(xx[ind_ok], all_data[ind_ok])\n\n for ax in axs:\n ax.scatter(xx, yy, c=z, s=50, edgecolor='', cmap=cmap, rasterized=True)\n\n return zreds, aexps\n\n\n\ndef simple_evol_path(gg, dt=10):\n \"\"\"\n return mass and lambda at point (by taking averages?)\n \"\"\"\n nout = []\n mass = []\n lamb = []\n\n for i in range(len(gg.nouts)-1, 0, -dt):\n nout.append(gg.nouts[i])\n mass.append(gg.data[\"mstar\"][i])\n lamb.append(gg.smoothed_lambda[i])\n return np.array(nout), np.array(mass), np.array(lamb)\n\ndef plot_minor(twogals, ax, suptitle=\"\",\n normalize=True,\n style=\"arrow\",\n nout_ini=37,\n img_scale=2.0,\n annotate=\"(B )\",\n arrow_scale = 40):\n import matplotlib as mpl\n \"\"\"\n Up to 4 galaxies in a plot\n \"\"\"\n #im = pickle.load(open(\"lambda_evol_all.pickle\", \"rb\"))\n #im.axes.set_ybound([-0.1, 0.85])\n\n fontsize_ticks = 8 * img_scale\n fontsize_tick_label = 8 * img_scale\n fontsize_legend = 7 * img_scale\n img_size_single_column =2.25 * img_scale\n\n loc = [0, 0, 0, 0]\n if len(twogals) == 2:\n if twogals[0].smoothed_lambda[-1] < twogals[1].smoothed_lambda[-1]:\n loc[1] = 0.65\n else:\n loc[0] = 0.65\n\n #ax.set_title(suptitle)\n\n for igal, gg in enumerate(twogals):\n if len(gg.smoothed_lambda) > 100:\n nn, mm, ll = simple_evol_path(gg)\n nn -= nout_ini\n if normalize:\n widths = (mm[:-1]/mm[-1])\n else:\n widths = np.sqrt(mm[:-1]/1e9)\n for i in range(len(mm)-1):\n #mm = im.axes.quiver(nn[i], ll[i], nn[i+1]-nn[i], ll[i+1]-ll[i],\n if style==\"arrow\":\n ax.arrow(nn[i], ll[i], nn[i+1]-nn[i], ll[i+1]-ll[i],\n fc=\"none\",\n ec=[\"red\", \"green\", \"yellow\", \"white\"][igal],\n alpha=0.5,\n width=widths[i],\n head_width=10 * widths[i],\n head_length=2000 * widths[i])\n\n elif style==\"quiver\":\n #ax.quiver(nn[:-1], ll[:-1], nn[1:]-nn[:-1], ll[1:]-ll[:-1],\n ax.quiver(nn[i], ll[i], nn[i+1]-nn[i], ll[i+1]-ll[i],\n scale_units='xy', angles='xy', scale=1,\n linewidth = 0.5,\n headwidth = 2 * widths[i]**0.5,\n headlength = 0.5 * widths[i],\n #headaxislength = 0.3 * widths[i],\n alpha=0.3, facecolor=\"none\",\n edgecolor=[\"red\", \"green\", \"yellow\", \"white\"][igal])\n #linewidth = 0.005 * widths[i]**3,\n # distance between two points differ since x distance is fixed but\n # y distance changes. So fixed headeraxislength results in changing\n # head shape. It's not trivial to retain the shape of arrows.\n elif style==\"stream\":\n patch = mpl.patches.FancyArrowPatch(\n (nn[i], ll[i]), (nn[i+1],ll[i+1]),\n arrowstyle=['->','-|>',\"fancy\",\"simple\",\"wedge\",\"-\"][3],\n mutation_scale=np.sqrt(widths[i]) * arrow_scale,\n# lw=np.sqrt(widths[i]) * 5,\n edgecolor=[\"red\", \"green\", \"yellow\", \"white\"][igal],\n facecolor=\"white\",\n fill=True,\n joinstyle=['miter', 'round', 'bevel'][0],\n alpha = 0.5,\n arrow_transmuter=None,\n connectionstyle='Arc3',\n connector=None,\n patchA=None,\n patchB=None,\n shrinkA=2.0,\n shrinkB=2.0,\n mutation_aspect=None,\n dpi_cor=1.0)\n ax.add_patch(patch)\n # Draw edge once more to have vivid edge + transparent face\n patch = mpl.patches.FancyArrowPatch(\n (nn[i], ll[i]), (nn[i+1],ll[i+1]),\n arrowstyle=['->','-|>',\"fancy\",\"simple\",\"wedge\",\"-\"][3],\n mutation_scale=np.sqrt(widths[i]) * arrow_scale,\n edgecolor=[\"red\", \"green\", \"yellow\", \"white\"][igal],\n fill=False,\n joinstyle=['miter', 'round', 'bevel'][0],\n alpha = 0.3,\n arrow_transmuter=None,\n connectionstyle='Arc3',\n connector=None,\n patchA=None,\n patchB=None,\n shrinkA=2.0,\n shrinkB=2.0,\n mutation_aspect=None,\n dpi_cor=1.0)\n ax.add_patch(patch)\n\n if gg.merger is not None:\n for nouti, nout, mr in zip(gg.merger.nout_ini, gg.merger.nout, gg.merger.mr):\n #im.axes.axvline(nouti - nout_ini, linestyle=':')\n #im.axes.axvline(nout - nout_ini, linestyle=':')\n ypos_annotate = gg.smoothed_lambda[gg.nouts == nout] + 0.05\n ax.plot([nout-nout_ini, nout-nout_ini],\n [loc[igal], ypos_annotate - 0.1 + loc[igal] * 0.1/0.75],\n lw = 1,\n linestyle=\"--\",\n color = [\"red\", \"green\", \"yellow\", \"white\"][igal],\n alpha = 0.5)\n ax.annotate(\"{:.2f}\".format(1./mr),\n xy=(nout - nout_ini, 0.32 + ((loc[igal]) - 0.32) * 1.1),\n fontsize=fontsize_legend)\n # text slightly further than the end of dashed lines\n #ax.annotate(suptitle, xy=(5, 0.79), fontsize=fontsize_ticks)\n else:\n print(\"Too short\")\n ax.text(0.05, 0.9, annotate, weight=\"bold\",transform=ax.transAxes, fontsize=fontsize_ticks)\n ax.text(0.13, 0.9, suptitle, transform=ax.transAxes, fontsize=fontsize_ticks)\n\n\ndef plot_rest(twogals, ax,\n suptitle=\"\",\n normalize=True,\n style=\"arrow\",\n nout_ini=37,\n img_scale=2.0,\n annotate=\"(B )\",\n arrow_scale = 40):\n\n import matplotlib as mpl\n \"\"\"\n Up to 4 galaxies in a plot\n \"\"\"\n #im = pickle.load(open(\"lambda_evol_all.pickle\", \"rb\"))\n #im.axes.set_ybound([-0.1, 0.85])\n\n fontsize_ticks = 8 * img_scale\n fontsize_tick_label = 8 * img_scale\n #fontsize_legend = 5 * img_scale\n img_size_single_column =2.25 * img_scale\n\n loc = [0, 0, 0, 0]\n if len(twogals) == 2:\n if twogals[0].smoothed_lambda[-1] < twogals[1].smoothed_lambda[-1]:\n loc[1] = 0.65\n else:\n loc[0] = 0.65\n\n #ax.set_title(suptitle)\n\n for igal, gg in enumerate(twogals):\n if len(gg.smoothed_lambda) > 100:\n nn, mm, ll = simple_evol_path(gg)\n nn -= nout_ini\n if normalize:\n widths = (mm[:-1]/mm[-1])\n else:\n widths = np.sqrt(mm[:-1]/1e9)\n for i in range(len(mm)-1):\n patch = mpl.patches.FancyArrowPatch(\n (nn[i], ll[i]), (nn[i+1],ll[i+1]),\n arrowstyle=['->','-|>',\"fancy\",\"simple\",\"wedge\",\"-\"][3],\n mutation_scale=np.sqrt(widths[i]) * arrow_scale,\n# lw=np.sqrt(widths[i]) * 5,\n edgecolor=[\"red\", \"green\", \"yellow\", \"white\"][igal],\n facecolor=\"white\",\n fill=True,\n joinstyle=['miter', 'round', 'bevel'][0],\n alpha = 0.5,\n arrow_transmuter=None,\n connectionstyle='Arc3',\n connector=None,\n patchA=None,\n patchB=None,\n shrinkA=2.0,\n shrinkB=2.0,\n mutation_aspect=None,\n dpi_cor=1.0)\n ax.add_patch(patch)\n # Draw edge once more to have vivid edge + transparent face\n patch = mpl.patches.FancyArrowPatch(\n (nn[i], ll[i]), (nn[i+1],ll[i+1]),\n arrowstyle=['->','-|>',\"fancy\",\"simple\",\"wedge\",\"-\"][3],\n mutation_scale=np.sqrt(widths[i]) * arrow_scale,\n edgecolor=[\"red\", \"green\", \"yellow\", \"white\"][igal],\n fill=False,\n joinstyle=['miter', 'round', 'bevel'][0],\n alpha = 0.3,\n arrow_transmuter=None,\n connectionstyle='Arc3',\n connector=None,\n patchA=None,\n patchB=None,\n shrinkA=2.0,\n shrinkB=2.0,\n mutation_aspect=None,\n dpi_cor=1.0)\n ax.add_patch(patch)\n else:\n print(\"Too short\")\n ax.text(0.05, 0.9, annotate, weight=\"bold\",transform=ax.transAxes, fontsize=fontsize_ticks)\n ax.text(0.13, 0.9, suptitle, transform=ax.transAxes, fontsize=fontsize_ticks)\n\n\ndef plot_major(twogals, ax,\n suptitle=\"\",\n normalize=True,\n nout_ini=37,\n img_scale=2.0,\n arrow_scale = 40):\n import matplotlib as mpl\n\n fontsize_ticks = 8 * img_scale\n fontsize_tick_label = 8 * img_scale\n fontsize_legend = 7 * img_scale\n\n loc = [0, 0.65, 0, 0]\n\n for igal, gg in enumerate(twogals):\n if len(gg.smoothed_lambda) > 100:\n nn, mm, ll = simple_evol_path(gg)\n nn -= nout_ini\n if normalize:\n widths = (mm[:-1]/mm[-1])\n else:\n widths = np.sqrt(mm[:-1]/1e9)\n for i in range(len(mm)-1):\n patch = mpl.patches.FancyArrowPatch(\n (nn[i], ll[i]), (nn[i+1],ll[i+1]),\n arrowstyle=['->','-|>',\"fancy\",\"simple\",\"wedge\",\"-\"][3],\n mutation_scale=np.sqrt(widths[i]) * arrow_scale,\n# lw=np.sqrt(widths[i]) * 5,\n edgecolor=[\"red\", \"green\", \"yellow\", \"white\"][igal],\n facecolor=\"white\",\n fill=True,\n joinstyle=['miter', 'round', 'bevel'][0],\n alpha = 0.5,\n dpi_cor=1.0)\n ax.add_patch(patch)\n # Draw edge once more to have vivid edge + transparent face\n patch = mpl.patches.FancyArrowPatch(\n (nn[i], ll[i]), (nn[i+1],ll[i+1]),\n arrowstyle=['->','-|>',\"fancy\",\"simple\",\"wedge\",\"-\"][3],\n mutation_scale=np.sqrt(widths[i]) * arrow_scale,\n edgecolor=[\"red\", \"green\", \"yellow\", \"white\"][igal],\n fill=False,\n joinstyle=['miter', 'round', 'bevel'][0],\n alpha = 0.3,\n dpi_cor=1.0)\n ax.add_patch(patch)\n\n if gg.merger is not None:\n for nouti, nout, mr in zip(gg.merger.nout_ini, gg.merger.nout, gg.merger.mr):\n if mr < 4:\n ypos_annotate = gg.smoothed_lambda[gg.nouts == nout] + 0.05\n ax.plot([nout-nout_ini, nout-nout_ini],\n [loc[igal], ypos_annotate - 0.1 + loc[igal] * 0.1/0.75],\n lw = 1,\n linestyle=\"--\",\n color = [\"red\", \"green\", \"yellow\", \"white\"][igal],\n alpha = 0.5)\n ax.annotate(\"{:.2f}\".format(1./mr),\n xy=(nout - nout_ini, 0.32 + ((loc[igal]) - 0.32) * 1.1),\n fontsize=fontsize_legend)\n # text slightly further than the end of dashed lines\n\n else:\n print(\"Too short\")\n ax.text(0.05, 0.9, \"(A) \", weight=\"bold\",transform=ax.transAxes, fontsize=fontsize_ticks)\n ax.text(0.13, 0.9, suptitle, transform=ax.transAxes, fontsize=fontsize_ticks)\n","sub_path":"pyram/analysis/all_plot_modules.py","file_name":"all_plot_modules.py","file_ext":"py","file_size_in_byte":34433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"258426121","text":"\"\"\"\nWrap conda commandline program\n\"\"\"\nimport os\nimport subprocess\nimport json\nimport hashlib\nimport contextlib\nimport tempfile\nimport requests\nfrom distutils.version import LooseVersion as V\nfrom tljh import utils\n\n\ndef sha256_file(fname):\n \"\"\"\n Return sha256 of a given filename\n\n Copied from https://stackoverflow.com/a/3431838\n \"\"\"\n hash_sha256 = hashlib.sha256()\n with open(fname, \"rb\") as f:\n for chunk in iter(lambda: f.read(4096), b\"\"):\n hash_sha256.update(chunk)\n return hash_sha256.hexdigest()\n\n\ndef check_miniconda_version(prefix, version):\n \"\"\"\n Return true if a miniconda install with version exists at prefix\n \"\"\"\n try:\n installed_version = subprocess.check_output([\n os.path.join(prefix, 'bin', 'conda'),\n '-V'\n ], stderr=subprocess.STDOUT).decode().strip().split()[1]\n return V(installed_version) >= V(version)\n except (subprocess.CalledProcessError, FileNotFoundError):\n # Conda doesn't exist\n return False\n\n\n@contextlib.contextmanager\ndef download_miniconda_installer(installer_url, sha256sum):\n \"\"\"\n Context manager to download miniconda installer from a given URL\n\n This should be used as a contextmanager. It downloads miniconda installer\n of given version, verifies the sha256sum & provides path to it to the `with`\n block to run.\n \"\"\"\n with tempfile.NamedTemporaryFile() as f:\n with open(f.name, 'wb') as f:\n f.write(requests.get(installer_url).content)\n\n if sha256_file(f.name) != sha256sum:\n raise Exception('sha256sum hash mismatch! Downloaded file corrupted')\n\n yield f.name\n\n\ndef fix_permissions(prefix):\n \"\"\"Fix permissions in the install prefix\n\n For all files in the prefix, ensure that:\n - everything is owned by current user:group\n - nothing is world-writeable\n\n Run after each install command.\n \"\"\"\n utils.run_subprocess(\n [\"chown\", \"-R\", \"{}:{}\".format(os.getuid(), os.getgid()), prefix]\n )\n utils.run_subprocess([\"chmod\", \"-R\", \"o-w\", prefix])\n\n\ndef install_miniconda(installer_path, prefix):\n \"\"\"\n Install miniconda with installer at installer_path under prefix\n \"\"\"\n utils.run_subprocess([\n '/bin/bash',\n installer_path,\n '-u', '-b',\n '-p', prefix\n ])\n # fix permissions on initial install\n # a few files have the wrong ownership and permissions initially\n # when the installer is run as root\n fix_permissions(prefix)\n\n\ndef ensure_conda_packages(prefix, packages):\n \"\"\"\n Ensure packages (from conda-forge) are installed in the conda prefix.\n \"\"\"\n conda_executable = [os.path.join(prefix, 'bin', 'python'), '-m', 'conda']\n abspath = os.path.abspath(prefix)\n # Let subprocess errors propagate\n # Explicitly do *not* capture stderr, since that's not always JSON!\n # Scripting conda is a PITA!\n # FIXME: raise different exception when using\n raw_output = subprocess.check_output(conda_executable + [\n 'install',\n '-c', 'conda-forge', # Make customizable if we ever need to\n '--json',\n '--prefix', abspath\n ] + packages).decode()\n # `conda install` outputs JSON lines for fetch updates,\n # and a undelimited output at the end. There is no reasonable way to\n # parse this outside of this kludge.\n filtered_output = '\\n'.join([\n l for l in raw_output.split('\\n')\n # Sometimes the JSON messages start with a \\x00. The lstrip removes these.\n # conda messages seem to randomly throw \\x00 in places for no reason\n if not l.lstrip('\\x00').startswith('{\"fetch\"')\n ])\n output = json.loads(filtered_output.lstrip('\\x00'))\n if 'success' in output and output['success'] == True:\n return\n fix_permissions(prefix)\n\n\ndef ensure_pip_packages(prefix, packages):\n \"\"\"\n Ensure pip packages are installed in the given conda prefix.\n \"\"\"\n abspath = os.path.abspath(prefix)\n pip_executable = [os.path.join(abspath, 'bin', 'python'), '-m', 'pip']\n\n utils.run_subprocess(pip_executable + [\n 'install',\n '--no-cache-dir',\n ] + packages)\n fix_permissions(prefix)\n\n\ndef ensure_pip_requirements(prefix, requirements_path):\n \"\"\"\n Ensure pip packages from given requirements_path are installed in given conda prefix.\n\n requirements_path can be a file or a URL.\n \"\"\"\n abspath = os.path.abspath(prefix)\n pip_executable = [os.path.join(abspath, 'bin', 'python'), '-m', 'pip']\n\n utils.run_subprocess(pip_executable + [\n 'install',\n '-r',\n requirements_path\n ])\n fix_permissions(prefix)\n","sub_path":"tljh/conda.py","file_name":"conda.py","file_ext":"py","file_size_in_byte":4656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"394887661","text":"import pytest\nfrom dagster import (\n DagsterInvariantViolationError,\n execute_pipeline,\n graph,\n job,\n op,\n reconstructable,\n)\nfrom dagster.core.test_utils import instance_for_test\n\n\ndef define_the_job():\n @op\n def my_op():\n return 5\n\n @job\n def call_the_op():\n for _ in range(10):\n my_op()\n\n return call_the_op\n\n\ndef test_job_execution_multiprocess_config():\n with instance_for_test() as instance:\n result = execute_pipeline(\n reconstructable(define_the_job),\n instance=instance,\n run_config={\"execution\": {\"config\": {\"multiprocess\": {\"max_concurrent\": 4}}}},\n )\n\n assert result.success\n assert result.output_for_solid(\"my_op\") == 5\n\n\nresults_lst = []\n\n\ndef define_in_process_job():\n @op\n def my_op():\n results_lst.append(\"entered\")\n\n @job\n def call_the_op():\n for _ in range(10):\n my_op()\n\n return call_the_op\n\n\ndef test_switch_to_in_process_execution():\n result = execute_pipeline(\n define_in_process_job(),\n run_config={\"execution\": {\"config\": {\"in_process\": {}}}},\n )\n assert result.success\n assert len(results_lst) == 10\n\n\n@graph\ndef basic_graph():\n pass\n\n\nbasic_job = basic_graph.to_job() # type: ignore[union-attr]\n\n\ndef test_non_reconstructable_job_error():\n with pytest.raises(\n DagsterInvariantViolationError,\n match=\"you must wrap the ``to_job`` call in a function at module scope\",\n ):\n reconstructable(basic_job)\n","sub_path":"python_modules/dagster/dagster_tests/core_tests/definitions_tests/test_job.py","file_name":"test_job.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"516096182","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2012-2019, Erkan Ozgur Yilmaz\n#\n# This module is part of anima and is released under the MIT\n# License: http://www.opensource.org/licenses/MIT\n\nimport os\nimport tempfile\n\nfrom pymel import core as pm\n\n\nclass General(object):\n \"\"\"General tools\n \"\"\"\n\n transform_info_temp_file_path = os.path.join(\n tempfile.gettempdir(),\n 'transform_info'\n )\n\n @classmethod\n def unshape_parent_nodes(cls):\n \"\"\"Moves the shape node of a mesh to another transform node as a\n children if the mesh node has other meshes under it. Essentially\n cleaning the scene.\n \"\"\"\n mesh_nodes_with_transform_children = []\n all_meshes = pm.ls(dag=1, type='mesh')\n\n for node in all_meshes:\n parent = node.getParent()\n tra_under_shape = pm.ls(\n parent.listRelatives(),\n type='transform'\n )\n if len(tra_under_shape):\n mesh_nodes_with_transform_children.append(parent)\n\n for node in mesh_nodes_with_transform_children:\n # duplicate the node\n dup = pm.duplicate(node)[0]\n\n # remove all descendents\n all_descendents = dup.listRelatives(ad=1)\n # remove the shape from the list\n all_descendents.remove(dup.getShape())\n\n pm.delete(all_descendents)\n\n # parent under the original node\n pm.parent(dup, node)\n\n # remove the shape of the original node\n pm.delete(node.getShape())\n\n @classmethod\n def namespace_deleter(cls):\n \"\"\"the legendary namespace deleter from Mehmet Erer\n\n finds and deletes unused namespaces\n \"\"\"\n all_namespaces = pm.listNamespaces()\n ref_namespaces = [ref.namespace for ref in pm.listReferences()]\n missing_namespaces = []\n\n from anima.ui.progress_dialog import ProgressDialogManager\n if len(all_namespaces) > 0:\n pdm = ProgressDialogManager()\n pdm.close()\n\n caller = pdm.register(len(all_namespaces),\n 'Locating Unused Namespaces...')\n for nsa in all_namespaces:\n i = 0\n for nsr in ref_namespaces:\n i += 1\n if nsr == nsa:\n break\n if i == len(ref_namespaces):\n missing_namespaces.append(nsa)\n caller.step()\n\n if len(missing_namespaces) > 0:\n caller = pdm.register(len(missing_namespaces),\n 'Deleting Unused Namespaces...')\n for ns in missing_namespaces:\n ns_info = pm.namespaceInfo(ns, lon=1, fn=1, r=1)\n if len(ns_info) > 0:\n nsc = ns_info[len(ns_info) - 1]\n nsc_array = nsc.split(':')\n if len(nsc_array) > 0:\n for del_nsc in nsc_array:\n pm.namespace(rm=del_nsc, mnr=1)\n else:\n pm.namespace(rm=ns, mnr=1)\n print ('Deleted -> :' + ns)\n caller.step()\n else:\n pm.warning(\n 'There are no first-level unused namespaces in this scene.'\n )\n\n if len(ref_namespaces) == 0 and len(all_namespaces) > 0:\n for ns in all_namespaces:\n pm.namespace(rm=ns, mnr=1)\n print ('Deleted -> : %s' % ns)\n pm.warning(\n 'There are no references in this scene. All empty namespaces '\n 'are deleted.'\n )\n\n @classmethod\n def version_creator(cls):\n \"\"\"version creator\n \"\"\"\n from anima.ui.scripts import maya\n maya.version_creator()\n\n @classmethod\n def export_transform_info(cls, use_global_pos=False):\n \"\"\"exports the transformation data in to a temp file\n \"\"\"\n data = []\n for node in pm.ls(sl=1, type='transform'):\n\n if use_global_pos:\n # print('using global position')\n tra = pm.xform(node, q=1, ws=1, t=1) # node.t.get()\n rot = pm.xform(node, q=1, ws=1, ro=1) # node.r.get()\n sca = pm.xform(node, q=1, ws=1, s=1) # node.s.get()\n pivr = pm.xform(node, q=1, ws=1, rp=1)\n pivs = pm.xform(node, q=1, ws=1, sp=1)\n\n else:\n # print('using local position')\n tra = node.t.get()\n rot = node.r.get()\n sca = node.s.get()\n pivr = node.rotatePivot.get()\n pivs = node.scalePivot.get()\n\n # print('tra: %0.3f %0.3f %0.3f' % (tra[0], tra[1], tra[2]))\n # print('rot: %0.3f %0.3f %0.3f' % (rot[0], rot[1], rot[2]))\n # print('sca: %0.3f %0.3f %0.3f' % (sca[0], sca[1], sca[2]))\n #\n # print('rotpiv: %0.3f %0.3f %0.3f' % (pivr[0], pivr[1], pivr[2]))\n # print('scapiv: %0.3f %0.3f %0.3f' % (pivs[0], pivs[1], pivs[2]))\n\n data.append('%s' % tra[0])\n data.append('%s' % tra[1])\n data.append('%s' % tra[2])\n\n data.append('%s' % rot[0])\n data.append('%s' % rot[1])\n data.append('%s' % rot[2])\n\n data.append('%s' % sca[0])\n data.append('%s' % sca[1])\n data.append('%s' % sca[2])\n\n data.append('%s' % pivr[0])\n data.append('%s' % pivr[1])\n data.append('%s' % pivr[2])\n\n data.append('%s' % pivs[0])\n data.append('%s' % pivs[1])\n data.append('%s' % pivs[2])\n\n with open(cls.transform_info_temp_file_path, 'w') as f:\n f.write('\\n'.join(data))\n\n @classmethod\n def import_transform_info(cls, use_global_pos=False):\n \"\"\"imports the transform info from the temp file\n \"\"\"\n\n with open(cls.transform_info_temp_file_path) as f:\n data = f.readlines()\n\n for i, node in enumerate(pm.ls(sl=1, type='transform')):\n j = i * 15\n if use_global_pos:\n # print('using global position')\n\n # import pivots first\n # rotatePivot\n pm.xform(\n node, ws=1,\n rp=(float(data[j + 9]),\n float(data[j + 10]),\n float(data[j + 11]))\n )\n\n # scalePivot\n pm.xform(\n node, ws=1,\n sp=(float(data[j + 12]),\n float(data[j + 13]),\n float(data[j + 14]))\n )\n\n pm.xform(\n node, ws=1,\n t=(float(data[j]),\n float(data[j + 1]),\n float(data[j + 2]))\n )\n pm.xform(\n node, ws=1,\n ro=(float(data[j + 3]),\n float(data[j + 4]),\n float(data[j + 5]))\n )\n pm.xform(\n node, ws=1,\n s=(float(data[j + 6]),\n float(data[j + 7]),\n float(data[j + 8]))\n )\n\n else:\n print('using local position')\n\n # set pivots first\n # rotatePivot\n node.rotatePivot.set(\n float(data[j + 9]), float(data[j + 10]), float(data[j + 11])\n )\n\n # scalePivot\n node.scalePivot.set(\n float(data[j + 12]), float(data[j + 13]), float(data[j + 14])\n )\n\n try:\n node.t.set(\n float(data[j]), float(data[j + 1]), float(data[j + 2])\n )\n except RuntimeError:\n pass\n\n try:\n node.r.set(\n float(data[j + 3]), float(data[j + 4]), float(data[j + 5])\n )\n except RuntimeError:\n pass\n\n try:\n node.s.set(\n float(data[j + 6]), float(data[j + 7]), float(data[j + 8])\n )\n except RuntimeError:\n pass\n\n # print('tra: %0.3f %0.3f %0.3f' %\n # (float(data[j]), float(data[j + 1]), float(data[j + 2])))\n # print('rot: %0.3f %0.3f %0.3f' %\n # (float(data[j + 3]), float(data[j + 4]), float(data[j + 5])))\n # print('sca: %0.3f %0.3f %0.3f' %\n # (float(data[j + 6]), float(data[j + 7]), float(data[j + 8])))\n # print('pivr: %0.3f %0.3f %0.3f' %\n # (float(data[j + 9]), float(data[j + 10]), float(data[j + 11])))\n # print('pivs: %0.3f %0.3f %0.3f' %\n # (float(data[j + 12]), float(data[j + 13]), float(data[j + 14])))\n\n @classmethod\n def export_component_transform_info(cls):\n \"\"\"exports the transformation data in to a temp file\n \"\"\"\n data = []\n for node in pm.ls(sl=1, fl=1):\n tra = pm.xform(node, q=1, ws=1, t=1) # node.t.get()\n\n data.append('%s' % tra[0])\n data.append('%s' % tra[1])\n data.append('%s' % tra[2])\n\n with open(cls.transform_info_temp_file_path, 'w') as f:\n f.write('\\n'.join(data))\n\n @classmethod\n def import_component_transform_info(cls):\n \"\"\"imports the transform info from the temp file\n \"\"\"\n with open(cls.transform_info_temp_file_path) as f:\n data = f.readlines()\n\n for i, node in enumerate(pm.ls(sl=1, fl=1)):\n j = i * 3\n pm.xform(node, ws=1, t=(float(data[j]), float(data[j + 1]), float(data[j + 2])))\n\n @classmethod\n def toggle_attributes(cls, attribute_name):\n \"\"\"toggles the given attribute for the given list of objects\n \"\"\"\n objs = pm.ls(sl=1)\n new_list = []\n\n attribute_count = 0\n set_to_state = 1\n\n for obj in objs:\n if obj.hasAttr(attribute_name):\n if obj.getAttr(attribute_name):\n attribute_count += 1\n new_list.append(obj)\n\n obj_count = len(new_list)\n\n if attribute_count == obj_count:\n set_to_state = 0\n\n for obj in new_list:\n obj.setAttr(attribute_name, set_to_state)\n\n @classmethod\n def dereferencer(cls):\n \"\"\"calls dereferencer\n \"\"\"\n selection = pm.ls()\n for item in selection:\n if pm.attributeQuery('overrideEnabled', node=item, exists=True):\n if not item.overrideEnabled.get(l=True):\n connections = pm.listConnections(item, d=True)\n in_layer = 0\n for i in range(0, len(connections)):\n if connections[i].type() == \"displayLayer\":\n in_layer = 1\n break\n if not in_layer:\n if not item.overrideDisplayType.get(l=True):\n item.overrideDisplayType.set(0)\n\n @classmethod\n def selection_manager(cls):\n from anima.env.mayaEnv import selection_manager\n selection_manager.UI()\n\n @classmethod\n def reference_selected_objects(cls):\n selection = pm.ls(sl=True)\n for item in selection:\n if item.overrideEnabled.get(se=True):\n item.overrideEnabled.set(1)\n if item.overrideDisplayType.get(se=True):\n item.overrideDisplayType.set(2)\n\n pm.select(cl=True)\n\n @classmethod\n def dereference_selected_objects(cls):\n selection = pm.ls(sl=True)\n for item in selection:\n if item.overrideEnabled.get(se=True):\n item.overrideEnabled.set(0)\n if item.overrideDisplayType.get(se=True):\n item.overrideDisplayType.set(0)\n\n pm.select(cl=True)\n\n @classmethod\n def remove_colon_from_names(cls):\n selection = pm.ls(sl=1)\n for item in selection:\n temp = item.split(':')[-1]\n pm.rename(item, temp)\n pm.ls(sl=1)\n\n @classmethod\n def remove_pasted(cls):\n \"\"\"removes the string 'pasted__' from selected object names\n \"\"\"\n rmv_str = \"pasted__\"\n [\n obj.rename(obj.name().split('|')[-1].replace(rmv_str, ''))\n for obj in pm.ls(sl=1)\n if rmv_str in obj.name()\n ]\n\n @classmethod\n def toggle_poly_meshes(cls):\n \"\"\"toggles mesh selection in the current panel\n \"\"\"\n panel_in_focus = pm.getPanel(wf=True)\n panel_type = pm.getPanel(typeOf=panel_in_focus)\n if panel_type == \"modelPanel\":\n poly_vis_state = pm.modelEditor(\n panel_in_focus,\n q=True,\n polymeshes=True\n )\n pm.modelEditor(\n panel_in_focus,\n e=True,\n polymeshes=(not poly_vis_state)\n )\n\n @classmethod\n def select_set_members(cls):\n selection = pm.ls(sl=1)\n if not selection:\n pass\n else:\n pm.select(selection[0].inputs())\n\n @classmethod\n def delete_unused_intermediate_shapes(cls):\n \"\"\"clears unused intermediate shape nodes\n \"\"\"\n ignored_node_types = [\n 'nodeGraphEditorInfo',\n 'shadingEngine',\n ]\n\n def filter_funct(x):\n return x.type() not in ignored_node_types\n\n unused_nodes = []\n for node in pm.ls(type=pm.nt.Mesh):\n if len(filter(filter_funct, node.inputs())) == 0 and \\\n len(filter(filter_funct, node.outputs())) == 0 \\\n and node.attr('intermediateObject').get():\n unused_nodes.append(node)\n pm.delete(unused_nodes)\n\n @classmethod\n def delete_all_sound(cls):\n pm.delete(pm.ls(type=\"audio\"))\n\n @classmethod\n def generate_thumbnail(cls):\n \"\"\"generates thumbnail for current scene\n \"\"\"\n from anima.env.mayaEnv import auxiliary\n reload(auxiliary)\n result = auxiliary.generate_thumbnail()\n if result:\n pm.informBox('Done!', 'Thumbnail generated successfully!')\n else:\n pm.informBox('Fail!', 'Thumbnail generation was unsuccessful!')\n\n @classmethod\n def cleanup_light_cameras(cls):\n \"\"\"Deletes all the light cameras in the current scene\n \"\"\"\n cameras_to_delete = []\n for node in pm.ls(type=['light', 'RedshiftPhysicalLight']):\n parent = node.getParent()\n cameras = parent.listRelatives(ad=1, type='camera')\n if cameras:\n cameras_to_delete.extend(cameras)\n\n pm.delete(cameras_to_delete)\n\n @classmethod\n def rename_unique(cls):\n \"\"\"renames the selected nodes with unique names\n \"\"\"\n import re\n [node.rename(re.sub('[\\d]+', '#', node.name()))\n for node in pm.selected()]\n\n @classmethod\n def rsproxy_data_importer(cls, path=''):\n \"\"\"Imports RsProxy data from Houdini\n\n Required point attributes\n pos\n rot\n sca\n \"\"\"\n from anima.env.mayaEnv import redshift\n\n if path == '':\n import os\n import tempfile\n path = os.path.join(\n tempfile.gettempdir(),\n 'rsproxy_info.json'\n )\n\n data_man = redshift.RSProxyDataManager()\n data_man.load(path)\n data_man.create()","sub_path":"anima/env/mayaEnv/general.py","file_name":"general.py","file_ext":"py","file_size_in_byte":15824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"263597667","text":"import parser\nimport database\nimport txtfile\nimport notify\nimport datetime\nimport os\n\nif __name__ == '__main__':\n try:\n os.chdir(os.path.abspath(\"/data/applications/AMP\"))\n\n # Request, parse, get a list of AMP alerts.\n entry_list = parser.generate_entry_list()\n print(\"Successfully got and parsed data\")\n\n # Save data to database.\n database.save_to_database(entry_list)\n print(\"Successfully inserted data to database\")\n\n # Generate report in form of a .txt file to display all alerts.\n txtfile.generate_report(entry_list)\n print(\"Successfully generated report\")\n\n # Send out the report through an email.\n notify.send_report()\n print(\"Successfully sent report\")\n print(\"Completed\")\n\n except Exception as e:\n # Send out the crash report through an email.\n txtfile.generate_err_report(e)\n notify.send_crash_report()\n print(\"Error Encountered, see crash log\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"622780436","text":"from setuptools import setup, find_packages\n\nVERSION = (1, 0, 3)\n\n__version__ = VERSION\n__versionstr__ = '.'.join(map(str, VERSION))\n\ninstall_requires = [\n 'ella>=2,<4',\n 'South>=0.7',\n]\n\ntest_requires = [\n 'nose',\n 'coverage',\n]\n\nsetup(\n name='ella_attachments',\n version=__versionstr__,\n description='Add attachments to Ella project',\n author='Ella Development Team',\n author_email='dev@ella-cms.com',\n license='BSD',\n url='https://github.com/ella/ella-attachments',\n\n packages=find_packages(\n where='.',\n exclude=('test_ella_attachments',)\n ),\n\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"Environment :: Web Environment\",\n \"Intended Audience :: Developers\",\n \"Operating System :: OS Independent\",\n \"Framework :: Django\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 2.5\",\n \"Programming Language :: Python :: 2.6\",\n \"Programming Language :: Python :: 2.7\",\n \"Topic :: Internet :: WWW/HTTP :: Dynamic Content\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ],\n\n include_package_data=True,\n install_requires=install_requires,\n\n test_suite='test_ella_attachments.run_tests.run_all',\n tests_require=test_requires,\n)\n","sub_path":"pypi_install_script/ella_attachments-1.0.3.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"174804974","text":"import sys\nimport os\nimport binary\nimport RSA\nimport primeArithmetic\n\nbinary_list = [] #String converted to binary\ncypher_list = [] #encoded string\ndecryp_list = [] #decrypted string\n\n# e_key = 7\n# d_key = 183343\n# N_ = 1285667\n\n#Key examples\n\n\n# 1117 1151 ->\n# Public key: N = 1285667 e = 7\n# Private key: N = 1285667 d = 183343\n\ne_key = 7\nd_key = 183343\nN_ = 1285667\n\n\n#primeArithmetic.print_Primes(100000,111111)\n#primeArithmetic.print_Primes(100,111)\nstring = u\"Heureux les simples d'esprit,\" + u\" le monde des cieux leur appartient.\"\n\n#First binary encode original string\n# for character in string:\n# binary_list.append(bin(ord(character))[2:]) #truncate 0b / pad to 8 characters\nbinary_list = binary.string2bits(string)\nprint(\"Binary string:\",binary_list)\nprint(\"\")\n\n#Second encrypt encoded string\nfor bin_value in binary_list:\n cypher_list.append(RSA.RSA_encrypt(bin_value,e_key,N_))\nprint(\"Cypher string: \",cypher_list)\nprint(\"\")\n\n#Third decrypt encrypted string\nfor cypher_value in cypher_list:\n decryp_list.append(RSA.RSA_decrypt(cypher_value,d_key,N_))\nprint(\"Decrypted cypher: \",decryp_list)\nprint(\"\")\n\n#Finally convert decoded string to text\nstring2 = binary.bits2string(decryp_list)\nprint(\"Decoded string:\\t\",string2)\n","sub_path":"encryption.py","file_name":"encryption.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"548128912","text":"import unittest\nfrom typing import List\nfrom pprint import pprint\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass Solution:\n def preorderTraversal(self, root: TreeNode) -> List[int]:\n res = []\n\n def sub(node):\n if not node:\n return\n res.append(node.val)\n sub(node.left)\n sub(node.right)\n\n sub(root)\n return res\n\n\nclass TestSolution(unittest.TestCase):\n\n def test_case_1(self):\n sol = Solution()\n pass\n\n # def test_edge_case_1(self):\n # s = Solution()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"Week_02/144_binary_tree_postorder_traversal.py","file_name":"144_binary_tree_postorder_traversal.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"323332267","text":"import os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\n\nimport random\nimport paddle\nimport paddle.fluid as fluid\nfrom rule_feature.feature_stacking.vector_stacking. config_feature_stacking import config\nfrom rule_feature.feature_stacking.vector_stacking.feature_stacking_data_feeder import train_mapper, val_mapper, data_reader\n\n# 网络结构定义\ndef stackingCnnModel(stacking):\n # fold 1 - 3\n # prediction = fluid.layers.fc(input=stacking, size=512, act='relu6')\n # prediction = fluid.layers.fc(input=prediction, size=512, act='relu6')\n # prediction = fluid.layers.dropout(prediction, 0.3)\n # prediction = fluid.layers.fc(input=prediction, size=9, act='softmax')\n\n #fold 4 - 5\n prediction = fluid.layers.fc(input=stacking, size=1024, act='relu')\n prediction = fluid.layers.fc(input=prediction, size=1024, act='relu')\n prediction = fluid.layers.dropout(prediction, 0.5)\n prediction = fluid.layers.fc(input=prediction, size=9, act='softmax')\n return prediction\n\n# 模型训练代码\ndef train():\n batch_size = 2000\n\n iters = 30000 // batch_size\n lr = config['lr']\n boundaries = [i * iters for i in config[\"num_epochs\"]]\n values = [ i * lr for i in config[\"lr_decay\"]]\n\n train_prog = fluid.Program()\n startup_prog = fluid.Program()\n with fluid.program_guard(train_prog, startup_prog):\n input_stacking = fluid.layers.data(shape=config['stacking_shape'], name='stacking')\n label = fluid.layers.data(shape=[1], name='label', dtype='int64')\n\n with fluid.unique_name.guard():\n out = stackingCnnModel(input_stacking)\n # 获取损失函数和准确率函数\n cost = fluid.layers.cross_entropy(out, label=label)\n avg_cost = fluid.layers.mean(cost)\n acc = fluid.layers.accuracy(out, label=label)\n\n # 获取训练和测试程序\n test_program = train_prog.clone(for_test=True)\n\n # 定义优化方法\n optimizer = fluid.optimizer.AdamOptimizer(learning_rate=fluid.layers.piecewise_decay(boundaries, values),\n regularization=fluid.regularizer.L2DecayRegularizer(1e-5))\n optimizer.minimize(avg_cost)\n\n # 定义一个使用GPU的执行器\n place = fluid.CUDAPlace(0) if config['use_gpu'] else fluid.CPUPlace()\n exe = fluid.Executor(place)\n # 进行参数初始化\n exe.run(startup_prog)\n\n file_list = os.listdir(config['root_path']+ 'ruleFeature/stacking/val_npy_vector/')\n random.shuffle(file_list)\n random.shuffle(file_list)\n random.shuffle(file_list)\n random.shuffle(file_list)\n random.shuffle(file_list)\n random.shuffle(file_list)\n random.shuffle(file_list)\n train_list = file_list[0:30000]\n val_list = file_list[30000:40000]\n\n train_reader = paddle.batch(reader=data_reader(train_list, train_mapper,\n config['root_path']+ 'ruleFeature/stacking/val_npy_vector/'), batch_size=batch_size)\n test_reader = paddle.batch(reader=data_reader(val_list, val_mapper,\n config['root_path']+ 'ruleFeature/stacking/val_npy_vector/'), batch_size=batch_size)\n\n # 定义输入数据维度\n feeder = fluid.DataFeeder(place=place, feed_list=[input_stacking, label])\n\n train_losses = []\n train_accs = []\n best_acc = 0\n for epoch in range(config['total_epochs']):\n for step, data in enumerate(train_reader()):\n train_loss, train_acc = exe.run(program=train_prog,\n feed=feeder.feed(data),\n fetch_list=[avg_cost, acc])\n train_losses.append(train_loss[0])\n train_accs.append(train_acc[0])\n\n # 每 100 个 batch 打印一次信息\n if step % 10 == 0 and step != 0:\n print('Epoch %d step %d: loss %0.5f accuracy %0.5f' %\n (epoch, step, sum(train_losses) / len(train_losses), sum(train_accs) / len(train_accs)))\n\n if step % 100 == 0 and step != 0:\n # 保存模型参数\n if not os.path.isdir(os.path.join(config['model_path'], str(epoch))):\n os.makedirs(os.path.join(config['model_path'], str(epoch)))\n fluid.io.save_params(exe, os.path.join(config['model_path'], str(epoch)), main_program=train_prog)\n\n # 进行测试\n test_accs = []\n test_costs = []\n for batch_id, data in enumerate(test_reader()):\n test_cost, test_acc = exe.run(program=test_program,\n feed=feeder.feed(data),\n fetch_list=[avg_cost, acc])\n test_accs.append(test_acc[0])\n test_costs.append(test_cost[0])\n # 求测试结果的平均值\n test_cost = (sum(test_costs) / len(test_costs))\n test_acc = (sum(test_accs) / len(test_accs))\n print('Test:%d, Cost:%0.5f, Accuracy:%0.5f' % (step, test_cost, test_acc))\n\n # 进行测试\n test_accs = []\n test_costs = []\n for batch_id, data in enumerate(test_reader()):\n test_cost, test_acc = exe.run(program=test_program,\n feed=feeder.feed(data),\n fetch_list=[avg_cost, acc])\n test_accs.append(test_acc[0])\n test_costs.append(test_cost[0])\n # 求测试结果的平均值\n test_cost = (sum(test_costs) / len(test_costs))\n test_acc = (sum(test_accs) / len(test_accs))\n print('Test:%d, Cost:%0.5f, Accuracy:%0.5f' % (step, test_cost, test_acc))\n\n # 保存模型参数\n if not os.path.isdir(os.path.join(config['model_path'], str(epoch))):\n os.makedirs(os.path.join(config['model_path'], str(epoch)))\n fluid.io.save_params(exe, os.path.join(config['model_path'], str(epoch)), main_program=train_prog)\n\nif __name__ == '__main__':\n train()","sub_path":"rule_feature/feature_stacking/vector_stacking/train_feature_stacking.py","file_name":"train_feature_stacking.py","file_ext":"py","file_size_in_byte":6145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"121231506","text":"\"\"\"\nClass to provide tesser methods, synchronous and asynchronous\n\nhttp://asyncio.readthedocs.io/en/latest/subprocess.html\nref tesser_time_trials.py\n\"\"\"\n\nimport asyncio\nimport logging\nfrom subprocess import Popen, PIPE, check_call, CalledProcessError, run\n\nimport aiofiles\n\n# logging\n\n# log = logging.getLogger(__name__)\n# log.addHandler(logging.NullHandler())\n\n\n# seperate logging file for ocr\nCLASSLOGGER = logging.getLogger(__name__)\nCLASSLOGGER.setLevel(logging.DEBUG)\n# create file handler which logs all debug messages\nfh = logging.FileHandler('ocr.log')\nfh.setLevel(logging.DEBUG)\n# create console handler with a higher log level\nch = logging.StreamHandler()\nch.setLevel(logging.CRITICAL)\n# create formatter and add it to the handlers\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nch.setFormatter(formatter)\nfh.setFormatter(formatter)\n# add the handlers to logger\nCLASSLOGGER.addHandler(ch)\nCLASSLOGGER.addHandler(fh)\n\n\nclass File_OCR:\n \"\"\"\n Andy Spence 22 January 2018\n Class to run async subprocess with tesser\n\n Does not have __await__ so user needs to call:\n read_tiff to read in the document and\n async_tesser to process the file\n \"\"\"\n\n version = '1.0'\n\n tesseract_version = '3.05.01'\n\n def __init__(self,\n tiff_file, # file name and path for tiff image\n exe_name='tesseract' # process executable\n ):\n self.tiff_file = tiff_file\n self.exe_name = exe_name\n\n async def read_tiff(self):\n \"\"\"read in contents of tiff file\"\"\"\n async with aiofiles.open(self.tiff_file, \"rb\") as fn:\n return await fn.read()\n\n async def async_tesser(self, file_object):\n \"\"\"\n OCR's a file type object.\n Asynchronous\n Will not accept an openCV image.\n Must be tiff file data, not file itself\n \"\"\"\n # todo-me retry\n args = [self.exe_name, 'stdin', 'stdout']\n\n CLASSLOGGER.debug('Spawning async subprocess with PIPES')\n\n try:\n process = await asyncio.create_subprocess_exec(\n *args,\n # stdin must a pipe to be accessible as process.stdin\n stdin=asyncio.subprocess.PIPE,\n # stdout must a pipe to be accessible as process.stdout\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE) # divert stderr to a sepereate Pipe\n # send data into the subprocess\n # read output\n stdout, stderr = await process.communicate(input=file_object)\n # Return cleaned stdout\n return stdout, stderr\n\n except Exception as e:\n CLASSLOGGER.warning('trapped an exception', e)\n stdout = ''\n stderr = ''\n return stdout, stderr\n\n\nclass Bytes_OCR:\n \"\"\"\n Andy Spence 30 January 2018\n\n Class to run async subprocess with tesser\n Differs from File_OCR in accepting a BytesIO object as input\n\n User needs to call:\n async_tesser to process the file\n \"\"\"\n\n version = '1.0'\n\n tesseract_version = '3.05.01'\n\n def __init__(self,\n exe_name='tesseract' # process executable\n ):\n self.exe_name = exe_name\n\n async def async_tesser(self, file_object, tag):\n \"\"\"\n OCR's a file type object.\n Asynchronous\n Will not accept an openCV image.\n Must be tiff file data, not file itself\n \"\"\"\n\n args = [self.exe_name, 'stdin', 'stdout']\n CLASSLOGGER.debug('Spawning async subprocess with PIPES for file {}'.format(tag))\n try:\n process = await asyncio.create_subprocess_exec(\n *args,\n # stdin must a pipe to be accessible as process.stdin\n stdin=asyncio.subprocess.PIPE,\n # stdout must a pipe to be accessible as process.stdout\n stdout=asyncio.subprocess.PIPE)\n # send data into the subprocess\n # read output\n CLASSLOGGER.debug('feeding data into sdtin PIPES for file {}'.format(file_object[:20]))\n stdout, stderr = await process.communicate(input=file_object)\n # Return cleaned stdout\n CLASSLOGGER.debug('received output stdout {}'.format(stdout))\n CLASSLOGGER.debug('received error stderr {}'.format(stderr))\n return stdout, stderr\n\n except Exception as e:\n CLASSLOGGER.warning('trapped an exception', e)\n print('CRITICAL OCR process exception')\n stdout = ''\n stderr = ''\n return stdout, stderr\n\n\nclass PdfOCR:\n \"\"\"\n Andy Spence April 2018\n\n Synchronous subprocess calls to tesser and poppler-utils to run tesser in pdf mode on a tiff file and generate\n an xml file for the output\n\n returns an equivalent http status code and the xml and pdf filenames\n \"\"\"\n\n def __init__(self,\n psm='-psm 1',\n oem='-oem 2',\n mode='pdf',\n quiet=True,\n ):\n\n self.psm = psm\n self.oem = oem\n self.mode = mode\n self.quiet = quiet\n\n def scan(self, filename):\n \"\"\"\n pass a tiff file to tesser for pdf OCR\n then pass the output file into pdftohtml to get xml output and readable pdf file\n\n filename is full path to the tiff file containing a single pdf page\n \"\"\"\n\n args = ['tesseract', filename, filename[:-5], self.psm, self.oem, self.mode]\n\n if self.quiet:\n args.extend(['quiet'])\n\n retcode_t, err = self.process_call_popen(*args)\n\n CLASSLOGGER.debug('tesser retcode: {}'.format(retcode_t))\n\n pdf_file = filename[:-5] + '.pdf'\n xml_file = filename[:-5] + '.xml'\n\n # convert tesser pdf output to html with a fn from poppler-utils\n args = ['pdftohtml', '-c', '-hidden', '-xml', pdf_file, xml_file]\n\n retcode_p = self.process_call(*args)\n\n CLASSLOGGER.debug('pdftohtml process retcode: {}'.format(retcode_p))\n\n # translate into HTTP type codes\n if (retcode_p != 0) or (retcode_t != 0):\n process_code = 400\n print('tesser sterr: {}'.format(err[1]))\n print('file: {}'.format(filename))\n else:\n process_code = 200\n\n return process_code, xml_file, pdf_file\n\n def process_call(self, *args):\n \"\"\"\n calls a subprocess defined by args\n \"\"\"\n\n try:\n ret_code = check_call(args)\n CLASSLOGGER.debug('subprocess retcode {}'.format(ret_code))\n except CalledProcessError as exp:\n CLASSLOGGER.debug('subprocess.CalledProcessError : {}'.format(exp))\n ret_code = 400\n\n return ret_code\n\n def process_call_popen(self, *args):\n \"\"\"\n calls a subprocess defined by args but using Popen\n\n captures stderr and suppress the output to the the console\n \"\"\"\n\n try:\n # input and output to files but feed stderr to a Pipe and then drop\n process = Popen(args, stderr=PIPE)\n err = process.communicate()\n ret_code = 0\n\n except CalledProcessError as exp:\n print('subprocess CalledProcessError: {}'.format(exp))\n ret_code = 400\n\n return ret_code, err\n\n\nclass TextOCR:\n \"\"\"\n Andy Spence April 2018\n\n Synchronous subprocess call to tesser on tiff file\n\n Does not read single digits for some reason\n\n returns an equivalent http status code and output to stdout and err to stderr\n \"\"\"\n\n def __init__(self,\n psm='-psm 1',\n oem='-oem 2',\n quiet=True,\n ):\n\n self.psm = psm\n self.oem = oem\n self.quiet = quiet\n\n def scan(self, filename):\n \"\"\"\n pass a tiff file to tesser for pdf OCR\n then pass the output file into pdftohtml to get xml output and readable pdf file\n\n filename is full path to the tiff file\n \"\"\"\n\n args = ['tesseract', filename, 'stdout', self.psm, self.oem]\n\n if self.quiet:\n args.extend(['quiet'])\n\n retcode_t, output, err = self.process_call_popen(*args)\n\n CLASSLOGGER.debug('tesser retcode: {}'.format(retcode_t))\n\n # translate into HTTP type codes\n if retcode_t != 0:\n process_code = 400\n print('tesser sterr: {}'.format(err[1]))\n print('file: {}'.format(filename))\n else:\n process_code = 200\n\n return process_code, output, err\n\n def process_call_popen(self, *args):\n \"\"\"\n calls a subprocess defined by args but using Popen\n\n captures stderr and suppress the output to the the console\n \"\"\"\n\n try:\n # input and output to files but feed stderr to a Pipe and then drop\n process = Popen(args, stdout=PIPE, stderr=PIPE)\n output, err = process.communicate()\n ret_code = 0\n\n except CalledProcessError as exp:\n print('subprocess CalledProcessError: {}'.format(exp))\n ret_code = 400\n\n return ret_code, output, err\n\n\n","sub_path":"src/Parse_data/page_class/wrangler/file_ocr.py","file_name":"file_ocr.py","file_ext":"py","file_size_in_byte":9207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"401903257","text":"import png\n\nMap = list[list[int]]\nCLine = list[tuple[int, int]]\n\n\ndef simulation_step(m: Map, in_x: int) -> tuple[Map, bool]:\n x = in_x\n y = 0\n\n while True:\n # Simulation is done\n if y == len(m)-1:\n return (m, True)\n\n if m[y+1][x] == 0:\n y += 1\n continue\n if m[y+1][x-1] == 0:\n y += 1\n x -= 1\n continue\n if m[y+1][x+1] == 0:\n y += 1\n x += 1\n continue\n break\n m[y][x] = 2\n\n return (m, False)\n\n\ndef clamp(v, lo, hi):\n return min(hi, max(lo, v))\n\n\ndef read_data() -> list[CLine]:\n with open(\"input.txt\", \"r\") as f:\n m_lines = []\n for line in f.readlines():\n coords = []\n for coord in line.strip().split(\"->\"):\n x, y = coord.split(\",\")\n coords.append((int(x), int(y)))\n m_lines.append(coords)\n return m_lines\n\n\ndef print_map(m: Map):\n t = ['.', '#', '\\033[32;1mo\\033[0m']\n for y in m:\n print(''.join(list(map(lambda v: t[v], y))))\n\n\ndef map_png(m: Map, filename: str):\n height = len(m)\n width = len(m[0])\n\n cmap = [(0, 0, 0), (255, 255, 255), (194, 178, 128)]\n\n img = []\n for y in range(height):\n row = ()\n for x in range(width):\n row = row + cmap[m[y][x]]\n img.append(row)\n with open(filename, \"wb\") as f:\n w = png.Writer(width, height, greyscale=False)\n w.write(f, img)\n\n\ndef bounding_box(lines: list[CLine]) -> tuple[tuple[int, int], int]:\n xs = []\n ys = []\n for line in lines:\n xs.extend([x for x, _ in line])\n ys.extend([y for _, y in line])\n\n min_x = min(xs)-1\n max_x = max(xs)+2\n\n max_y = max(ys)+1\n return ((min_x, max_x), max_y)\n\n\ndef generate_map(lines: list[CLine]):\n (min_x, max_x), max_y = bounding_box(lines)\n delta_x = max_x - min_x\n\n m = [[0]*delta_x for _ in range(max_y)]\n\n for line in lines:\n for idx in range(1, len(line)):\n start_x = line[idx-1][0]-min_x\n diff_x = line[idx][0] - line[idx-1][0]\n delta_x = clamp(diff_x, -1, 1)\n\n start_y = line[idx-1][1]\n diff_y = line[idx][1] - line[idx-1][1]\n delta_y = clamp(diff_y, -1, 1)\n\n for i in range(max(abs(diff_x), abs(diff_y))+1):\n m[i*delta_y + start_y][i*delta_x + start_x] = 1\n return m\n\n\ndef count_sand(m: Map) -> int:\n count = 0\n for row in m:\n count += len(list(filter(lambda x: x == 2, row)))\n return count\n\n\nif __name__ == \"__main__\":\n lines = read_data()\n m = generate_map(lines)\n (min_x, _), _ = bounding_box(lines)\n injection = 500 - min_x\n\n done = False\n while not done:\n m, done = simulation_step(m, injection)\n print(count_sand(m))\n # map_png(m, \"filled_1.png\")\n print_map(m)\n","sub_path":"2022/14/Python/proto1.py","file_name":"proto1.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"51615037","text":"from sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import train_test_split\n# sklearn 提供的归一化方法\nfrom sklearn import preprocessing\n# from sklearn.model_selection import cross_val_score\nimport numpy as np\n\n\ndef filematrix(filename):\n \"\"\"\n\n :param filename:\n :return:\n return_mat 特征矩阵\n class_label_vector 标签向量\n \"\"\"\n fr = open(filename)\n array_of_lines = fr.readlines()\n number_of_lines = len(array_of_lines)\n return_mat = np.zeros((number_of_lines, 3))\n\n class_label_vector = []\n index = 0\n for line in array_of_lines:\n line = line.strip()\n list_form_line = line.split('\\t')\n return_mat[index, :] = list_form_line[0:3]\n if list_form_line[-1] == 'didntLike':\n class_label_vector.append(1)\n elif list_form_line[-1] == 'smallDoses':\n class_label_vector.append(2)\n elif list_form_line[-1] == 'largeDoses':\n class_label_vector.append(3)\n index += 1\n return return_mat, class_label_vector\n\n\ndef test(return_mat, class_label_vector):\n \"\"\"\n\n :param return_mat:\n :param class_label_vector:\n :return:\n\n 结果:\n 使用划分数据集进行训练的正确率为: 76.8%\n \"\"\"\n X_train, X_test, y_train, y_test = train_test_split(return_mat, class_label_vector)\n knn = KNeighborsClassifier(n_neighbors= 3, algorithm= 'auto')\n # min_max_scaler = preprocessing.MinMaxScaler()\n # X_train_minmax = min_max_scaler.fit_transform()\n # 创建一个knn分类\n knn.fit(X_train, y_train)\n # 使用测试集进行训练\n y_predicted = knn.predict(X_test)\n # 计算正确率\n accuracy = np.mean(y_test == y_predicted) * 100\n # 打印\n print('使用划分数据集进行训练的正确率为:{0: .1f}%'.format(accuracy))\n\n\ndef test_autonorm(return_mat, class_label_vector):\n X_train, X_test, y_train, y_test = train_test_split(return_mat, class_label_vector)\n # 创建一个knn分类\n knn = KNeighborsClassifier(n_neighbors=3, algorithm='auto')\n # 归一化处理\n min_max_scaler = preprocessing.MinMaxScaler()\n\n X_train_minmax = min_max_scaler.fit_transform(X_train)\n print(min)\n X_test_minmax = min_max_scaler.transform(X_test)\n\n knn.fit(X_train_minmax, y_train)\n\n y_predicted = knn.predict(X_test_minmax)\n # 计算正确率\n accuracy = np.mean(y_test == y_predicted) * 100\n # 打印\n print('使用划分数据集进行训练的正确率为:{0: .1f}%'.format(accuracy))\n return knn, min_max_scaler\n\n# def val_score(return_mat, class_label_vector):\n# \"\"\"\n# 使用sklearn中的交叉验证计算正确率\n# :param dataSet:\n# :param labels:\n# :return:\n# \"\"\"\n# knn = KNeighborsClassifier()\n# scores = cross_val_score(knn, return_mat, class_label_vector, scoring='accuracy')\n# average_accuracy = np.mean(scores) * 100\n# print('使用交叉验证得到的准确率为:{0: .1f}%'.format(average_accuracy))\n\n\ndef classify_person():\n # 输出结果\n result_list = ['讨厌','有些喜欢','非常喜欢']\n #三维特征用户输入\n precentTats = float(input(\"玩视频游戏所耗时间百分比:\"))\n ffMiles = float(input(\"每年获得的飞行常客里程数:\"))\n iceCream = float(input(\"每周消费的冰激淋公升数:\"))\n filename = 'knn/datingTestSet.txt'\n\n return_mat, class_label_vector = filematrix(filename)\n in_arr = np.array([ffMiles, precentTats, iceCream])\n knn, min_max_scaler = test_autonorm(return_mat, class_label_vector)\n test_data = min_max_scaler.transform(in_arr.reshape(1, -1))\n predicted_data = knn.predict(test_data)\n print(result_list[predicted_data])\n\nif __name__ == \"__main__\":\n classify_person()","sub_path":"knn/helan 约会/sk_helan.py","file_name":"sk_helan.py","file_ext":"py","file_size_in_byte":3767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"463772298","text":"# Este código toma datos de un archivo del Millenium para H_beta\n# y dibuja, para un redshift z dado, la función de luminosidad sin atenuar,\n# la atenuada por Millenium, la atenuada por Calzetti y la de por Cardelli\n# Pablo Fernández, 14/05/2021\n\nimport read_jc_obs as jc\n\nfrom Att_Calzetti import att_Cal_1, att_Cal_2\nfrom Att_Cardelli import att_Car_1, att_Car_2\n\nfrom matplotlib import pyplot as plt # para usar legend\nfrom pylab import plot, errorbar, xlabel, ylabel, title, xlim, ylim\nfrom numpy import zeros, size, histogram, log10, append, arange, loadtxt\n\n###############################################################################\n\nunitsh = True # True: todo con unidades de h\nhu = 0.6777 # parámetro Hubble\n\n###############################################################################\n\n# Toma un redshift y el archivo correspondiente\nredshift = 0.69\nfile = 'LHb_45_200.txt'\nwaveA = 4861 # Longitud de onda de H_beta en Angstroms\n\n###############################################################################\n\n# PARÁMETROS DEL PLOT DEL HISTOGRAMA\nlbox = 200 # lado de la caja en Mpc/h\nvol = lbox**3 # volumen en Mpc^3/h^3\n\nif not unitsh: # volumen sin h\n vol = (lbox/hu)**3\n \nlmin = 39.\nlmax = 43.\ndl = 0.1\nlbins = arange(lmin,lmax,dl)\nlhist = lbins\nvbins = append(lbins,lmax) \n \ntypes = ['sin atenuar','Millenium', 'Calzetti', 'Cardelli']\ncolors = ['blue','green','red','cyan']\n\n \n# DATOS EXPERIMENTALES DE H_beta\n\nobs_path = '/Users/pablofernandez/Documents/5º curso/TFG2/Datos/Comparat_2016/'\n\nox, oy, el, eh = jc.read_jc_lf(obs_path,redshift,\n infile='H1_4862-data-summary-Planck15.txt',h2unitL=True)\n\nif not unitsh: # ahora, sin h^-2 ni h^-3\n ox, oy, el, eh = jc.read_jc_lf(obs_path,redshift,\n infile='H1_4862-data-summary-Planck15.txt',h2unitL=False)\n\nMerror = zeros((2,size(el))) # guarda las barras de error\nMerror[0,:]=el\nMerror[1,:]=eh\n\n# DATOS MILLENIUM: extracción de luminosidades y parámetros de las galaxias\n\ndata = loadtxt(file, float, delimiter=',')\n\nif unitsh:\n L_Hb_noext = log10(data[:, 0])+40 # para que esté en log10(L[erg/s h^-2])\n L_Hb_ext = log10(data[:, 1])+40\nelse: # sin la h\n L_Hb_noext = log10(data[:, 0])+40 -2*log10(hu)\n L_Hb_ext = log10(data[:, 1])+40 -2*log10(hu)\n\nMcold_disc = data[:, 2]\nmetals_coldgas = data[:, 3]\nrdisk = data[:, 4]\n\nZ_disc = metals_coldgas/Mcold_disc\nif unitsh:\n Mcold_disc = Mcold_disc*1e10 # (en masas solares/h)\n rhalf_mass_disc = rdisk # (en Mpc/h)\nelse: # sin la h\n Mcold_disc = Mcold_disc*1e10/hu\n rhalf_mass_disc = rdisk/hu\n\n# PLOT HISTOGRAMA\n\n# v_datos es una matriz que guardará todos los tipos de luminosidades\nv_datos = zeros((size(types),size(L_Hb_noext)))\n\nv_datos[0,:] = L_Hb_noext # sin atenuar\nv_datos[1,:] = L_Hb_ext # atenuado por Millenium\n \n \nfor j in range(size(L_Hb_noext)):\n \n attenuation_disc_Cal = att_Cal_1(waveA, Mcold_disc[j], rhalf_mass_disc[j], Z_disc[j])\n attenuation_disc_Car = att_Car_1(waveA, Mcold_disc[j], rhalf_mass_disc[j], Z_disc[j])\n \n # atenuación en el continuo\n v_datos[2,j] = att_Cal_2(v_datos[0,j], attenuation_disc_Cal, 1)\n v_datos[3,j] = att_Car_2(v_datos[0,j], attenuation_disc_Car, 1)\n \nfor i in range(size(types)):\n H, bins_edges = histogram(v_datos[i],bins=vbins)\n y = log10(H/(vol*dl))\n \n plot(lhist,y,color=colors[i],label=types[i]) \n \nleg = plt.legend(loc=0)\n\n# PLOT DATOS EXPERIMENTALES\n\nerrorbar(ox, oy, Merror, fmt='o', color='grey', capsize=2)\n\ntitle('z = %.2f' %redshift) \n\nif unitsh:\n xlabel(\"log$_{10}$(LH$\\u03B2$[erg s$^{-1}$ h$^{-2}$]])\",size=15)\n ylabel(\"log$_{10}$($\\Phi$[Mpc$^{-3}$ dex$^{-1}$ h$^{-3}$])\",size=15)\nelse:\n xlabel(\"log$_{10}$(LH$\\u03B2$[erg s$^{-1}$]])\",size=15)\n ylabel(\"log$_{10}$($\\Phi$[Mpc$^{-3}$ dex$^{-1}$])\",size=15)\n \nxlim(40.5,43)\nylim(-6,-1.5)\n\nplt.savefig('Hb_45_200.pdf')","sub_path":"Atenuación_Hb.py","file_name":"Atenuación_Hb.py","file_ext":"py","file_size_in_byte":3956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"370036351","text":"from rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom api import models\nfrom api import service\nfrom django.http import JsonResponse\nimport hashlib,json\nimport time\nfrom django.conf import settings\nfrom .utils.decrypt import decrypt\n\n\ndef gen_key(ctime):\n key = \"{}|{}\".format(settings.API_KEY, ctime)\n md5 = hashlib.md5()\n md5.update(key.encode('utf-8'))\n return md5.hexdigest()\n\n\nSING_RECORD = {}\n\nclass AuthView(APIView):\n def dispatch(self, request, *args, **kwargs):\n ret = {'status': True, 'msg': '66666'}\n key = request.GET.get('key')\n ctime = request.GET.get('ctime')\n now = time.time()\n\n sign = gen_key(ctime)\n\n # 时间的判断\n if now - float(ctime) > 3:\n ret['status'] = False\n ret['msg'] = '认证超时'\n return JsonResponse(ret)\n\n if sign in SING_RECORD:\n ret['status'] = False\n ret['msg'] = '认证已使用'\n return JsonResponse(ret)\n\n if key != sign:\n ret['status'] = False\n ret['msg'] = '验证不通过'\n return JsonResponse(ret)\n SING_RECORD[sign] = None\n\n if ret['status']:\n return super().dispatch(request,*args,**kwargs)\n else:\n return JsonResponse(ret)\n\n\n\nclass Asset(AuthView):\n def get(self, request):\n host_list = ['host1', 'host2']\n\n return Response(host_list) # 自动进行序列化\n\n def post(self, request):\n\n info = json.loads(decrypt(request.body).decode('utf-8'))\n action_type = info.get('type')\n print(info)\n ret = {'status': True, 'error': None, 'hostname': None}\n\n if action_type == 'create':\n\n # 新增主机信息\n\n server_dict = {}\n server_dict.update(info['basic']['data'])\n server_dict.update(info['cpu']['data'])\n server_dict.update(info['board']['data'])\n\n # 将字典装换为关键字参数的形式: name=value, 存入到数据库中,返回此条记录对象\n server = models.Server.objects.create(**server_dict)\n\n # 新增磁盘信息\n\n disk_info = info['disk']['data']\n disk_list = []\n for i in disk_info.values():\n i['server'] = server\n disk_list.append(models.Disk(**i))\n\n models.Disk.objects.bulk_create(disk_list)\n\n # 新增内存信息\n\n memory_info = info['memory']['data']\n memory_list = []\n for i in memory_info.values():\n i['server'] = server\n memory_list.append(models.Memory(**i))\n\n models.Memory.objects.bulk_create(memory_list)\n\n # 新增网卡信息\n nic_info = info['nic']['data']\n nic_list = []\n for name, i in nic_info.items():\n i['server'] = server\n i['name'] = name\n nic_list.append(models.NIC(**i))\n\n models.NIC.objects.bulk_create(nic_list)\n\n ## ****************************** 更新资产信息 ****************************\n elif action_type == 'update':\n # 更新资产信息\n\n # 查找要修改的主机\n hostname = info['basic']['data']['hostname']\n server_list = models.Server.objects.filter(hostname=hostname)\n server = server_list.first()\n\n service.process_basic(info, server_list)\n service.process_disk(info, server)\n service.process_memory(info, server)\n service.process_nic(info, server)\n\n\n\n ## ****************************** 更新主机和资产信息 ****************************\n\n elif action_type == 'host_change':\n # 更新资产信息和主机名\n print('更新资产信息和主机名')\n\n #### 更新主机名\n cert = info.get('cert')\n server_list = models.Server.objects.filter(hostname=cert)\n server = server_list.first()\n server.hostname = info['basic']['data']['hostname']\n server.save()\n service.process_basic(info, server_list)\n service.process_disk(info, server)\n service.process_memory(info, server)\n service.process_nic(info, server)\n\n ret['hostname'] = info['basic']['data']['hostname']\n return Response(ret)\n\n","sub_path":"cmdb_api/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"574439421","text":"from wallet.domain import Tag, User\nfrom wallet.domain.storage import EntityAlreadyExist, Storage\n\n\nclass TagsService:\n __slots__ = (\"_storage\",)\n\n def __init__(self, storage: Storage) -> None:\n self._storage = storage\n\n async def add(self, name: str, user: User) -> Tag:\n tag = Tag(key=0, name=name, user=user)\n\n async with self._storage as store:\n existed = await store.tags.find_by_name(user, name)\n\n if existed:\n raise EntityAlreadyExist()\n\n tag.key = await store.tags.add(tag)\n await store.commit()\n\n return tag\n","sub_path":"src/wallet/services/tags.py","file_name":"tags.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"150264864","text":"import tensorflow as tf\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.regularizers import l2,l1\nfrom tensorflow.keras.layers import Conv2D, UpSampling2D,BatchNormalization,GaussianNoise\nfrom tensorflow.keras.layers import MaxPooling2D, Dropout, Activation, Concatenate\nfrom tensorflow.keras.layers import Add, Multiply, Input, Conv2DTranspose,LeakyReLU, ReLU\n\n\n\nclass ConvLayer():\n def __init__(self,\n kernel_size,\n padding,\n initializer):\n\n self.kernel_size=kernel_size\n self.padding=padding\n self.initializer=initializer\n\n\n def __call__(self, f, dilation=1):\n return Conv2D(\n filters=f, \n kernel_size=self.kernel_size,\n padding=self.padding, \n kernel_initializer=self.initializer,\n dilation_rate=dilation\n )\n\n\nclass UpLayer():\n def __init__(self,\n kernel_size,\n padding,\n initializer,\n activation,\n layer_type):\n \n self.kernel_size=kernel_size\n self.padding=padding\n self.initializer=initializer\n self.activation=activation\n self.layer_type=layer_type\n\n\n def __call__(self, f=None, pool=(2,2)):\n if self.layer_type=='upsampling':\n layer=UpSampling2D(pool)\n elif self.layer_type=='transpose':\n layer=Conv2DTranspose(\n f,\n kernel_size=self.kernel_size,\n activation=self.activation, \n strides=(2,2), \n padding=self.padding\n )\n return layer\n\n\nclass IdentityLayer():\n def __init__(self, padding, strides):\n self.kernel_size=(1,1)\n self.padding=padding\n self.strides=strides\n \n\n def __call__(self, x , f):\n \n identity = Conv2D(f, \n kernel_size=self.kernel_size,\n padding=self.padding, \n strides=self.strides)(x)\n identity = BatchNormalization()(identity)\n x = Add()([identity, x])\n return x\n\n\ndef conv_block(x,\n f,\n conv_layer,\n normalize=True, \n drop=False):\n\n x = conv_layer(f)(x) \n x = BatchNormalization()(x) if normalize else x\n #x = GaussianNoise(0.3)(x)\n x = ReLU()(x)\n #x = LeakyReLU(0.1)(x)\n #x = Dropout(0.2)(x) if contraction else x\n x = conv_layer(f)(x)\n x = BatchNormalization()(x) if normalize else x\n #x = GaussianNoise(0.3)(x)\n #x = LeakyReLU(0.1)(x)\n x = ReLU()(x)\n #x = LeakyReLU(0.1)(x)\n #x = Dropout(0.2)(x) if contraction else x \n return x\n\n\n\ndef residual_block(x1,\n f,\n conv_layer,\n identity_layer,\n strides=(1,1),\n normalize=True,\n drop=False):\n\n x2 = conv_layer(f)(x) \n x2 = BatchNormalization()(x) if normalize else x\n x2 = ReLU()(x)\n #x = Dropout(0.2)(x) if drop else x\n x2 = conv_layer(f)(x)\n x2 = BatchNormalization()(x) if normalize else x\n x2 = ReLU()(x)\n #x = Dropout(0.2)(x) if drop else x \n x2 = identity_layer(r, x, f, strides=stride)\n return x\n\n\ndef multi_block(x,\n f,\n conv_layer,\n up_layer,\n normalize=True\n ):\n\n out_f=f/3\n x = MaxPooling2D((2,2))(x)\n\n x1 = conv_layer(out_f, 1)(x)\n x1 = MaxPooling2D((1,1))(x1)\n x1 = BatchNormalization()(x1) if normalize else x1\n x1 = ReLU()(x1)\n x1 = conv_layer(out_f, 1)(x1)\n x1 = BatchNormalization()(x1) if normalize else x1\n x1 = ReLU()(x1)\n\n x2 = conv_layer(out_f, 2)(x1)\n x2 = MaxPooling2D((2,2))(x2)\n x2 = BatchNormalization()(x2) if normalize else x2\n x2 = ReLU()(x2)\n x2 = conv_layer(out_f, 2)(x2)\n x2 = BatchNormalization()(x2) if normalize else x2\n x2 = ReLU()(x2)\n x2 = up_layer(pool=(2,2))(x2)\n\n x3 = conv_layer(out_f, 4)(x2)\n x3 = MaxPooling2D((4,4))(x3)\n x3 = BatchNormalization()(x3) if normalize else x3\n x3 = ReLU()(x3)\n x3 = conv_layer(out_f, 4)(x3)\n x3 = BatchNormalization()(x3) if normalize else x3\n x3 = ReLU()(x3) \n x3 = up_layer(pool=(4,4))(x3)\n\n x = Concatenate()([x1,x2,x3])\n\n return x\n\n\n\n\n\n\n","sub_path":"src/models/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":4432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"139523546","text":"from classes.vec import *\nimport numpy as np \nimport time\nimport matplotlib.pyplot as plt\nimport math\nimport random\n\n# this is an extremely rudimentary path tracer that renders a scene of spheres to a pyplot image. \n\n# material codes:\n# 0: transparent\n# 1: specular\n# 2: diffuse \n# 3: emissive \n\n# ---SCENE DEFINITION---\n\nr = ray(vec(0,1,0),vec(1,0,0))\nscne = [\n sphere(1,vec(5,0,0),2),\n sphere(2,vec(-2.2,0,-5),3),\n sphere(2,vec(1,0,-5),3),\n sphere(2,vec(4,0,-5),3),\n sphere(2,vec(7,0,-5),3),\n sphere(2,vec(10,0,-5),3)\n]\n\n\n# ---MAIN ROUTINE---\n\ntime0 = time.time()\n\n# image dimensions\nwidth = 32\nheight = width\n# the \"zoom\" factor\nview = 0.25\n# samples per pixel\nspp = 256\n# max ray bounces \nr_bnc = 5\n# background value\nb_val = 0.2\n# global brightness of lights (this is the only spot where the field can be adjusted)\nlight_pwr = 1.5\n# output matrix\nout = np.reshape(np.zeros(width*height),(width,height))\nwd = np.linspace(-view,view,width)\nht = np.linspace(-view,view,height)\n\nfor w in range(width):\n print('rendering line',w,'of',width)\n \n for h in range(height):\n brt = 0\n print('.', end='')\n for i in range(spp):\n er = ray(vec(0,0,0),vec(1, (wd[w] + np.random.randn()*0.002), (ht[h] + np.random.randn()*0.002)))\n if intersect(er,scne)[0] > 0:\n brt += raytree(er,scne,r_bnc,b_val,light_pwr)\n else:\n brt += raytree(er,scne,r_bnc,b_val,light_pwr)*spp\n break\n out[height - h - 1][w] = brt/spp\n print('',end='\\n')\n\nprint('render time:',round(time.time()-time0,3),'sec')\n\nplt.imshow(out,vmin=0,vmax=1,cmap = 'gray')\nplt.show()","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"459882691","text":"import pymongo\nfrom config import MONGO_PORT, DB_NAME, COLLECTION, SYMBOL_LIST_FILE\n\nfrom collections import defaultdict\n\nclass MongoQuery:\n def __init__(self):\n conn = pymongo.Connection('127.0.0.1', MONGO_PORT)\n database = conn[DB_NAME]\n self.db = database[COLLECTION]\n \n def stock_totals(self, stocks):\n final = defaultdict(lambda: 0)\n for stock in stocks:\n if stock.quantity > 0:\n data = self.db.find({\n 'stock_symbol': stock.name,\n 'date': {'$gte': str(stock.date_obtained)}\n })\n for row in data:\n price = float(row['stock_price_close'])\n final[row['date']] += price * stock.quantity\n return final\n\ndef read_stock_symbols():\n with open(SYMBOL_LIST_FILE) as stock_file:\n return stock_file.read().split()\n","sub_path":"model/mongo_query.py","file_name":"mongo_query.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"92300594","text":"from flask import *\nimport paypalrestsdk as paypal\nfrom paypalrestsdk import *\nfrom flask_sqlalchemy import *\nfrom os import environ\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = environ.get('dbURL')\n# app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://root@localhost:3306/bidding'\napp.config['SQLALCHEMY_DATABASE_URI'] = environ.get('dbURL')\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n \ndb = SQLAlchemy(app)\n\n\n# Currently using bidID retrieved from database.\n# Need to change to bidID retrieved from other microservices later.\n\n\n\n# class ListBid(db.Model):\n# __tablename__ = 'bidItem'\n# bidID = db.Column(db.String(10), primary_key=True)\n# productID = db.Column(db.String(100), nullable=False)\n# sellerID = db.Column(db.String(10), nullable=False)\n# bidDateTime = db.Column(db.String(20), nullable=False)\n# buyerID = db.Column(db.String(10), nullable=False)\n# bidAmt = db.Column(db.Float(), nullable=False)\n# bidStatus = db.Column(db.String(20), nullable=False)\n# meetup = db.Column(db.String(100), nullable=False)\n\n \n# def __init__(self, bidID, productID, sellerID, buyerID, bidDateTime, bidAmt, bidStatus, meetup):\n# self.bidID = bidID\n# self.productID = productID\n# self.sellerID = sellerID\n# self.bidDateTime = bidDateTime\n# self.buyerID = buyerID\n# self.bidAmt = bidAmt\n# self.bidStatus = bidStatus\n# self.meetup = meetup\n\n# def json(self):\n# return {\"bidID\": self.bidID, \"productID\": self.productID, \"sellerID\": self.sellerID, \"bidDateTime\": self.bidDateTime, \"buyerID\": self.buyerID, \"bidAmt\": self.bidAmt, \"bidStatus\": self.bidStatus, \"meetup\": self.bidStatus }\n\n\n\n\npaypal.configure({\n \"mode\": \"sandbox\", # sandbox or live\n \"client_id\": \"ASWAtFfl_iT5f6x7dTBwChLqyHE8OA-aqbKEUJ1uXlZC5bFSNEL1XcdwBJqQ9oV9grKW-7j1jod3X68I\",\n \"client_secret\": \"EFPgiR2Ku0gSyOgjc7hkkxfTAc2R4mPFWKUPy_RxFgxWR-h6ko6uZLjtFNgVd_ZLAHP8dHy6TkmGE92B\"})\n\n\n\n@app.route('/')\ndef index():\n #link to a homepage where user can make transaction \n return render_template(\"payment.html\", **locals())\n\n\n\n@app.route('/paypal_payment', methods=['GET', 'POST'])\ndef paypal_payment():\n if request.method == 'POST':\n content = request.json\n productName = content['productName']\n bidID = content['bidID']\n bidAmt = content['bidAmt']\n \n # code to execute payment through paypal website\n payment = paypal.Payment({\n \"intent\": \"sale\",\n \"payer\": {\n \"payment_method\": \"paypal\"},\n\n # Redirect URLs\n \"redirect_urls\": {\n \"return_url\": \"http://0.0.0.0:5005/paypal_Return?success=true\",\n \"cancel_url\": \"http://0.0.0.0:5005/paypal_Return?cancel=true\"},\n\n \"transactions\": [{\n\n # ItemList\n \"item_list\": {\n \"items\": [{\n \"name\": productName,\n \"sku\": bidID,\n \"price\": str(bidAmt),\n \"currency\": \"USD\",\n \"quantity\": 1}]},\n \"amount\": {\n \"total\": str(bidAmt * 1),\n \"currency\": \"USD\"},\n \"description\": \"test 123 This is the payment transaction description.\"}]})\n\n # Create a transaction and return Payment status\n if payment.create():\n print(\"Payment[%s] created successfully\" % (payment.id))\n # Redirect the user to approval url\n for link in payment.links:\n if link.method == \"REDIRECT\":\n # Convert to str to avoid google appengine unicode issue\n # https://github.com/paypal/rest-api-sdk-python/pull/58\n redirect_url = str(link.href)\n print(\"Redirect for approval: %s\" % (redirect_url))\n return jsonify({\"redirect_url\": redirect_url, \"paymentID\": payment.id })\n\n else:\n print(\"Error while generating transaction:\")\n print(payment.error)\n return \"Error while generating transaction\"\n\n@app.route('/paypal_Return', methods=['GET'])\ndef paypal_Return():\n\n paymentId = request.args['paymentId']\n payer_id = request.args['PayerID']\n payment = paypal.Payment.find(paymentId)\n\n # PayerID is required to approve the payment.\n if payment.execute({\"payer_id\": payer_id}):\n print(\"Payment[%s] execute successfully\" % (payment.id))\n return 'Payment execute successfully!' + \" Your Payment ID is: \" + payment.id\n else:\n print(payment.error)\n return 'Having trouble executing payment! Please try again later.'\n\nif __name__ == '__main__':\n app.run(host = '0.0.0.0', port=5005, debug=True)\n","sub_path":"docker/transaction_microservice/transaction.py","file_name":"transaction.py","file_ext":"py","file_size_in_byte":4668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"577942923","text":"# Copyright 2019-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\nfrom typing import Any, Optional, Sequence\n\nfrom braket.circuits.quantum_operator import QuantumOperator\nfrom braket.circuits.qubit_set import QubitSet\n\n\nclass Noise(QuantumOperator):\n \"\"\"\n Class `Noise` represents a noise channel that operates on one or multiple qubits. Noise\n are considered as building blocks of quantum circuits that simulate noise. It can be\n used as an operator in an `Instruction` object. It appears in the diagram when user prints\n a circuit with `Noise`. This class is considered the noise channel definition containing\n the metadata that defines what the noise channel is and what it does.\n \"\"\"\n\n def __init__(self, qubit_count: Optional[int], ascii_symbols: Sequence[str]):\n \"\"\"\n Args:\n qubit_count (int, optional): Number of qubits this noise channel interacts with.\n ascii_symbols (Sequence[str]): ASCII string symbols for this noise channel. These\n are used when printing a diagram of circuits. Length must be the same as\n `qubit_count`, and index ordering is expected to correlate with target ordering\n on the instruction.\n\n Raises:\n ValueError: `qubit_count` is less than 1, `ascii_symbols` are None, or\n length of `ascii_symbols` is not equal to `qubit_count`\n \"\"\"\n super().__init__(qubit_count=qubit_count, ascii_symbols=ascii_symbols)\n\n @property\n def name(self) -> str:\n \"\"\"\n Returns the name of the quantum operator\n\n Returns:\n The name of the quantum operator as a string\n \"\"\"\n return self.__class__.__name__\n\n def to_ir(self, target: QubitSet) -> Any:\n \"\"\"Returns IR object of quantum operator and target\n\n Args:\n target (QubitSet): target qubit(s)\n Returns:\n IR object of the quantum operator and target\n \"\"\"\n raise NotImplementedError(\"to_ir has not been implemented yet.\")\n\n def to_matrix(self, *args, **kwargs) -> Any:\n \"\"\"Returns a list of matrices defining the Kraus matrices of the noise channel.\n\n Returns:\n Iterable[np.ndarray]: list of matrices defining the Kraus matrices of the noise channel.\n \"\"\"\n raise NotImplementedError(\"to_matrix has not been implemented yet.\")\n\n def __eq__(self, other):\n if isinstance(other, Noise):\n return self.name == other.name\n return NotImplemented\n\n def __repr__(self):\n return f\"{self.name}('qubit_count': {self.qubit_count})\"\n\n @classmethod\n def register_noise(cls, noise: \"Noise\"):\n \"\"\"Register a noise implementation by adding it into the Noise class.\n\n Args:\n noise (Noise): Noise class to register.\n \"\"\"\n setattr(cls, noise.__name__, noise)\n\n\nclass SingleProbabilisticNoise(Noise):\n \"\"\"\n Class `SingleProbabilisticNoise` represents the bit/phase flip noise channel on N qubits\n parameterized by a single probability.\n \"\"\"\n\n def __init__(\n self, probability: float, qubit_count: Optional[int], ascii_symbols: Sequence[str]\n ):\n \"\"\"\n Args:\n probability (float): The probability that the noise occurs.\n qubit_count (int): The number of qubits to apply noise.\n ascii_symbols (Sequence[str]): ASCII string symbols for the noise. These are used when\n printing a diagram of a circuit. The length must be the same as `qubit_count`, and\n index ordering is expected to correlate with the target ordering on the instruction.\n\n Raises:\n ValueError: If the `qubit_count` is less than 1, `ascii_symbols` are `None`, or\n `ascii_symbols` length != `qubit_count`, `probability` is not `float`,\n `probability` > 1/2, or `probability` < 0\n \"\"\"\n super().__init__(qubit_count=qubit_count, ascii_symbols=ascii_symbols)\n\n if not isinstance(probability, float):\n raise TypeError(\"probability must be float type\")\n if not (probability <= 0.5 and probability >= 0.0):\n raise ValueError(\"probability must be a real number in the interval [0,1/2]\")\n self._probability = probability\n\n @property\n def probability(self) -> float:\n \"\"\"\n Returns:\n probability (float): The probability that parameterizes the noise channel.\n \"\"\"\n return self._probability\n\n def __repr__(self):\n return f\"{self.name}('probability': {self.probability}, 'qubit_count': {self.qubit_count})\"\n\n\nclass SingleProbabilisticNoise_34(Noise):\n \"\"\"\n Class `SingleProbabilisticNoise` represents the Depolarizing and TwoQubitDephasing noise\n channels parameterized by a single probability.\n \"\"\"\n\n def __init__(\n self, probability: float, qubit_count: Optional[int], ascii_symbols: Sequence[str]\n ):\n \"\"\"\n Args:\n probability (float): The probability that the noise occurs.\n qubit_count (int): The number of qubits to apply noise.\n ascii_symbols (Sequence[str]): ASCII string symbols for the noise. These are used when\n printing a diagram of a circuit. The length must be the same as `qubit_count`, and\n index ordering is expected to correlate with the target ordering on the instruction.\n\n Raises:\n ValueError: If the `qubit_count` is less than 1, `ascii_symbols` are `None`, or\n `ascii_symbols` length != `qubit_count`, `probability` is not `float`,\n `probability` > 3/4, or `probability` < 0\n \"\"\"\n super().__init__(qubit_count=qubit_count, ascii_symbols=ascii_symbols)\n\n if not isinstance(probability, float):\n raise TypeError(\"probability must be float type\")\n if not (probability <= 0.75 and probability >= 0.0):\n raise ValueError(\"probability must be a real number in the interval [0,3/4]\")\n self._probability = probability\n\n @property\n def probability(self) -> float:\n \"\"\"\n Returns:\n probability (float): The probability that parameterizes the noise channel.\n \"\"\"\n return self._probability\n\n def __repr__(self):\n return f\"{self.name}('probability': {self.probability}, 'qubit_count': {self.qubit_count})\"\n\n\nclass SingleProbabilisticNoise_1516(Noise):\n \"\"\"\n Class `SingleProbabilisticNoise` represents the TwoQubitDepolarizing noise channel\n parameterized by a single probability.\n \"\"\"\n\n def __init__(\n self, probability: float, qubit_count: Optional[int], ascii_symbols: Sequence[str]\n ):\n \"\"\"\n Args:\n probability (float): The probability that the noise occurs.\n qubit_count (int): The number of qubits to apply noise.\n ascii_symbols (Sequence[str]): ASCII string symbols for the noise. These are used when\n printing a diagram of a circuit. The length must be the same as `qubit_count`, and\n index ordering is expected to correlate with the target ordering on the instruction.\n\n Raises:\n ValueError: If the `qubit_count` is less than 1, `ascii_symbols` are `None`, or\n `ascii_symbols` length != `qubit_count`, `probability` is not `float`,\n `probability` > 15/16, or `probability` < 0\n \"\"\"\n super().__init__(qubit_count=qubit_count, ascii_symbols=ascii_symbols)\n\n if not isinstance(probability, float):\n raise TypeError(\"probability must be float type\")\n if not (probability <= 0.9375 and probability >= 0.0):\n raise ValueError(\"probability must be a real number in the interval [0,15/16]\")\n self._probability = probability\n\n @property\n def probability(self) -> float:\n \"\"\"\n Returns:\n probability (float): The probability that parameterizes the noise channel.\n \"\"\"\n return self._probability\n\n def __repr__(self):\n return f\"{self.name}('probability': {self.probability}, 'qubit_count': {self.qubit_count})\"\n\n\nclass PauliNoise(Noise):\n \"\"\"\n Class `PauliNoise` represents the general Pauli noise channel on N qubits\n parameterized by three probabilities.\n \"\"\"\n\n def __init__(\n self,\n probX: float,\n probY: float,\n probZ: float,\n qubit_count: Optional[int],\n ascii_symbols: Sequence[str],\n ):\n \"\"\"\n Args:\n probX [float], probY [float], probZ [float]: The coefficients of the Kraus operators\n in the channel.\n qubit_count (int): The number of qubits to apply noise.\n ascii_symbols (Sequence[str]): ASCII string symbols for the noise. These are used when\n printing a diagram of a circuit. The length must be the same as `qubit_count`, and\n index ordering is expected to correlate with the target ordering on the instruction.\n\n Raises:\n ValueError: If the `qubit_count` is less than 1, `ascii_symbols` are `None`, or\n `ascii_symbols` length != `qubit_count`, `probX` or `probY` or `probZ`\n is not `float`, `probX` or `probY` or `probZ` > 1.0, or\n `probX` or `probY` or `probZ` < 0.0, or `probX`+`probY`+`probZ` > 1\n \"\"\"\n super().__init__(qubit_count=qubit_count, ascii_symbols=ascii_symbols)\n\n if not isinstance(probX, float):\n raise TypeError(\"probX must be float type\")\n if not (probX <= 1.0 and probX >= 0.0):\n raise ValueError(\"probX must be a real number in the interval [0,1]\")\n if not isinstance(probY, float):\n raise TypeError(\"probY must be float type\")\n if not (probY <= 1.0 and probY >= 0.0):\n raise ValueError(\"probY must be a real number in the interval [0,1]\")\n if not isinstance(probZ, float):\n raise TypeError(\"probZ must be float type\")\n if not (probZ <= 1.0 and probZ >= 0.0):\n raise ValueError(\"probZ must be a real number in the interval [0,1]\")\n if probX + probY + probZ > 1:\n raise ValueError(\"the sum of probX, probY, probZ cannot be larger than 1\")\n\n self._probX = probX\n self._probY = probY\n self._probZ = probZ\n\n @property\n def probX(self) -> float:\n \"\"\"\n Returns:\n probX (float): The probability of a Pauli X error.\n \"\"\"\n return self._probX\n\n @property\n def probY(self) -> float:\n \"\"\"\n Returns:\n probY (float): The probability of a Pauli Y error.\n \"\"\"\n return self._probY\n\n @property\n def probZ(self) -> float:\n \"\"\"\n Returns:\n probZ (float): The probability of a Pauli Z error.\n \"\"\"\n return self._probZ\n\n def __repr__(self):\n return f\"{self.name}('probX': {self.probX}, 'probY': {self.probY}, \\\n'probZ': {self.probZ}, 'qubit_count': {self.qubit_count})\"\n\n\nclass DampingNoise(Noise):\n \"\"\"\n Class `DampingNoise` represents a damping noise channel\n on N qubits parameterized by gamma.\n \"\"\"\n\n def __init__(self, gamma: float, qubit_count: Optional[int], ascii_symbols: Sequence[str]):\n \"\"\"\n Args:\n gamma (float): Probability of damping.\n qubit_count (int): The number of qubits to apply noise.\n ascii_symbols (Sequence[str]): ASCII string symbols for the noise. These are used when\n printing a diagram of a circuit. The length must be the same as `qubit_count`, and\n index ordering is expected to correlate with the target ordering on the instruction.\n\n Raises:\n ValueError: If the `qubit_count` is less than 1, `ascii_symbols` are `None`, or\n `ascii_symbols` length != `qubit_count`, `gamma` is not `float`,\n `gamma` > 1.0, or `gamma` < 0.0.\n \"\"\"\n super().__init__(qubit_count=qubit_count, ascii_symbols=ascii_symbols)\n\n if not isinstance(gamma, float):\n raise TypeError(\"gamma must be float type\")\n if not (gamma <= 1.0 and gamma >= 0.0):\n raise ValueError(\"gamma must be a real number in the interval [0,1]\")\n self._gamma = gamma\n\n @property\n def gamma(self) -> float:\n \"\"\"\n Returns:\n gamma (float): Probability of damping.\n \"\"\"\n return self._gamma\n\n def __repr__(self):\n return f\"{self.name}('gamma': {self.gamma}, 'qubit_count': {self.qubit_count})\"\n\n\nclass GeneralizedAmplitudeDampingNoise(DampingNoise):\n \"\"\"\n Class `GeneralizedAmplitudeDampingNoise` represents the generalized amplitude damping\n noise channel on N qubits parameterized by gamma and probability.\n \"\"\"\n\n def __init__(\n self,\n gamma: float,\n probability: float,\n qubit_count: Optional[int],\n ascii_symbols: Sequence[str],\n ):\n \"\"\"\n Args:\n gamma (float): Probability of damping.\n probability (float): Probability of the system being excited by the environment.\n qubit_count (int): The number of qubits to apply noise.\n ascii_symbols (Sequence[str]): ASCII string symbols for the noise. These are used when\n printing a diagram of a circuit. The length must be the same as `qubit_count`, and\n index ordering is expected to correlate with the target ordering on the instruction.\n\n Raises:\n ValueError: If the `qubit_count` is less than 1, `ascii_symbols` are `None`, or\n `ascii_symbols` length != `qubit_count`, `probability` or `gamma` is not `float`,\n `probability` > 1.0, or `probability` < 0.0, `gamma` > 1.0, or `gamma` < 0.0.\n \"\"\"\n super().__init__(gamma=gamma, qubit_count=qubit_count, ascii_symbols=ascii_symbols)\n\n if not isinstance(probability, float):\n raise TypeError(\"probability must be float type\")\n if not (probability <= 1.0 and probability >= 0.0):\n raise ValueError(\"probability must be a real number in the interval [0,1]\")\n self._probability = probability\n\n @property\n def probability(self) -> float:\n \"\"\"\n Returns:\n probability (float): Probability of the system being excited by the environment.\n \"\"\"\n return self._probability\n\n def __repr__(self):\n return f\"{self.name}('gamma': {self.gamma}, 'probability': {self.probability}, \\\n'qubit_count': {self.qubit_count})\"\n","sub_path":"artifacts/minimal_bugfixes/amazon-braket-sdk-python/amazon-braket-sdk-python#250/after/noise.py","file_name":"noise.py","file_ext":"py","file_size_in_byte":15139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"26835566","text":"import sys\n\nss = lambda f: lambda *args: str(f(*args), encoding='ascii')\ndef init():\n global devices, getGPUName, pynvml\n sys.path.append('site-packages/nvidia-ml-py')\n import pynvml # pylint: disable=E0401\n sys.path.pop()\n pynvml.nvmlInit()\n devices = [pynvml.nvmlDeviceGetHandleByIndex(i) for i in range(pynvml.nvmlDeviceGetCount())]\n getGPUName = ss(pynvml.nvmlDeviceGetName)\n\ngetFreeMem = lambda device: pynvml.nvmlDeviceGetMemoryInfo(device).free # pylint: disable=E0602\ngetGPU = lambda: tuple(map(getFreeMem, devices))\ngetName = lambda: tuple(map(getGPUName, devices))\n\nif __name__ == '__main__':\n init()\n print(getName(), getGPU())","sub_path":"python/readgpu.py","file_name":"readgpu.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"487748608","text":"# -*- coding: utf-8 -*-\n# BSD 3-Clause License\n#\n# Copyright (c) 2017\n# All rights reserved.\n# Copyright 2022 Huawei Technologies Co., Ltd\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n# ==========================================================================\n\n# Copyright (c) OpenMMLab. All rights reserved.\nimport warnings\n\nimport mmcv\nfrom mmdet.core import bbox2roi\nfrom torch import nn\nfrom torch.nn import functional as F\n\nfrom mmocr.core import imshow_edge, imshow_node\nfrom mmocr.models.builder import DETECTORS, build_roi_extractor\nfrom mmocr.models.common.detectors import SingleStageDetector\nfrom mmocr.utils import list_from_file\n\n\n@DETECTORS.register_module()\nclass SDMGR(SingleStageDetector):\n \"\"\"The implementation of the paper: Spatial Dual-Modality Graph Reasoning\n for Key Information Extraction. https://arxiv.org/abs/2103.14470.\n\n Args:\n visual_modality (bool): Whether use the visual modality.\n class_list (None | str): Mapping file of class index to\n class name. If None, class index will be shown in\n `show_results`, else class name.\n \"\"\"\n\n def __init__(self,\n backbone,\n neck=None,\n bbox_head=None,\n extractor=dict(\n type='mmdet.SingleRoIExtractor',\n roi_layer=dict(type='RoIAlign', output_size=7),\n featmap_strides=[1]),\n visual_modality=False,\n train_cfg=None,\n test_cfg=None,\n class_list=None,\n init_cfg=None,\n openset=False):\n super().__init__(\n backbone, neck, bbox_head, train_cfg, test_cfg, init_cfg=init_cfg)\n self.visual_modality = visual_modality\n if visual_modality:\n self.extractor = build_roi_extractor({\n **extractor, 'out_channels':\n self.backbone.base_channels\n })\n self.maxpool = nn.MaxPool2d(extractor['roi_layer']['output_size'])\n else:\n self.extractor = None\n self.class_list = class_list\n self.openset = openset\n\n def forward_train(self, img, img_metas, relations, texts, gt_bboxes,\n gt_labels):\n \"\"\"\n Args:\n img (tensor): Input images of shape (N, C, H, W).\n Typically these should be mean centered and std scaled.\n img_metas (list[dict]): A list of image info dict where each dict\n contains: 'img_shape', 'scale_factor', 'flip', and may also\n contain 'filename', 'ori_shape', 'pad_shape', and\n 'img_norm_cfg'. For details of the values of these keys,\n please see :class:`mmdet.datasets.pipelines.Collect`.\n relations (list[tensor]): Relations between bboxes.\n texts (list[tensor]): Texts in bboxes.\n gt_bboxes (list[tensor]): Each item is the truth boxes for each\n image in [tl_x, tl_y, br_x, br_y] format.\n gt_labels (list[tensor]): Class indices corresponding to each box.\n\n Returns:\n dict[str, tensor]: A dictionary of loss components.\n \"\"\"\n x = self.extract_feat(img, gt_bboxes)\n node_preds, edge_preds = self.bbox_head.forward(relations, texts, x)\n return self.bbox_head.loss(node_preds, edge_preds, gt_labels)\n\n def forward_test(self,\n img,\n img_metas,\n relations,\n texts,\n gt_bboxes,\n rescale=False):\n x = self.extract_feat(img, gt_bboxes)\n node_preds, edge_preds = self.bbox_head.forward(relations, texts, x)\n return [\n dict(\n img_metas=img_metas,\n nodes=F.softmax(node_preds, -1),\n edges=F.softmax(edge_preds, -1))\n ]\n\n def extract_feat(self, img, gt_bboxes):\n if self.visual_modality:\n x = super().extract_feat(img)[-1]\n feats = self.maxpool(self.extractor([x], bbox2roi(gt_bboxes)))\n return feats.view(feats.size(0), -1)\n return None\n\n def show_result(self,\n img,\n result,\n boxes,\n win_name='',\n show=False,\n wait_time=0,\n out_file=None,\n **kwargs):\n \"\"\"Draw `result` on `img`.\n\n Args:\n img (str or tensor): The image to be displayed.\n result (dict): The results to draw on `img`.\n boxes (list): Bbox of img.\n win_name (str): The window name.\n wait_time (int): Value of waitKey param.\n Default: 0.\n show (bool): Whether to show the image.\n Default: False.\n out_file (str or None): The output filename.\n Default: None.\n\n Returns:\n img (tensor): Only if not `show` or `out_file`.\n \"\"\"\n img = mmcv.imread(img)\n img = img.copy()\n\n idx_to_cls = {}\n if self.class_list is not None:\n for line in list_from_file(self.class_list):\n class_idx, class_label = line.strip().split()\n idx_to_cls[class_idx] = class_label\n\n # if out_file specified, do not show image in window\n if out_file is not None:\n show = False\n\n if self.openset:\n img = imshow_edge(\n img,\n result,\n boxes,\n show=show,\n win_name=win_name,\n wait_time=wait_time,\n out_file=out_file)\n else:\n img = imshow_node(\n img,\n result,\n boxes,\n idx_to_cls=idx_to_cls,\n show=show,\n win_name=win_name,\n wait_time=wait_time,\n out_file=out_file)\n\n if not (show or out_file):\n warnings.warn('show==False and out_file is not specified, only '\n 'result image will be returned')\n return img\n\n return img\n","sub_path":"PyTorch/built-in/cv/detection/DBpp_ID4145_for_PyTorch/mmocr/models/kie/extractors/sdmgr.py","file_name":"sdmgr.py","file_ext":"py","file_size_in_byte":7661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"307240605","text":"import urllib.request\nimport re\ncount = 0\nwhile True:\n url = input('URL--> ')\n if re.search('https?://.+', url):\n host = url.split('/')[2]\n break\n else:\n print('Invalid URL')\n continue\nfile = urllib.request.urlopen(url).read().decode()\n\n#fhand = open('test.txt', 'wb')\n# fhand.write(file_handle)\n# fhand.close()\nfor word in file:\n # char = char.decode()\n count = count + 1\n if count <= 3000:\n print(word, end='')\nprint('\\nOverall number of characters:', count)\n","sub_path":"ex_12_03.py","file_name":"ex_12_03.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"482624036","text":"import os\n\nimport tensorflow as tf\nfrom tensorflow import keras\n\nimport cv2 as cv\nimport numpy as np\n\nfrom tensor_flow_code.some_models.simple_net_model import simple_model\nfrom tensor_flow_code.some_models.alx_net_model import alexnet_model\n\nfrom ocv.Rectangles import Rectangle\n\n\nmodel = simple_model()\nmodel.compile(optimizer=\"adam\", loss='binary_crossentropy', metrics=['accuracy'])\nprint(model.summary())\n\nmodel.load_weights(\"./yes_no_simple_7.weights\")\n\n\nroi = (44, 130, 35, 43)\ncount_cols = 64\ncount_rows = 40\ncur_col = 0\ncur_row = 0\n\npastes = 0\ncounter = 0\n\nsize = (count_rows * roi[3], count_cols * roi[2], 3)\n\ncanvas = np.zeros(size, dtype=np.uint8)\n\n\nvideo_dir = \"/home/yurych4/Videos/raw_video_from_cam/shevchenko_rum/picked/shew2\"\nlist_videos = os.listdir(video_dir)\n\nfor video_name in list_videos:\n path = os.path.join(video_dir, video_name)\n print(\"Open:\", path)\n\n cap = cv.VideoCapture(path)\n while cap.isOpened():\n ret, frame = cap.read()\n if ret:\n img = frame[roi[1]:roi[1]+roi[3], roi[0]:roi[0]+roi[2]]\n img_for_show = img[:]\n img = cv.cvtColor(img, cv.COLOR_BGR2RGB)\n img = cv.resize(img, (50, 50))\n img = img / 255\n img = img.reshape(1, 50, 50, 3)\n\n result_predict = model.predict(img)\n\n print(result_predict)\n # state = np.argmax(result_predict, axis=1)\n\n if result_predict[0][0] > 0.5:\n cv.rectangle(img_for_show, (10, 10), (45, 45), (255, 0, 0), 1)\n\n if pastes < (count_cols * count_rows):\n pastes += 1\n print(pastes)\n\n if cur_col >= count_cols:\n cur_col = 0\n cur_row += 1\n\n ins_roi = (cur_col * roi[2], cur_row * roi[3], roi[2], roi[3])\n\n canvas[ins_roi[1]:ins_roi[1]+ins_roi[3], ins_roi[0]:ins_roi[0]+ins_roi[2]] = img_for_show\n\n cur_col += 1\n # cv.imshow(\"canv\", canvas)\n # cv.waitKey(0)\n\n else:\n print(\"Save!\")\n counter += 1\n cv.imwrite(\"/home/yurych4/datasets/traffic_lights/video_maps/shew2/simple_6/\" + str(counter) + \".jpg\", canvas)\n\n canvas = np.zeros(size, dtype=np.uint8)\n\n cur_col = 0\n cur_row = 0\n pastes = 0\n\n else:\n break\n\n cap.release()\n\n\n\n\n\n\n\n # img = cv.imread(path, cv.IMREAD_COLOR)\n #\n # img_to_show = img[:]\n # img = cv.cvtColor(img, cv.COLOR_BGR2RGB)\n #\n # img = cv.resize(img, (50, 50))\n # img = img.reshape(1, 50, 50, 3)\n #\n # print(model.predict(img))\n #\n # cv.imshow(\"some\", img_to_show)\n # cv.waitKey(0)\n","sub_path":"tensor_flow_code/yes_no_testing.py","file_name":"yes_no_testing.py","file_ext":"py","file_size_in_byte":2748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"170086855","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/9/29 8:46\n# @Author : Tony\n\"\"\"投资管理的数据库SQL实现\"\"\"\nfrom datetime import datetime\nfrom peewee import (\n AutoField,\n CharField,\n Database,\n DateTimeField,\n FloatField,\n Model)\nfrom typing import Sequence, Type\n\nfrom vnpy.app.cta_strategy.base import EngineType\nfrom vnpy.trader.constant import Exchange, Direction, Offset\nfrom vnpy.trader.database.investment.base import TradeDataExt, InvestmentData, ProductData, CommissionUnit, \\\n InvestmentState\nfrom .database import InvestmentDatabaseManager\nfrom ..database import Driver\nfrom ..database_sql import ModelBase, init_mysql, init_sqlite, init_postgresql\n\n\ndef init(driver: Driver, settings: dict):\n init_funcs = {\n Driver.SQLITE: init_sqlite,\n Driver.MYSQL: init_mysql,\n Driver.POSTGRESQL: init_postgresql,\n }\n assert driver in init_funcs\n\n db = init_funcs[driver](settings)\n trade, investment, product = init_models(db, driver)\n return InvestmentSqlManager(trade, investment, product)\n\n\ndef init_models(db: Database, driver: Driver):\n class DbTradeData(ModelBase):\n \"\"\"\n 交易记录\n \"\"\"\n id = AutoField()\n symbol: str = CharField()\n product_code: str = CharField()\n exchange: str = CharField()\n datetime: datetime = DateTimeField()\n\n direction: str = CharField()\n offset: str = CharField()\n price: float = FloatField()\n volume: float = FloatField()\n rest_volume: float = FloatField()\n strategy: str = CharField()\n engine_type: str = CharField()\n\n class Meta:\n database = db\n db_table = \"dbtrade\"\n indexes = (((\"datetime\", \"engine_type\", \"symbol\", \"exchange\"), False),)\n\n @staticmethod\n def from_trade(trade: TradeDataExt):\n \"\"\"\n Generate DbTradeData object from TradeData.\n \"\"\"\n db_trade = DbTradeData()\n db_trade.product_code = trade.product_code\n db_trade.symbol = trade.symbol\n db_trade.exchange = trade.exchange.value\n db_trade.datetime = trade.datetime\n db_trade.offset = trade.offset.value\n db_trade.direction = trade.direction.value\n db_trade.volume = trade.volume\n db_trade.rest_volume = trade.volume # 剩余需要开平配对的数量\n db_trade.price = trade.price\n db_trade.strategy = trade.strategy\n db_trade.engine_type = trade.engine_type.value\n\n return db_trade\n\n def to_trade(self):\n trade = TradeDataExt(\n id=self.id,\n product_code=self.product_code,\n symbol=self.symbol,\n exchange=Exchange(self.exchange),\n datetime=self.datetime,\n direction=Direction(self.direction),\n offset=Offset(self.offset),\n price=self.price,\n volume=self.volume,\n rest_volume=self.rest_volume,\n strategy=self.strategy,\n engine_type=EngineType(self.engine_type)\n )\n return trade\n\n @staticmethod\n def save_one(product: \"DbTradeData\") -> int:\n record = product.to_dict()\n return DbTradeData.insert(record).execute()\n\n class DbInvestmentData(ModelBase):\n \"\"\"\n 投资记录\n \"\"\"\n id = AutoField()\n product_code: str = CharField()\n symbol: str = CharField()\n exchange: str = CharField()\n\n start_datetime: datetime = DateTimeField()\n end_datetime: datetime = DateTimeField(null=True)\n\n direction: str = CharField()\n volume: float = FloatField()\n close_volume: float = FloatField()\n\n open_price: float = FloatField()\n finish_price: float = FloatField(null=True) # 多笔平仓价的均价\n\n money_lock: float = FloatField(null=True) # 资金占用\n profit: float = FloatField(null=True) # 毛利润\n cost_fee: float = FloatField(null=True) # 手续费\n net_profit: float = FloatField(null=True) # 净利润 = 毛利润 - 手续费\n profit_rate: float = FloatField(null=True) # 利润率 = 净利润 /\n\n open_trade_id: int = CharField()\n close_trade_ids: str = CharField(null=True)\n\n strategy: str = CharField()\n state: int = CharField()\n engine_type: str = CharField()\n\n class Meta:\n database = db\n db_table = \"dbinvestment\"\n indexes = (((\"start_datetime\", \"engine_type\", \"state\", \"symbol\", \"exchange\"), False),)\n\n @staticmethod\n def from_investment(investment: InvestmentData):\n db_investment = DbInvestmentData()\n db_investment.id = investment.id if investment.id is not None and investment.id > 0 else None\n db_investment.product_code = investment.product_code\n db_investment.symbol = investment.symbol\n db_investment.exchange = investment.exchange.value\n db_investment.open_price = investment.open_price\n db_investment.finish_price = investment.finish_price\n db_investment.volume = investment.volume\n db_investment.close_volume = investment.close_volume\n db_investment.direction = investment.direction.value\n\n db_investment.money_lock = investment.money_lock\n db_investment.profit = investment.profit\n db_investment.profit_rate = investment.profit_rate\n db_investment.net_profit = investment.net_profit\n db_investment.cost_fee = investment.cost_fee\n db_investment.strategy = investment.strategy\n db_investment.start_datetime = investment.start_datetime\n db_investment.end_datetime = investment.end_datetime\n db_investment.open_trade_id = investment.open_trade_id\n if len(investment.close_trade_ids) > 0:\n db_investment.close_trade_ids = \",\".join([str(x) for x in investment.close_trade_ids])\n\n db_investment.state = investment.state.value\n db_investment.engine_type = investment.engine_type.value\n\n return db_investment\n\n def to_investment(self):\n investment = InvestmentData(\n id=self.id,\n exchange=Exchange(self.exchange),\n product_code=self.product_code,\n symbol=self.symbol,\n open_price=self.open_price,\n finish_price=self.finish_price,\n volume=self.volume,\n close_volume=self.close_volume,\n direction=Direction(self.direction),\n\n money_lock=self.money_lock,\n profit=self.profit,\n profit_rate=self.profit_rate,\n net_profit=self.net_profit,\n cost_fee=self.cost_fee,\n strategy=self.strategy,\n start_datetime=self.start_datetime,\n end_datetime=self.end_datetime,\n open_trade_id=self.open_trade_id,\n close_trade_ids=self.close_trade_ids.split(\",\") if self.close_trade_ids is not None else None,\n state=InvestmentState(self.state),\n engine_type=EngineType(self.engine_type)\n )\n return investment\n\n @staticmethod\n def save_one(product: \"DbInvestmentData\"):\n record = product.to_dict()\n DbInvestmentData.insert(record).execute()\n\n class DbProductData(ModelBase):\n \"\"\"\n 期货品种配置\n \"\"\"\n id = AutoField()\n exchange: str = CharField()\n product_code: str = CharField()\n product_name: str = CharField()\n contract_size: float = FloatField()\n margin_percent: float = FloatField()\n commission_unit: str = CharField()\n commission: float = FloatField()\n\n class Meta:\n database = db\n db_table = \"dbproduct\"\n indexes = (((\"exchange\", \"product_code\"), True),)\n\n @staticmethod\n def from_product(product: ProductData):\n db_product = DbProductData()\n db_product.exchange = product.exchange.value\n db_product.product_code = product.product_code\n db_product.product_name = product.product_name\n db_product.contract_size = product.contract_size\n db_product.margin_percent = product.margin_percent\n db_product.commission_unit = product.commission_unit.value\n db_product.commission = product.commission\n return db_product\n\n def to_product(self):\n product = ProductData(\n exchange=Exchange(self.exchange),\n product_code=self.product_code,\n product_name=self.product_name,\n contract_size=self.contract_size,\n margin_percent=self.margin_percent,\n commission_unit=CommissionUnit(self.commission_unit),\n commission=self.commission\n )\n return product\n\n @staticmethod\n def save_one(product: \"DbProductData\"):\n record = product.to_dict()\n if driver is Driver.POSTGRESQL:\n return DbProductData.insert(record).on_conflict(\n action=\"IGNORE\",\n update=record,\n conflict_target=(\n DbProductData.exchange,\n DbProductData.product_code\n ),\n ).execute()\n else:\n return DbProductData.insert(record).on_conflict_ignore().execute()\n\n db.connect()\n db.create_tables([DbTradeData, DbInvestmentData, DbProductData])\n return DbTradeData, DbInvestmentData, DbProductData\n\n\nclass InvestmentSqlManager(InvestmentDatabaseManager):\n\n def __init__(self, class_trade: Type[Model], class_investment: Type[Model], class_product: Type[Model]):\n self.class_trade = class_trade\n self.class_investment = class_investment\n self.class_product = class_product\n\n def save_trade_data(self, data: TradeDataExt) -> int:\n trade = self.class_trade.from_trade(data)\n return self.class_trade.save_one(trade)\n\n def save_investment_data(self, data: InvestmentData) -> int:\n investment = self.class_investment.from_investment(data)\n self.class_investment.save_one(investment)\n\n def get_investment(self, symbol: str, exchange: Exchange, engine_type: str, start_time: datetime) -> InvestmentData:\n s = (\n self.class_investment.select().where(\n (self.class_investment.symbol == symbol)\n & (self.class_investment.exchange == exchange.value)\n & (self.class_investment.engine_type == engine_type)\n & (self.class_investment.state == InvestmentState.PROGRESSING.value)\n & (self.class_investment.start_datetime > start_time)\n ).order_by(self.class_investment.start_datetime.asc()).limit(1)\n )\n\n return s[0].to_investment() if s is not None and len(s) > 0 else None\n\n def load_investment(self, strategy: str, symbol: str, engine_type: str, start_time: datetime,\n end_time: datetime, investment_state: str) -> Sequence[InvestmentData]:\n investment_state_str = investment_state if investment_state != \"\" else None\n\n end_time = datetime(end_time.year, end_time.month, end_time.day, hour=23, minute=59, second=59, microsecond=59)\n s = (\n self.class_investment.select().where(\n (((self.class_investment.symbol ** f'%{symbol}%') | (\n self.class_investment.exchange ** f'%{symbol}%')) | (symbol is None or symbol.isspace()))\n & ((self.class_investment.strategy ** f'%{strategy}%') | (strategy is None or strategy.isspace()))\n & (self.class_investment.engine_type == engine_type)\n & ((self.class_investment.state == investment_state_str) | (investment_state_str is None))\n & (self.class_investment.start_datetime >= start_time)\n & (self.class_investment.start_datetime <= end_time)\n ).order_by(self.class_investment.start_datetime.asc())\n )\n # print(s)\n data = [db_investment.to_investment() for db_investment in s]\n return data\n\n def finish_investment(self, data: InvestmentData):\n investment = self.class_investment.from_investment(data)\n investment.save()\n\n def save_product_data(self, data: ProductData) -> int:\n product = self.class_product.from_product(data)\n return self.class_product.save_one(product)\n\n def load_all_product(self) -> Sequence[\"ProductData\"]:\n s = (self.class_product.select())\n data = [db_product.to_product() for db_product in s]\n return data\n\n def get_product(self, product_code: str, exchange: Exchange) -> \"ProductData\":\n s = (self.class_product.select().where((self.class_product.product_code == product_code)\n & (self.class_product.exchange == exchange.value)))\n return s[0].to_product() if s is not None and len(s) > 0 else None\n\n def get_trade_data(self, trade_id: int) -> \"TradeDataExt\":\n s = (self.class_trade.select().where((self.class_trade.id == trade_id)))\n return s[0].to_trade() if s is not None and len(s) > 0 else None\n","sub_path":"vnpy/trader/database/investment/database_sql.py","file_name":"database_sql.py","file_ext":"py","file_size_in_byte":13554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"553525241","text":"from django.shortcuts import render, redirect\nfrom .models import Article\n\n# Create your views here.\n# [GET 게시글 전체 리스트를 보여주는 함수\ndef index(request):\n # 1. Article 모델 클래스의 모든 인스턴스 들고오기 -> 리턴 값은 쿼리셋 형태\n articles = Article.objects.order_by('-pk') #DB단\n # articles = Article.objects.all()[::-1] #Python단\n context = {\n 'articles' : articles,\n }\n return render(request, 'articles/index.html', context)\n\n# [GET] 게시글 하나에 대한 상세정보를 보여주는 함수\ndef detail(request, pk):\n #데이터베이스에서 게시글 가져오기\n article = Article.objects.get(pk=pk)\n context = {\n 'article' : article,\n }\n # 게시글을 템플릿에 넘겨주기\n return render(request, 'articles/detail.html', context)\n\n# [GET] 사용자에게 게시글 작성 Form을 보여주는 함수\ndef new(request):\n return render(request, 'articles/new.html')\n\n# [POST] 사용자로부터 Form으로 제출한 데이터를 받아서 DB에 저장하는 함수\ndef create(request):\n # 1. DB 저장하기\n # 1-1. 사용자가 보낸 데이터 추출하기\n title = request.POST.get('title')\n content = request.POST.get('content')\n\n # 1-2. DB에 새로운 게시글 저장하기\n article = Article(title=title, content=content)\n article.save()\n # Article.objects.create(title=title, content=content)\n\n # 2. DB 저장이 끝난 후 게시글 상세정보로 리다이렉트하기\n # return render(request, 'articles/create.html')\n # return redirect('/articles/')\n # 파이썬 파일에서 넘겨줄떈 콤마 찍고 쓰고, html에선 한칸 띄우면됨.\n return redirect('articles:detail', article.pk)\n\ndef delete(request, pk):\n # 1. 삭제할 게시글 가져오기\n article = Article.objects.get(pk=pk)\n # 요청 형태가 'POST'인 경우에만 게시글 삭제\n if request.method == 'POST':\n # 2. 삭제하기\n article.delete()\n # 3. 메인 페이지로 Redirect\n return redirect('articles:index')\n # 'POST'가 아니면\n else:\n # return redirect('articles:index')\n return redirect('articles:detail', article.pk)\n\ndef edit(request,pk):\n article = Article.objects.get(pk=pk)\n context = {\n 'article' : article,\n }\n return render(request, 'articles/edit.html', context)\n\ndef update(request, pk):\n # 1.수정할 pk번 게시글 가져오기\n article = Article.objects.get(pk=pk)\n # 2. 사용자가 제출한 데이터로 게시글 정보를 수정하기\n article.title = request.POST.get('title')\n article.content = request.POST.get('content')\n # 3. 데이터베이스에 저장하기\n article.save()\n # 4. 게시글 상세정보 페이지로 Redirect\n return redirect('articles:detail', article.pk)","sub_path":"web/problems/0820/crud/articles/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"533187227","text":"\"\"\"\nmotexml: MoteXML binary XML encoding format python support package.\nWarpper around shared library for python.\n\"\"\"\n\nfrom setuptools import setup, find_packages\nfrom os.path import join as pjoin\n\nimport motexml\n\ndoclines = __doc__.split(\"\\n\")\n\nsetup(name='motexml',\n version=motexml.__version__,\n description='MoteXML binary XML encoding format python support package.',\n long_description='\\n'.join(doclines[2:]),\n url='http://github.com/proactivity-lab/python-motexml',\n author='Raido Pahtma',\n author_email='raido.pahtma@ttu.ee',\n license='MIT',\n platforms=['any'],\n packages=find_packages(),\n install_requires=[],\n test_suite='nose.collector',\n tests_require=['nose'],\n scripts=[pjoin('bin', 'motexml-generate'), pjoin('bin', 'motexml-to-xml'), pjoin('bin', 'motexml-from-xml')],\n zip_safe=False)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"558586478","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\nfrom django.utils.timezone import utc\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('jobs', '0007_auto_20150710_2220'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='event',\n name='pub_date',\n ),\n migrations.AddField(\n model_name='event',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 7, 11, 2, 23, 36, 293000, tzinfo=utc), verbose_name='date of event'),\n preserve_default=False,\n ),\n ]\n","sub_path":"src/jobs/migrations/0008_auto_20150710_2223.py","file_name":"0008_auto_20150710_2223.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"281825662","text":"from time import sleep as sl\nimport glob\nfrom os.path import basename\nfrom os import remove\nimport os\nfrom Bio.Blast.Applications import NcbiblastnCommandline\nfrom Bio.Blast import NCBIXML\nimport glob\nfrom multiprocessing.dummy import Pool as ThreadPool\nimport multiprocessing\nimport time\nimport subprocess as sub\nimport itertools\nimport shutil\nimport sys\nfrom Bio import SeqIO\nfrom Bio import SeqRecord\nfrom Bio.Seq import Seq\nimport inspect\nimport re\n\n\nstart_time = time.time()\n\n\"\"\"\n1 - Pick scheme\n2 - Blast all loci in scheme\n3 - Perfect matches store match and fact of match\n4 - any loci with no perfect match store location in query genome from matches to intact alleles\n5 - blast newly defined allele region against complete allele set\n6 - call alleles\n\"\"\"\n\ndef get_allele_pos(allele_location):\n \"\"\"\n :param allele_location: allele location file\n :return: dictionary of {allele name: [allele_st,allele_end,allele_direction]}\n \"\"\"\n inf = [x.split('\\t') for x in open(allele_location,\"r\").readlines()]\n outd = {y[0]:y[1:] for y in inf}\n return outd\n\n\ndef makedb(fasta,dbfolder):\n \"\"\"\n\n :param fasta: fasta file to make database with\n :param dbfolder: folder to write db to\n :return: nothing BUT runds makeblastdb to generate the blast database required\n \"\"\"\n out = fasta.split(\"/\")[-1]\n path = dbfolder+\"/\"+out\n p = sub.Popen(['makeblastdb', '-dbtype','nucl','-in',fasta,\"-out\",path],stdout=sub.PIPE,stderr=sub.PIPE)\n p.communicate()\n\n\ndef mean(numbers):\n return float(sum(numbers)) / max(len(numbers), 1)\n\n\ndef run_blast(query_seq,locus_db,wordsize):\n \"\"\"\n\n :param query_seq: query sequence - can be multiple fasta seqs\n :param locus_db: blastdb path\n :param wordsize: blast word size\n :return: returns list of blast results\n \"\"\"\n cpus = multiprocessing.cpu_count()\n gene = basename(locus_db).replace(\".fasta\",\"\")\n tmp_out = \"tmp/\"+gene+\"_tmp_blast.xml\"\n cline = NcbiblastnCommandline(\n query=query_seq,\n db=locus_db,\n evalue=10,\n perc_identity=90,\n out=tmp_out,\n outfmt=5,\n max_target_seqs=10000,\n max_hsps=3,\n word_size=wordsize,\n num_threads=cpus,\n task=\"dc-megablast\")\n\n stdout, stderr = cline()\n\n r_handle = open(tmp_out)\n\n blast_records = list(NCBIXML.parse(r_handle))\n\n remove(tmp_out)\n \"\"\"\n blast_records structure: \n list of results (if multifasta input, one result per fasta seq) \n \n result attributes: >>>'alignments'<<<, 'application', 'blast_cutoff', 'database', 'database_length', 'database_letters', 'database_name', 'database_sequences', 'date', 'descriptions', 'dropoff_1st_pass', 'effective_database_length', 'effective_hsp_length', 'effective_query_length', 'effective_search_space', 'effective_search_space_used', 'expect', 'filter', 'frameshift', 'gap_penalties', 'gap_trigger', 'gap_x_dropoff', 'gap_x_dropoff_final', 'gapped', 'hsps_gapped', 'hsps_no_gap', 'hsps_prelim_gapped', 'hsps_prelim_gapped_attemped', 'ka_params', 'ka_params_gap', 'matrix', 'multiple_alignment', 'num_good_extends', 'num_hits', 'num_letters_in_database', 'num_seqs_better_e', 'num_sequences', 'num_sequences_in_database', 'posted_date', 'query', 'query_id', 'query_length', 'query_letters', 'reference', 'sc_match', 'sc_mismatch', 'threshold', 'version', 'window_size']\n alignment attributes: 'accession', 'hit_def', 'hit_id', >>>'hsps'<<<, 'length', 'title']\n hsp attributes: 'align_length', 'bits', 'expect', 'frame', 'gaps', 'identities', 'match', 'num_alignments', 'positives', 'query', 'query_end', 'query_start', 'sbjct', 'sbjct_end', 'sbjct_start', 'score', 'strand'\n \"\"\"\n\n return blast_records\n\n\ndef return_scheme_loci_ls(schemefolder):\n \"\"\"\n :param schemefolder: accession list folder regex\n :return: dictionary of each scheme as key with list of loci as value\n \"\"\"\n inschemes = glob.glob(schemefolder)\n schemes = {}\n\n for scheme in inschemes:\n sc = scheme.split(\"/\")[-1].replace(\"_gene_accessions.txt\", \"\")\n s = open(scheme, \"r\").read().splitlines()\n schemes[sc] = s\n\n return schemes\n\n\ndef get_allele_fastas(allelefolder):\n allele_list = glob.glob(allelefolder)\n allele_fastas = {}\n for allele in allele_list:\n name = basename(allele).replace(\".fasta\",\"\")\n allele_fastas[name] = allele\n return allele_fastas\n\n\ndef get_word_size(allele_fasta):\n \"\"\"\n\n :param allele_fasta: fasta path for alleles of a locus\n :return: word size for use in blast that is 20% of the average locus length\n \"\"\"\n alleles = SeqIO.parse(allele_fasta,\"fasta\")\n sizes = []\n sizesdict = {}\n for i in alleles:\n sizes.append(len(i.seq))\n avsize = mean(sizes)\n wordsize = int(avsize*0.2)\n # print(wordsize)\n return wordsize\n\ndef print_blasthsp(result,alignment,hsp,alignment_locus):\n print(\"\\n\\n\")\n print(alignment.hit_def)\n # print('allele size:', sizes[alignment_locus + \"-1\"])\n print('alignment length:', hsp.align_length)\n print('identities:', hsp.identities)\n print('gaps:', hsp.gaps)\n print('query contig', result.query)\n print('query start', hsp.query_start)\n print('query end: ', hsp.query_end)\n print('subject start', hsp.sbjct_start)\n print('subject end: ', hsp.sbjct_end)\n print(hsp.query)\n print(hsp.match)\n print(hsp.sbjct)\n\ndef get_exactmatches(blasthits,partial_hit,allele_sizes):\n \"\"\"\n\n :param blasthits: parsed blast output as list of qury seq results\n :param partial_hit:list of loci, when an exact hit is found it is removed from list - resulting in a list of loci still to be examined\n :param allele_sizes: allele lengths of reference alleles\n :return: alleles that match exactly for length with no gaps and 100% identity - one for each locus - alleles with Ns are ignored\n \"\"\"\n exacthits = 0\n totalhits = 0\n perfect_hit = {}\n # print(partial_hit)\n for result in blasthits:\n for alignment in result.alignments:\n for hsp in alignment.hsps:\n if hsp.identities == alignment.length and hsp.gaps == 0 and alignment.length == allele_sizes[alignment.hit_def]:\n perfect_hit_allele = alignment.title.split(\" \")[-1]\n perfect_hit_locus = perfect_hit_allele.split(\"-\")[0]\n # print(perfect_hit_locus)\n perfect_hit[perfect_hit_locus] = perfect_hit_allele\n partial_hit.remove(perfect_hit_locus)\n exacthits +=1\n totalhits += 1\n elif hsp.identities > (alignment.length*0.5) and hsp.identities < alignment.length:\n totalhits +=1\n\n print(\"exact hits: \" + str(exacthits) + \", total hits: \" + str(totalhits) + \", remaining loci to check: \" + str(len(partial_hit)))\n\n return partial_hit, perfect_hit\n\n\ndef get_partial_match_query_region(blast_results,partial_matches,sizes):\n \"\"\"\n\n :param blast_results: 1st round blast results\n :param partial_matches: loci without exact matches\n :return: partials dictionary {locus:list of tuples} tuple -> (hsp matching reference allele,query contig where match was found)\n Also writes fasta file of these hits for each locus to be used to blast all alleles of the locus\n \"\"\"\n\n # print(partial_matches)\n partials = {}\n for result in blast_results:\n for alignment in result.alignments:\n alignment_locus = alignment.hit_def.rsplit(\"-\")[0]\n if alignment_locus in partial_matches and alignment.hit_def == alignment_locus+\"-1\":\n for hsp in alignment.hsps:\n if 'STMMW_00001' in alignment_locus:\n print(\"\\n\\n\")\n print(alignment.hit_def)\n # print('allele size:',sizes[alignment_locus+\"-1\"])\n print('alignment length:', hsp.align_length)\n print('identities:', hsp.identities)\n print('gaps:', hsp.gaps)\n print('query contig', result.query)\n print('query start', hsp.query_start)\n print('query end: ', hsp.query_end)\n print('subject start', hsp.sbjct_start)\n print('subject end: ', hsp.sbjct_end)\n print(hsp.query)\n print(hsp.match)\n print(hsp.sbjct)\n if alignment_locus not in partials:\n partials[alignment_locus] = [(hsp,result.query)]\n else:\n partials[alignment_locus].append((hsp,result.query))\n\n ### for queries with non intact hit to ref allele check other hits to see if remainder of locus is present before calling deletion - could be caused by assembly error or repetitive insertion\n ### need to deal with split matches that overlap - STMMW_45221-1 in current example 100 gene scheme\n for locus in partials:\n hsplis = []\n c = 1\n for hsp in partials[locus]:\n hitseq = Seq(hsp[0].query.replace(\"-\",\"\"))\n # hitseq = only_nucs(hitseq)\n s = SeqRecord.SeqRecord(hitseq,locus+\"_hit_no_\"+str(c),description=\"\")\n hsplis.append(s)\n c+=1\n SeqIO.write(hsplis,\"tmp/\"+locus+\"_hits.fasta\",\"fasta\")\n return partials\n\n\ndef only_nucs(instring):\n outstring = ''\n for n in instring:\n if n in [\"A\",\"T\",\"G\",\"C\",\"N\",\"a\",\"t\",\"c\",\"g\",\"n\"]:\n outstring+=n\n return outstring\n\n\ndef run_secondary_N_blast(partialhsps,allelefastas):\n \"\"\"\n Make blast db from alleles for locus of interest\n blast hit regions in query genome against db\n :param partialhsps: all hsps matching to loci without exact alleles\n :param allele_fastas: dictionary of {locus:alleles path}\n :return: blast results in same format as run_blast() function\n \"\"\"\n secresults = {}\n for locus in partialhsps:\n for i in allelefastas:\n if i == locus:\n makedb(allelefastas[locus],\"tmp\")\n sec_blast_results = run_blast(\"tmp/\"+locus+\"_hits.fasta\",\"tmp/\"+locus+\".fasta\",11)\n secresults[locus] = sec_blast_results\n return secresults\n\n\ndef return_n_ignored_hit_identities(hsp):\n # TODO:may need to check for locations where N nucleotides align with gaps - not sure what to do there...\n \"\"\"\n :param hsp: hsp from a blast output\n :return: number of matches in a HSP including positions where either query or subject have an N\n \"\"\"\n ident = int(hsp.identities)\n for pos in range(len(hsp.query)):\n if hsp.query[pos] == \"N\" or hsp.query[pos] == \"n\" or hsp.sbjct[pos] == \"N\" or hsp.sbjct[pos] == \"n\":\n ident +=1\n return ident\n\n\ndef reverse_complement(dna):\n complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A',\"-\":\"-\",\"N\":\"N\"}\n return ''.join([complement[base] for base in dna[::-1]])\n\n\ndef find_muts_frm_sec_results(s_results,allele_sizes,ref_pos):\n # TODO: loci that have two intact hits with the reference - may need to mark as 0 unless we implement synteny identification\n \"\"\"\n\n :param s_results: all secondary blast results\n :param allele_sizes: length of all alleles\n :param ref_pos: positions of loci in the reference (allows genome position naming of SNPs)\n :return: list of snps in (ref,pos,change) format relative to the allele\n also return deletions and insertions IN THE UNKNOWN ALLELE i.e. treat reference as unchanged\n del format (ref,pos,\"del\")\n ins format (\"ins\",pos,nuc) - insertions will be a series of changes at the same reference position\n remaining loci - loci that do not have a single hit that alignes to the reference from start to end\n multiple_hits - loci that have two intact hits with the reference - may need to mark as 0 unless we implement synteny identification somewhere\n newalleles - for a locus where there is one hit that spans the reference, the locus and sequence(with \"-\" removed) returned in dictionary of {locus:sequence}\n \"\"\"\n\n snps = {}\n deletions = {}\n insertions = {}\n remaining_loci = []\n multiple_hits = []\n newalleles = {}\n anymuts = {}\n for locus in s_results:\n remaining_loci.append(locus)\n snps[locus] = []\n deletions[locus] = []\n insertions[locus] = []\n anymuts[locus] = []\n genome_pos = int(ref_pos[locus][0])\n for result in s_results[locus]:\n for alignment in result.alignments:\n if alignment.hit_def == locus + \"-1\":\n alignment_locus = alignment.hit_def.rsplit(\"-\")[0]\n for hsp in alignment.hsps:\n orient = \"+\"\n unknown_allele = hsp.query\n ref_allele = hsp.sbjct\n matches = hsp.match\n refstart = hsp.sbjct_start\n refend = hsp.sbjct_end\n ## re-orient matches so positions are always in direction of reference allele\n if int(hsp.sbjct_start) > int(hsp.sbjct_end):\n orient = \"-\"\n unknown_allele = reverse_complement(unknown_allele)\n ref_allele = reverse_complement(ref_allele)\n matches = matches[::-1]\n refstart,refend = refend,refstart\n\n intact_nucs = [\"A\", \"T\", \"G\", \"C\", \"a\", \"t\", \"c\", \"g\"]\n for i in range(len(unknown_allele)):\n if matches[i] == \" \":\n if unknown_allele[i] in intact_nucs and ref_allele[i] in intact_nucs:\n pos = i - ref_allele[:i].count(\n \"-\") # correct for reference allele length if it is changed by upstream insertions in the query\n nuc = (ref_allele[i], genome_pos + pos, unknown_allele[i])\n snps[locus].append(nuc)\n anymuts[locus].append(nuc)\n elif unknown_allele[i] == \"-\" and ref_allele[i] in intact_nucs:\n pos = i - ref_allele[:i].count(\"-\")\n d = (ref_allele[i], genome_pos + pos, \"del\")\n deletions[locus].append(d)\n anymuts[locus].append(d)\n elif unknown_allele[i] in intact_nucs and ref_allele[i] == \"-\":\n pos = i - ref_allele[:i].count(\"-\")\n ins=(\"ins\", genome_pos + pos, unknown_allele[i])\n insertions[locus].append(ins)\n anymuts[locus].append(ins)\n\n if refstart == 1 and refend == allele_sizes[locus+\"-1\"]: # this step gets hit that covers reference allele\n if locus in remaining_loci and \"N\" not in unknown_allele:\n remaining_loci.remove(locus)\n else:\n multiple_hits.append(locus)\n if \"N\" not in unknown_allele:\n newalleles[locus] = unknown_allele.replace(\"-\",\"\")\n\n return anymuts,snps,deletions,insertions,remaining_loci,multiple_hits,newalleles\n\n\ndef make_intact_allele_fasta(scheme_fastas,dbname):\n \"\"\"\n\n :param scheme_fastas: fasta file paths for scheme of interest\n :param dbname: output fasta path\n :return:fasta file with all intact alleles derived from fasta files of loci making up a scheme\n \"\"\"\n outseqs = []\n for fname in scheme_fastas:\n infile = SeqIO.parse(fname,\"fasta\")\n for allele in infile:\n if \"--\" not in allele.id:\n outseqs.append(allele)\n SeqIO.write(outseqs,dbname,\"fasta\")\n\ndef remove_Ns(inseq):\n outname = inseq.replace(\".fasta\",\"_no_n.fasta\")\n seqs = SeqIO.parse(inseq,\"fasta\")\n no_n_ls = []\n for s in seqs:\n s2 = s\n s2.seq = Seq(str(s.seq).replace(\"N\",\"\"))\n no_n_ls.append(s2)\n SeqIO.write(no_n_ls,outname,\"fasta\")\n return outname\n\ndef check_ends(contig,qstart,qend,sstart,send,reflen):\n ## if hit in reverse orientation have to check opposite end of hit in query genome\n\n new_qstart = 0\n new_qend = 0\n added_start = ''\n added_end = ''\n\n\n\n if int(sstart) > int(send):\n new_qstart = int(qstart) - (reflen - int(sstart))\n new_qend = int(qend) + int(send) - 1\n\n\n elif int(sstart) < int(send):\n new_qstart = int(qstart) - int(sstart)\n new_qend = int(qend) + (reflen - int(send) - 1)\n\n added_start = contig[new_qstart:int(qstart) - 1]\n added_end = contig[int(qend):new_qend - 1]\n\n ## if missing flanking region is not all Ns then use original query hit edge - allows for rearrangements/deletions where flanking regions are really gone\n if added_start.count(\"N\") != len(added_start):\n new_qstart = qstart\n added_start = [\"del\",len(added_start)]\n if added_end.count(\"N\") != len(added_end):\n new_qend = qend\n added_end = [\"del\", len(added_end)]\n full_allele = contig[new_qstart:new_qend]\n\n return full_allele,added_start,added_end\n\ndef check_all_orient(hsp_list):\n orient = []\n for tup in hsp_list:\n hsp = tup[0]\n if hsp.sbjct_end < hsp.sbjct_start:\n orient.append(\"negative\")\n else:\n orient.append(\"positive\")\n if len(list(set(orient))) > 1:\n return \"mixed\"\n else:\n return orient[0]\n\ndef largest_nonn_strings(string):\n matches = re.findall(r\"[ATGC]*\",string)\n mx = max([len(x) for x in matches])\n return mx\n\ndef check_mid(contig,hspls,q_genome,wordsize,reflen):\n \"\"\"\n use word length ratio as cutoff for allowing non-N letters in restored gap sequence(i.e. if word length is 12. non-N sequence chunk can be a max of 18 before mid regions is called something else)\n :param contig:\n :param hspls:\n :param q_genome:\n :return:\n \"\"\"\n\n\n orient = check_all_orient(hspls)\n if orient == \"mixed\":\n # TODO work out what to do with mixed orientation\n return \"mixed_orientation\"\n else:\n ordered_by_query = []\n order = {}\n for tup in hspls:\n hsp = tup[0]\n order[hsp.query_start] = hsp\n\n sorted_hsps = sorted(map(int, order.keys()))\n full_allele = order[sorted_hsps[0]].query\n sstart = order[sorted_hsps[0]].sbjct_start\n send = order[sorted_hsps[-1]].sbjct_end\n qstart = order[sorted_hsps[0]].query_start\n qend = order[sorted_hsps[-1]].query_start\n\n for start in range(len(sorted_hsps)-1):\n hsp = order[sorted_hsps[start]]\n hspnext = order[sorted_hsps[start+1]]\n mid_section_st = int(hsp.query_end)\n mid_section_en = int(hspnext.query_start)\n mid_section_seq = q_genome[contig][mid_section_st:mid_section_en-1]\n full_allele += mid_section_seq\n full_allele += hspnext.query\n\n nonn_size = largest_nonn_strings(mid_section_seq)\n if nonn_size > (wordsize*2):\n return \"possible_insertion\"\n\n full_allele, added_start, added_end = check_ends(contig, qstart, qend, sstart, send, reflen)\n\n return full_allele\n\n\n\n\n\n\n\n\n\n\n\n # nmin = 0\n # nmax = 0\n # if hsp.sbjct_end < hsp.sbjct_start:\n # nmin = hsp.sbjct_end\n # nmax = hsp.sbjct_start\n # else:\n # nmin = hsp.sbjct_start\n # nmax = hsp.sbjct_end\n # if nmin < min:\n # min = nmin\n # if nmax > max:\n # max = nmax\n #\n # hsp = tup[0]\n # queryid = tup[1]\n # contig = q_genome[queryid]\n # print(\"\\n\")\n # # print('allele length:', reflen)\n # print('alignment length:', hsp.align_length)\n # print('identities:', hsp.identities)\n # print('gaps:', hsp.gaps)\n # print('query contig', queryid)\n # print('query start', hsp.query_start)\n # print('query end: ', hsp.query_end)\n # print('subject start', hsp.sbjct_start)\n # print('subject end: ', hsp.sbjct_end)\n # print(hsp.query)\n # print(hsp.match)\n # print(hsp.sbjct)\n # print(min,max)\n\ndef reconstruct_n_interupted_loci(locus,hspls,query_genome,reflen,missing_perc_cutoff,wordsize,s_results):\n query_genome = SeqIO.parse(query_genome,\"fasta\")\n q_genome = {}\n\n full_allele = \"\"\n\n for s in query_genome:\n q_genome[s.id] = str(s.seq)\n\n ##check that number of identities in blast hits is at least X fraction of normal reference allele length\n ident_no = 0\n for tup in hspls:\n matches = int(tup[0].identities)\n ident_no += matches\n fraction_ident = float(ident_no)/float(reflen)\n if fraction_ident < float(missing_perc_cutoff):\n # print(locus,\"unscorable: number of Ns exceeds cutoff\")\n return \"unscorable_too_much_missing\",\"\"\n\n if len(hspls) > 1:\n contigs = {}\n hsp_to_investigate = []\n for tup in hspls:\n hsp = tup[0]\n contig = tup[1].split(\" \")[0]\n if contig not in contigs:\n contigs[contig] = [tup]\n else:\n contigs[contig].append(tup)\n\n # if hits come from > 1 contig\n if len(contigs.keys()) > 1:\n return \"split over contigs\",\"\"\n else:\n for c in contigs:\n fixed_mid = check_mid(c, contigs[c],q_genome,wordsize,reflen)\n if fixed_mid == \"possible_insertion\":\n return \"possible_insertion\",\"\"\n elif fixed_mid == \"mixed_orientation\":\n return \"mixed_orientation\",\"\"\n else:\n full_allele = fixed_mid\n\n else:\n # print(locus+\": \"+hspls[0][1])\n hsp = hspls[0][0]\n queryid = hspls[0][1].split(\" \")[0]\n contig = q_genome[queryid]\n # print(\"\\n\")\n # print('allele length:', reflen)\n # print('alignment length:', hsp.align_length)\n # print('identities:', hsp.identities)\n # print('gaps:', hsp.gaps)\n # print('query contig', queryid)\n # print('query start', hsp.query_start)\n # print('query end: ', hsp.query_end)\n # print('subject start', hsp.sbjct_start)\n # print('subject end: ', hsp.sbjct_end)\n # print(hsp.query)\n # print(hsp.match)\n # print(hsp.sbjct)\n\n full_allele,added_start,added_end = check_ends(contig,hsp.query_start,hsp.query_end,hsp.sbjct_start,hsp.sbjct_end,reflen)\n\n \"\"\"\n Get partial matches to loci:\n when match has end missing check input genome for Ns back to start/end of locus\n - if Ns store this in allele\n - if not Ns store as truncated allele\n\n when multiple hits check if on same contig:\n - if yes then check if gap between is Ns or something else\n - if Ns reconstruct allele\n - if not Ns - potential large indel or other rearrangement\n - if no split allele - return pieces for other analysis\n\n - if no snps or indels of another type - need to generate -1_X\n - if snps or indels store\n :param partial_hits_to_ref_allele: for each locus existing hits to the ref (-1) allele\n :param query_genome:\n :return:\n \"\"\"\n if float(len(full_allele)) > 1.5*float(reflen):\n # print(locus,\"unscorable: N-locus too long!!\")\n return \"unscorable_too_long\",\"\"\n\n # need to get closest hit of non N region/s and record muts\n\n # if single region then get list of alleles with 0 indels or snps, if either is present > new allele\n exact_ns = \"\"\n idents = []\n allele = []\n mutno = []\n sbjct_n_no = []\n #count how many mismatches there are to each alignment as well as how many identities (i.e. across multiple hsps if present), also need to take into account large dels from\n for result in s_results[locus]:\n for alignment in result.alignments:\n muts = 0\n ident = 0\n sbjct_n = 0\n alignment_locus = alignment.hit_def.rsplit(\"-\")[0]\n for hsp in alignment.hsps:\n ident += int(hsp.identities)\n for pos in range(len(hsp.match)):\n if \" \" in hsp.match[pos] and hsp.query[pos] != \"N\" and hsp.sbjct[pos] != \"N\":\n muts+=1\n if hsp.sbjct[pos] == \"N\":\n sbjct_n += 1\n allele.append(alignment.hit_def)\n idents.append(ident)\n mutno.append(muts)\n sbjct_n_no.append(sbjct_n)\n #get the highest identity score in all alignments\n maxident = max(idents)\n # get all allele matches that have the highest identity\n tophits = []\n muts = {}\n for hit in range(len(idents)):\n if idents[hit] == maxident:\n if mutno[hit] == 0 and sbjct_n_no[hit] == 0:\n # print(allele[hit],idents[hit])\n tophits.append(allele[hit])\n muts[allele[hit]]=\"no\"\n elif sbjct_n_no[hit] > 0 and mutno[hit] == 0:\n tophits.append(allele[hit])\n print(\"Ns\",allele[hit], idents[hit])\n muts[allele[hit]] = \"no\"\n elif sbjct_n_no[hit] > 0 and mutno[hit] > 0:\n print(\"MUTS + Ns\", allele[hit], idents[hit])\n tophits.append(allele[hit])\n muts[allele[hit]] = \"yes\"\n else:\n print(\"MUTS\", allele[hit], idents[hit])\n tophits.append(allele[hit])\n muts[allele[hit]] = \"yes\"\n\n # if >1 +ve hit mark as unsure\n # if 1 +ve mark as -ve version of allele and check if it already exists\n # if 1 or more -ve versions of the same allele with no others mark as -ve version of allele and check if it already exists\n intact = [x for x in tophits if \"--\" not in x]\n if len(intact) > 1:\n return \"mutiple_tophits\",full_allele\n elif len(intact) == 1 and muts[intact[0]] == \"no\":\n return \"new neg allele\",[intact[0].split(\"-\")[-1],full_allele]\n elif len(intact) == 1 and muts[intact[0]] == \"yes\":\n if \"N\" in full_allele:\n return \"novel neg allele\", full_allele\n else:\n # TODO : need to record that these cases represent large deletions relative to the reference allele\n return \"novel pos allele\", full_allele\n elif len(intact) == 0:\n alleles = list(set([x.split(\"-\")[-1].split(\"_\")[0] for x in tophits]))\n\n if len(alleles) > 1:\n return \"mutiple_neg_tophits\",full_allele\n elif len(alleles) == 1 and muts[alleles[0]] == \"no\":\n return \"new neg allele\",[\"-\"+alleles[0],full_allele]\n elif len(intact) == 1 and muts[alleles[0]] == \"yes\":\n if \"N\" in full_allele:\n return \"novel neg allele\", full_allele\n else:\n #TODO : need to record that these cases represent large deletions relative to the reference allele\n return \"novel pos allele\", full_allele\n else:\n return \"nohits\",full_allele\n\n\n return \"other_investigate\",full_allele\n\n # if >1 region get alleles that are exact mathes to all regions if any snps or indels to top hit > new allele\n\n\n # print(\"\\nSequence added at start: \\n\",added_start,\"\\n\",\"Sequence added at end: \\n\",added_end,\"\\n\",full_allele)\n\n # print(locus,hspls)\n # return full_allele\n\n\ndef main(schemelists, alleles, query_genome,locus_refrence_locs,scheme,wordsize):\n\n cpus = multiprocessing.cpu_count()\n\n if os.path.exists(\"tmp\"):\n shutil.rmtree('tmp')\n os.mkdir(\"tmp\")\n else:\n os.mkdir(\"tmp\")\n inschemes = schemelists + \"/*.txt\"\n\n alleles_folder = alleles + \"/*.fasta\"\n\n # gets dictionary with lists of loci for each scheme\n scheme_gene_lists = return_scheme_loci_ls(inschemes)\n\n # gets list of allele fasta file paths\n allele_fastas = get_allele_fastas(alleles_folder)\n\n # gets list of loci in scheme of interest\n schemelist = scheme_gene_lists[scheme]\n\n # gets allele reference contig, positions and orientation dict\n locus_positions = get_allele_pos(locus_refrence_locs)\n\n wordsizes = []\n scheme_fastas = []\n\n ## makes a list of all of the fasta files in the scheme of interest\n ## also makes list of word size to use depending on ref allele size\n for i in schemelist:\n allele_file = allele_fastas[i]\n scheme_fastas.append(allele_file)\n ws = get_word_size(allele_file)\n wordsizes.append(ws)\n\n\n ##writes all fasta files in scheme to tmpdb location -- effectively a python \"cat\"\n tmpdb = \"tmp/\"+scheme+\"_alleles.fasta\"\n\n # with open(tmpdb, 'w') as outfile:\n # for fname in scheme_fastas:\n # with open(fname) as infile:\n # outfile.write(infile.read())\n make_intact_allele_fasta(scheme_fastas,tmpdb)\n\n ##generates blast db from above concatenated fasta file\n makedb(tmpdb, \"tmp/\")\n\n\n ##load scheme allele fastas as Seq object\n allele_sizes = {}\n\n scheme_alleles = SeqIO.parse(tmpdb,\"fasta\")\n\n ## make dict of allele sizes\n for allele in scheme_alleles:\n allele_sizes[allele.id] = len(allele.seq)\n\n\n no_n_query_genome = remove_Ns(query_genome)\n\n ##return blast results\n # blast_hits = run_blast(no_n_query_genome, tmpdb, 12)\n blast_hits = run_blast(query_genome, tmpdb, wordsize)\n\n ##complete loci are exact matches to an allele already in the db\n ##partial loci are the rest\n partial_loci,complete_loci = get_exactmatches(blast_hits,schemelist,allele_sizes)\n\n ##returns hsps that give the positions of matches in the query genomes that match the \"1\"/reference allele\n ## also writes these regions to one fasta file for each locus different hsps are called \"_hit_no_1\", \"hit_no_2\" etc\n partial_hsps = get_partial_match_query_region(blast_hits,partial_loci,allele_sizes)\n\n # for i in complete_loci:\n # print(i,complete_loci[i])\n # sl(0.2)\n\n # for locus in partial_hsps:\n # print(\"\\n\")\n # print(locus)\n # print(\"ref allele length:\",allele_sizes[locus+\"-1\"])\n # for tup in partial_hsps[locus]:\n # hsp = tup[0]\n # queryid = tup[1]\n # print(\"\\n\")\n # # print('allele length:', allele_sizes[alignment.hit_def])\n # print('alignment length:', hsp.align_length)\n # print('identities:', hsp.identities)\n # print('gaps:', hsp.gaps)\n # print('query contig', queryid)\n # print('query start', hsp.query_start)\n # print('query end: ', hsp.query_end)\n # print('subject start', hsp.sbjct_start)\n # print('subject end: ', hsp.sbjct_end)\n # print(hsp.query)\n # print(hsp.match)\n # print(hsp.sbjct)\n\n ## run blast for each locus with 'query genome region that corresponds to \"reference\" allele hit regions' against all alleles for that locus\n\n sec_results = run_secondary_N_blast(partial_hsps,allele_fastas)\n\n# -----------------\n # different process for split hits\n # check for Ns\n # check for missing ends\n # check for indels - always call relative to existing allele\n # if gap in subject = insertion in query\n # if gap in query = deletion in query\n # check for SNPs\n# ------------------\n\n ### if match against reference runs from reference start to end then snps/indesl can be called without checking for missing ends\n ### therefore can extract snps from alignment against \"-1\" reference allele using locus blast results - find_snps function\n\n all_muts,snp_dict,deldict,insdict,remaining_loci,mult_hits,new_alleles = find_muts_frm_sec_results(sec_results,allele_sizes,locus_positions)\n\n # for i in new_alleles:\n # print(i,snp_dict[i],deldict[i],insdict[i],new_alleles[i])\n # sl(0.2)\n\n has_muts = []\n\n inss = 0\n dels = 0\n snps = 0\n bothinsdel = 0\n\n for locus in all_muts:\n if len(snp_dict[locus])==0 and len(deldict[locus])>0:\n dels+=1\n if len(snp_dict[locus])==0 and (len(deldict[locus])>0 or len(insdict[locus])>0):\n bothinsdel+=1\n if len(snp_dict[locus])==0 and len(insdict[locus])>0:\n inss+=1\n if len(snp_dict[locus])>0:\n snps+=1\n if len(snp_dict[locus])>0 or len(deldict[locus]) > 0 or len(insdict[locus]) > 0:\n has_muts.append(locus)\n print(\"\\n\",locus)\n print(all_muts[locus])\n print(snp_dict[locus])\n print(deldict[locus])\n print(insdict[locus])\n # print(new_alleles[locus])\n\n muts_only = has_muts\n unscorable = []\n split_over_contigs = []\n multiple_hits_mixed_orientation = []\n possible_mid_locus_insertion = []\n split_over_contigs_with_muts = []\n n_loci = {}\n nloci_ls = []\n no_hits = []\n unaccounted = schemelist\n # print(\"exact match\")\n # for locus in complete_loci:\n # print(locus,complete_loci[locus])\n\n print(\"Non-exact match no Ns\")\n\n for locus in has_muts:\n print(locus,\"new pos allele\")\n if locus in new_alleles:\n print(new_alleles[locus])\n\n print(\"non-exact match with Ns\")\n for locus in remaining_loci:\n ## return query loci with N positions restored (large regions or regions at loci ends will be missing from hsps)\n out1,out2 = reconstruct_n_interupted_loci(locus,partial_hsps[locus],query_genome,allele_sizes[locus + \"-1\"],0.50,wordsize,sec_results)\n n_loci[locus] = out1\n print(locus,out1,out2)\n if out1 == \"other_investigate\":\n print(out2)\n if out1 == \"unscorable\":\n unscorable.append(locus)\n unaccounted.remove(locus)\n if locus in has_muts:\n muts_only.remove(locus)\n elif out1 == \"split over contigs\":\n if locus not in has_muts:\n split_over_contigs.append(locus)\n unaccounted.remove(locus)\n else:\n split_over_contigs_with_muts.append(locus)\n muts_only.remove(locus)\n unaccounted.remove(locus)\n elif out1 == \"mixed_orientation\":\n multiple_hits_mixed_orientation.append(locus)\n unaccounted.remove(locus)\n elif out1 == \"possible_insertion\":\n possible_mid_locus_insertion.append(locus)\n unaccounted.remove(locus)\n elif out1 == \"\":\n no_hits.append(locus)\n unaccounted.remove(locus)\n elif out1 == \"new neg allele\":\n # print(locus,out1)\n nloci_ls.append(locus)\n unaccounted.remove(locus)\n elif out1 == \"nohits\":\n continue\n\n for i in muts_only:\n unaccounted.remove(i)\n\n ###TODO need to get categories properly organised so that totals add up - probably overlap of alleles with mutations and alleles with N regions\n # print(\"Perfect_hits: \",len(complete_loci.keys()))\n # print(\"intact with mutations: \",len(muts_only),\"\\n\",\"\\n\".join(muts_only))\n # print(\"reconstructed 'N' containing:\",len(nloci_ls),\"\\n\",\"\\n\".join(nloci_ls))\n # print(\"hit split over different contigs:\", len(split_over_contigs),\"\\n\",\"\\n\".join(split_over_contigs))\n # print(\"hit split over different contigs with muts: \\n\", len(split_over_contigs_with_muts),\"\\n\", \"\\n\".join(split_over_contigs_with_muts))\n # print(\"mixed orientation:\",len(multiple_hits_mixed_orientation),\"\\n\",\"\\n\".join(multiple_hits_mixed_orientation))\n # print(\"possible mid locus insertion:\", len(possible_mid_locus_insertion),\"\\n\",\"\\n\".join(possible_mid_locus_insertion))\n # print(\"unscorable:\",len(unscorable),\"\\n\".join(unscorable))\n # print(\"loci with no hits in query:\", len(no_hits),\"\\n\",\"\\n\".join(no_hits))\n # print(\"loci remaining:\", len(unaccounted),\"\\n\",\"\\n\".join(unaccounted))\n\n\n # print(unscorable)\n # print(split_over_contigs)\n\n # print(\"\\n\")\n # print(locus)\n # print(\"ref allele length:\", allele_sizes[locus + \"-1\"])\n # for tup in partial_hsps[locus]:\n # hsp = tup[0]\n # queryid = tup[1]\n # print(\"\\n\")\n # # print('allele length:', allele_sizes[alignment.hit_def])\n # print('alignment length:', hsp.align_length)\n # print('identities:', hsp.identities)\n # print('gaps:', hsp.gaps)\n # print('query contig', queryid)\n # print('query start', hsp.query_start)\n # print('query end: ', hsp.query_end)\n # print('subject start', hsp.sbjct_start)\n # print('subject end: ', hsp.sbjct_end)\n # print(hsp.query)\n # print(hsp.match)\n # print(hsp.sbjct)\n\n\n\n #\n # print(\"loci with snps: \",snps)\n # print(\"loci with deletions no snps: \",dels)\n # print(\"loci with insertions no snps:\",inss)\n # print(\"loci with insertions or deletions, no snps:\",bothinsdel)\n # print(\"Remaining with 1 or less intact hits:\",remaining_loci)\n # print(\"Remaining with multiple intact hits:\",mult_hits)\n\n # print(\"query_hit\\tallele\\tfull allele length\\talignment length\\tn_corr_ident\\tgaps\")\n # for locus in sec_results:\n # if locus == \"STMMW_25991\":\n # print(locus)\n # for result in sec_results[locus]:\n # for alignment in result.alignments:\n # alignment_locus = alignment.hit_def.rsplit(\"-\")[0]\n # for hsp in alignment.hsps:\n # if hsp.align_length >= allele_sizes[\"STMMW_25991-1\"]:\n # ncor_ident = return_n_ignored_hit_identities(hsp)\n # # if hsp.align_length == ncor_ident:\n # outp = [result.query,alignment.hit_def,allele_sizes[\"STMMW_25991-1\"],hsp.align_length,ncor_ident,hsp.gaps]\n # outp = map(str,outp)\n # print(\"\\t\".join(outp))\n # # print(\"\\n\\n\")\n # # print(alignment.hit_def)\n # # print('alignment length:', hsp.align_length)\n # # print('identities:', hsp.identities)\n # # print('n_corr identities',ncor_ident)\n # # print('gaps:', hsp.gaps)\n # # print('query contig', result.query)\n # # print('query start', hsp.query_start)\n # # print('query end: ', hsp.query_end)\n # # print('subject start', hsp.sbjct_start)\n # # print('subject end: ', hsp.sbjct_end)\n # print(hsp.query)\n # print(hsp.match)\n # print(hsp.sbjct)\n\n '''\n blast hits structure: \n list of results\n \n result attributes: >>>'alignments'<<<, 'application', 'blast_cutoff', 'database', 'database_length', 'database_letters', 'database_name', 'database_sequences', 'date', 'descriptions', 'dropoff_1st_pass', 'effective_database_length', 'effective_hsp_length', 'effective_query_length', 'effective_search_space', 'effective_search_space_used', 'expect', 'filter', 'frameshift', 'gap_penalties', 'gap_trigger', 'gap_x_dropoff', 'gap_x_dropoff_final', 'gapped', 'hsps_gapped', 'hsps_no_gap', 'hsps_prelim_gapped', 'hsps_prelim_gapped_attemped', 'ka_params', 'ka_params_gap', 'matrix', 'multiple_alignment', 'num_good_extends', 'num_hits', 'num_letters_in_database', 'num_seqs_better_e', 'num_sequences', 'num_sequences_in_database', 'posted_date', 'query', 'query_id', 'query_length', 'query_letters', 'reference', 'sc_match', 'sc_mismatch', 'threshold', 'version', 'window_size']\n alignment attributes: 'accession', 'hit_def', 'hit_id', >>>'hsps'<<<, 'length', 'title']\n hsp attributes: 'align_length', 'bits', 'expect', 'frame', 'gaps', 'identities', 'match', 'num_alignments', 'positives', 'query', 'query_end', 'query_start', 'sbjct', 'sbjct_end', 'sbjct_start', 'score', 'strand'\n \n '''\n\n\n # print(\",\".join(partial_hit))\n # shutil.rmtree('tmp')\n\n\n print((\"--- %s seconds ---\" % (time.time() - start_time)))\n\n\n\n\n\n# run_blast()\n#20 ~6s\n#30 ~10s\n#100 ~30s\n\n\n# main(\"/Users/michaelpayne/Documents/UNSW/Salmonella/new_typing_scheme/scheme_development/betas/cgMLST_b4/hierMLST_stm_loci_accession_lists\",\n# \"/Users/michaelpayne/Documents/UNSW/Salmonella/new_typing_scheme/allele_scheme_dev/blast_testing/hierMLST_stm_alleles\",\n# \"/Users/michaelpayne/Documents/UNSW/Salmonella/new_typing_scheme/allele_scheme_dev/dev_genomes/SRR2532791_nullarbor_megahit.fa\",\n# \"/Users/michaelpayne/Documents/UNSW/Salmonella/new_typing_scheme/allele_scheme_dev/blast_testing/hierMLST_stm_allele_locations.txt\",sys.argv[1],12)\n\n\n# main(\"/Users/michaelpayne/Documents/UNSW/Salmonella/new_typing_scheme/scheme_development/betas/cgMLST_b4/hierMLST_stm_loci_accession_lists\",\n# \"/Users/michaelpayne/Documents/UNSW/Salmonella/new_typing_scheme/scheme_development/betas/cgMLST_b4/hierMLST_stm_alleles\",\n# \"/Users/michaelpayne/Documents/UNSW/Salmonella/new_typing_scheme/allele_scheme_dev/dev_genomes/SRR2532791_skesa_assembly.fasta\",\n# \"/Users/michaelpayne/Documents/UNSW/Salmonella/new_typing_scheme/allele_scheme_dev/blast_testing/hierMLST_stm_allele_locations.txt\",sys.argv[1],12)\n\n# main(\"/Users/michaelpayne/Documents/UNSW/Salmonella/new_typing_scheme/scheme_development/betas/cgMLST_b4/hierMLST_stm_loci_accession_lists\",\n# \"/Users/michaelpayne/Documents/UNSW/Salmonella/new_typing_scheme/scheme_development/betas/cgMLST_b4/hierMLST_stm_alleles\",\n# \"/Users/michaelpayne/Documents/UNSW/Salmonella/new_typing_scheme/allele_scheme_dev/dev_genomes/SRR2532791.fasta\",'100')\n\n# main(\"/Users/michaelpayne/Documents/UNSW/Salmonella/new_typing_scheme/scheme_development/betas/cgMLST_b4/hierMLST_stm_loci_accession_lists\",\n# \"/Users/michaelpayne/Documents/UNSW/Salmonella/new_typing_scheme/scheme_development/betas/cgMLST_b4/hierMLST_stm_alleles\",\n# \"/Users/michaelpayne/Documents/UNSW/Salmonella/new_typing_scheme/allele_scheme_dev/dev_genomes/SRR2532791_snpfilt_masked_contigs.fasta\",\n# \"/Users/michaelpayne/Documents/UNSW/Salmonella/new_typing_scheme/allele_scheme_dev/blast_testing/hierMLST_stm_allele_locations.txt\",sys.argv[1],12)\n\nmain(\"/Users/michaelpayne/Documents/UNSW/Salmonella/new_typing_scheme/scheme_development/betas/cgMLST_b4/hierMLST_stm_loci_accession_lists\",\n\"/Users/michaelpayne/Documents/UNSW/Salmonella/new_typing_scheme/scheme_development/betas/cgMLST_b4/hierMLST_stm_alleles\",\n\"/Users/michaelpayne/Documents/UNSW/Salmonella/new_typing_scheme/allele_scheme_dev/dev_genomes/SRR2532791_nullarbor_megahit.fa\",\n\"/Users/michaelpayne/Documents/UNSW/Salmonella/new_typing_scheme/allele_scheme_dev/blast_testing/hierMLST_stm_allele_locations.txt\",sys.argv[1],12)\n\n# main(\n# \"/Users/michaelpayne/Documents/UNSW/Salmonella/new_typing_scheme/scheme_development/betas/cgMLST_b4/hierMLST_stm_loci_accession_lists\",\n# \"/Users/michaelpayne/Documents/UNSW/Salmonella/new_typing_scheme/allele_scheme_dev/blast_testing/hierMLST_stm_alleles\",\n# \"/Users/michaelpayne/Documents/UNSW/Salmonella/new_typing_scheme/allele_scheme_dev/dev_genomes/SRR2532791_snpfilt_scaffolds.fasta\",\n# '560')\n\n\n\n\n# if __name__ == \"__main__\":\n# main(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4])","sub_path":"allele_MLST_caller/allele_caller_v0.2.py","file_name":"allele_caller_v0.2.py","file_ext":"py","file_size_in_byte":43670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"458569978","text":"#encoding=gbk\n\nimport decimal\n\nfrom cj.orm import *\nfrom cj.web import modal,js,app\nfrom cj.utils import get_config\nfrom cj.utils import date2str\nfrom cj.utils.common import log\n\nfrom datetime import datetime\n\napp_config = get_config()\n\ndef is_work_day(day_str):\n sqlconn = dbconn(app_config.dbconn.pjtz)\n day_str = day_str.replace('-','')\n day_dt = datetime.strptime(day_str,'%Y%m%d')\n tmp_day = sqlconn.get(\"select * from holiday where start_date<='%s' and end_date>='%s'\" % (day_str,day_str))\n sqlconn.close()\n if(tmp_day):\n if(tmp_day.flag==0):\n return False\n else:\n if(day_dt.weekday()>=5):\n return False\n return True\n\ndef get_add_days(day_str, bill_kind, is_same_city):\n days = 0\n sqlconn = dbconn(app_config.dbconn.pjtz)\n day_str = day_str.replace('-','')\n day_dt = datetime.strptime(day_str,'%Y%m%d')\n tmp_day = sqlconn.get(\"select * from holiday where start_date<='%s' and end_date>='%s'\" % (day_str,day_str))\n sqlconn.close()\n if(tmp_day):\n if(tmp_day.flag==0):\n end_date = datetime.strptime(tmp_day['end_date'],'%Y%m%d')\n days = (end_date-day_dt).days + 1\n else:\n if(day_dt.weekday()==5):\n days = 2\n elif(day_dt.weekday()==6):\n days = 1\n if(int(bill_kind) not in (1,3) and int(is_same_city)==0):\n days += 3\n return days\n\ndef is_dup_key(bill_no):\n ret = False\n sqlconn = dbconn(app_config.dbconn.pjtz)\n if(sqlconn.get(\"select * from pj_discount where bill_no='%s'\" % bill_no)):\n ret = True\n sqlconn.close()\n return ret\n\ndef get_buy_rate(day_str, days):\n \"\"\"直线内插法计算收购利率\"\"\"\n rate = -1\n sqlconn = dbconn(app_config.dbconn.pjtz)\n l_day = sqlconn.get(\"select top 1 period_rate,period_day from pj_period where trading_day='%s' and period_day<=%d and period_stat=1 order by period_day desc\" % (day_str,days))\n h_day = sqlconn.get(\"select top 1 period_rate,period_day from pj_period where trading_day='%s' and period_day>=%d and period_stat=1 order by period_day\" % (day_str,days))\n if(l_day and h_day):\n if(h_day.period_day==l_day.period_day):\n return decimal.Decimal(str(l_day.period_rate))\n rate = l_day.period_rate + decimal.Decimal(days-l_day.period_day) / decimal.Decimal(h_day.period_day-l_day.period_day) * (h_day.period_rate-l_day.period_rate)\n rate = round(rate, 4)\n if(l_day and not h_day):\n return decimal.Decimal(str(l_day.period_rate))\n if(h_day and not l_day):\n return decimal.Decimal(str(h_day.period_rate))\n return decimal.Decimal(str(rate))\n\ndef get_buy_price(day_str, bill_kind, accept_bank, amount, months):\n \"\"\"获取贴现业务收购价格\"\"\"\n sqlconn = dbconn(app_config.dbconn.pjtz)\n day_str = day_str.replace('-','')\n day_dt = datetime.strptime(day_str,'%Y%m%d')\n bill_kind = int(str(bill_kind))\n if(bill_kind<4):\n price_list = []\n max_day = sqlconn.get(\"select top 1 trading_day from discount_price where bill_kind='%s' and accept_bank='%s' and trading_day<='%s' order by trading_day desc\" % (bill_kind, accept_bank,day_str))\n if(not max_day):\n max_day = sqlconn.get(\"select top 1 trading_day from discount_price where accept_bank='%s' and trading_day<='%s' order by trading_day desc\" % (accept_bank,day_str))\n if(not max_day):\n return 0\n price_list = sqlconn.select(\"select * from discount_price where accept_bank='%s' and trading_day='%s'\" % (accept_bank, max_day.trading_day))\n else:\n price_list = sqlconn.select(\"select * from discount_price where bill_kind='%s' and accept_bank='%s' and trading_day='%s'\" % (bill_kind, accept_bank, max_day.trading_day))\n sqlconn.close()\n for price in price_list:\n if(eval(str(amount)+price.amount_exp) and eval(str(months)+price.date_exp)):\n return decimal.Decimal(str(price.price))\n else:\n price = sqlconn.get(\"select top 1 price from discount_price where bill_kind='%s' and trading_day<='%s' order by trading_day desc\" % (bill_kind, day_str))\n return decimal.Decimal(str(price.price))\n return 0\n\ndef get_sponsor_prop(contract_no):\n sqlconn = dbconn(app_config.dbconn.pjtz)\n data = sqlconn.get(\"select isnull(sum(prop),0) all_prop from cont_sponsor where contract_no='%s'\" % contract_no)\n sqlconn.close()\n return data.all_prop\n\ndef get_approval_sql(dept_no):\n sql = \"\"\n if(dept_no=='7907'):\n sql += \" and dept_no='%s'\" % dept_no\n elif(dept_no=='1961'):\n sql += \" and dept_no in (%s)\" % get_zh_dept()\n elif(dept_no=='7901'):\n sql += \" and dept_no not in ('7907',%s)\" % get_zh_dept()\n #sql += \" and dept_no not in ('7907',%s) and (((dept_no between '7903' and '7985') and bill_kind in ('0','1') and is_agent<>1) or ((dept_no not between '7903' and '7985') and bill_kind>'3'))\" % get_zh_dept()\n #sql += \" and dept_no not in ('7907',%s) and (((dept_no between '7903' and '7985') and bill_kind<='3' and is_agent<>1) or ((dept_no not between '7903' and '7985') and bill_kind>'3'))\" % get_zh_dept()\n else:\n sql += \" and dept_no not in ('7907',%s) and (((dept_no between '7903' and '7985') and bill_kind in ('0','1') and is_agent=1) or ((dept_no between '7903' and '7985') and bill_kind in ('2','3')) or ((dept_no not between '7903' and '7985') and bill_kind<='3'))\" % get_zh_dept()\n return sql\n\ndef get_zh_dept():\n return \"'1961','1962'\"\n\ndef get_discount_bill_kind():\n return app.get_combo_data('0-银承纸票,1-银承电票,2-商承纸票,3-商承电票,4-理财投资,5-自营投资,99-再贴现')\n\ndef get_discount_accept_bank():\n return app.get_combo_data('0-无,1-国有股份制,2-有授信的其他银行')\n\ndef get_discount_modal():\n field = \"bill_no,dept_no,bill_kind,cust_name,amount,apply_rate,start_day,trading_day,expiring_day,accept_bank,bank_name,is_same_city,is_agent,is_re_discount,rediscount_start,rediscount_end,buy_rate,rediscount_rate,days,profit,add_prop,add_profit,all_profit,rediscount_profit,sponsor,sponsor_profit,remark,status_id\"\n label = \"票号,所属部门,票据种类,贴现客户全称,单张票据金额,申请年利率%,出票日,实际贴现日,票面到期日,承兑行类型,承兑行名称,同城,代理贴现,是否再贴,再贴现起息日,再贴现到期日,收购利率%,再贴利率%,加天,中收,加成比例%,加成利润,合计利润,再贴利润,客户经理,客户经理利润,备注,状态\"\n\n dm = modal.Modal(field, label, \"contract_no\")\n\n dm.bill_no.renderer = app.get_link_render('点击查看数据流程')\n dm.bill_no.cellclick = \"openwin(/flow/flow_log.py)\"\n\n dm.cust_name.xtype = \"textarea\"\n dm.bank_name.xtype = \"textarea\"\n\n before_close = \"\"\"Ext.Ajax.request({ \n url:'pj_pub.py?_method=check_sponsor_prop&item_id=' + contract_no,\n params:{},\n success: function(resp,opts) {\n var resp = Ext.util.JSON.decode(resp.responseText); \n if(resp.success) {store.reload; return true;}\n else {Ext.Msg.alert('TIP', resp.data); return false;}\n },\n failure: function(resp,opts) {\n var resp = Ext.util.JSON.decode(resp.responseText);\n Ext.Msg.alert('TIP', resp.data);\n return false;\n } \n });\"\"\"\n #before_close = \"return false;\"\n\n dm.sponsor.renderer = js.Function('',['value','metadata','record'],\n \"\"\"metadata.attr = 'ext:qtip=\"点击修改主办\"'; \n if(value==null)\n return \"添加\";\n else\n return \"\" + value.replace(/,/g,'
    ') + \"
    \";\"\"\");\n dm.sponsor.cellclick = \"openwin(discount_cont_sponsor.py);;store.reload()\"\n #dm.sponsor.cellclick = {'func':'openwin(cont_sponsor.py)', 'close_action':before_close}\n dm.sponsor.editable = False\n\n dm.dept_no.xtype = \"combo\"\n dm.dept_no.datasource = app.get_combo_data(\"select dept_no,dept_name from adm_dept where dept_no not in ('7900','1960')\", dbconn(app_config.dbconn.admin),'dept_no','dept_name')\n \n #dm.counter_party.value_field = \"party_name\"\n #dm.counter_party.text_field = \"party_name\"\n #dm.counter_party.form_cfg = {'editable':True, 'triggerAction':'all'}\n #dm.counter_party.allow_blank = False\n\n dm.bill_kind.xtype = \"combo\"\n dm.bill_kind.datasource = get_discount_bill_kind()\n dm.bill_kind.allow_blank = False\n\n dm.accept_bank.xtype = \"combo\"\n dm.accept_bank.datasource = get_discount_accept_bank()\n dm.bank_name.allow_blank = False\n\n dm.trading_day.xtype = \"datefield\"\n dm.expiring_day.xtype = \"datefield\"\n dm.start_day.xtype = \"datefield\"\n\n dm.is_same_city.xtype = \"combo\"\n dm.is_same_city.datasource = app.get_combo_data('0-否,1-是')\n dm.is_same_city.allow_blank = False\n\n dm.is_agent.xtype = \"combo\"\n dm.is_agent.datasource = app.get_combo_data('0-否,1-是')\n dm.is_agent.allow_blank = False\n\n dm.is_re_discount.xtype = \"combo\"\n dm.is_re_discount.datasource = app.get_combo_data('0-否,1-是')\n dm.is_re_discount.allow_blank = False\n\n dm.status_id.xtype = \"combo\"\n dm.status_id.datasource = \"select * from flow_status_info\"\n dm.status_id.value_field = \"status_id\"\n dm.status_id.text_field = \"status_name\"\n\n dm.status_id.width = 80\n dm.status_id.editable=False\n\n dm.amount.align = 'right'\n dm.amount.xtype = 'numberFieldFormat'\n dm.amount.renderer = js.format('$')\n dm.amount.allow_blank = False\n\n dm.profit.align = 'right'\n dm.profit.renderer = js.format('$')\n dm.profit.editable = False\n\n dm.add_prop.align = 'right'\n\n dm.add_profit.align = 'right'\n dm.add_profit.renderer = js.format('$')\n dm.add_profit.editable = False\n\n dm.all_profit.align = 'right'\n dm.all_profit.renderer = js.format('$')\n dm.all_profit.editable = False\n\n #dm.trading_day.edit_readonly = True\n dm.trading_day.allow_blank = False\n\n dm.expiring_day.allow_blank = False\n dm.dept_no.allow_blank = False\n\n dm.apply_rate.align = 'right'\n dm.apply_rate.allow_blank = False\n\n dm.buy_rate.align = 'right'\n dm.buy_rate.editable = False\n\n dm.rediscount_start.xtype = \"datefield\"\n dm.rediscount_end.xtype = \"datefield\"\n\n dm.rediscount_start.grid_hidden = True\n dm.rediscount_end.grid_hidden = True\n dm.rediscount_start.editable = False\n dm.rediscount_end.editable = False\n dm.rediscount_rate.grid_hidden = True\n dm.rediscount_profit.grid_hidden = True\n dm.rediscount_rate.editable = False\n dm.rediscount_profit.editable = False\n\n dm.sponsor_profit.grid_hidden = True\n\n dm.rediscount_profit.align = 'right'\n dm.rediscount_profit.renderer = js.format('$')\n\n dm.days.align = 'right'\n dm.days.editable = False\n\n return dm\n\ndef discount_check(data):\n if(data['start_day']>data['expiring_day'] or data['expiring_day']data['trading_day']):\n return {'success':False,'data':'日期要求票面到期日>=实际贴现日>=出票日'}\n try:\n a = datetime.strptime(data['trading_day'],'%Y-%m-%d')\n b = datetime.strptime(data['expiring_day'],'%Y-%m-%d')\n except:\n return {'success':False,'data':'日期格式不正确'}\n \n if(not is_work_day(data['trading_day'])):\n return {'success':False,'data':'交易日不能是节假日'}\n\n if(data['is_agent']==None):\n return {'success':False,'data':'必须选择是否代理'}\n\n days = get_add_days(data['expiring_day'], data['bill_kind'], data['is_same_city'])\n data['days'] = days\n\n amount = data['amount']\n apply_rate = data['apply_rate']\n buy_rate = data['buy_rate']\n #add_prop = data['add_prop']\n\n if(isinstance(amount, unicode)):\n amount = amount.encode('gbk')\n if(isinstance(apply_rate, unicode)):\n apply_rate = apply_rate.encode('gbk')\n if(isinstance(buy_rate, unicode)):\n buy_rate = buy_rate.encode('gbk')\n #if(isinstance(add_prop, unicode)):\n # add_prop = add_prop.encode('gbk')\n\n if(isinstance(amount, str)):\n amount = decimal.Decimal(amount.replace(\",\",\"\"))\n if(isinstance(apply_rate, str)):\n apply_rate = decimal.Decimal(apply_rate)\n if(isinstance(buy_rate, str)):\n buy_rate = decimal.Decimal(buy_rate)\n #if(isinstance(add_prop, str)):\n # add_prop = decimal.Decimal(add_prop)\n\n if(not data['manual']):\n buy_rate = get_buy_price(data['trading_day'], data['bill_kind'], data['accept_bank'], amount, (b-a).days)\n data['buy_rate'] = buy_rate\n\n if(buy_rate>0):\n #log.info((b-a).days)\n #log.info(days)\n #log.info(apply_rate)\n #log.info(buy_rate)\n #log.info(amount)\n data['profit'] = ((b-a).days + days) * (apply_rate - buy_rate) * amount / 360 /100\n else:\n data['profit'] = 0\n #\n return 0\n\ndef send_mail(to, subject, content):\n return\n if(isinstance(to, int)):\n sqlconn = dbconn(app_config.dbconn.admin)\n sql = \"select * from adm_user_role where role_id=%d\" % to\n role_users = sqlconn.select(sql, \"role_id,user_login\")\n sqlconn.close()\n\n user_ids = []\n for role_user in role_users:\n user_ids.append(role_user.user_login+\"@spdb.com.cn\")\n to = \";\".join(user_ids)\n\n from cj.utils import mail\n m = mail.Mail()\n m.send_mail(to, subject, content)\n #m.send_mail(\"caij-szn@spdb.com.cn\", subject, content + \"
    \" + to)\n\ndef get_zg_modal():\n field = \"contract_no,counter_party,keep_expire,bill_kind,amount,actually_paid,interest,trading_day,expiring_day,days,start_day,deadline_day,bill_count,project_rate,collocation_rate,external_rate,tg_amount,gl_amount,deal_rate,cost_rate,rate_spreads,profit,fund_source,bill_from,double_sell,forward_bank,dbsell_interest,sponsor,approval_no,custodian_bank,keep_interest,collocation_earnings,remark,status_id\"\n label = \"合同号,交易对手,种类,业务类型,票面金额,实付金额,后收息利息,交易日,到期日,天数,票面起始日,票面截止日,张数,项目利率(%),托管费率(%),外部利率(%),托管费,管理费,资金利率(%),成本利率(%),业务利差(%),业务利润,资金来源,票源行,是否双卖,远期买断行,远期双卖利息,主办,批复号,标的保管行,留存利息,托管户收益,备注,状态\"\n\n dm = modal.Modal(field, label, \"contract_no\")\n\n dm.contract_no.width=150\n dm.keep_expire.width=60\n\n dm.sponsor.renderer = js.Function('',['value','metadata','record'],\n \"\"\"metadata.attr = 'ext:qtip=\"点击修改主办\"'; \n if(value==null)\n return \"添加\";\n else\n return \"\" + value.replace(/,/g,'
    ') + \"
    \";\"\"\");\n dm.sponsor.cellclick = \"openwin(cont_sponsor.py);;store.reload()\"\n #dm.sponsor.cellclick = {'func':'openwin(cont_sponsor.py)', 'close_action':before_close}\n dm.sponsor.editable = False\n\n dm.counter_party.xtype = \"combo\"\n dm.counter_party.datasource = \"select party_name from pj_counter_party\"\n dm.counter_party.value_field = \"party_name\"\n dm.counter_party.text_field = \"party_name\"\n dm.counter_party.form_cfg = {'editable':True, 'triggerAction':'all'}\n dm.counter_party.allow_blank = False\n\n dm.custodian_bank.xtype = \"combo\"\n dm.custodian_bank.datasource = \"select party_name from pj_counter_party\"\n dm.custodian_bank.value_field = \"party_name\"\n dm.custodian_bank.text_field = \"party_name\"\n dm.custodian_bank.form_cfg = {'editable':True, 'triggerAction':'all'}\n\n dm.forward_bank.xtype = \"combo\"\n dm.forward_bank.datasource = \"select party_name from pj_counter_party\"\n dm.forward_bank.value_field = \"party_name\"\n dm.forward_bank.text_field = \"party_name\"\n dm.forward_bank.form_cfg = {'editable':True, 'triggerAction':'all'}\n\n dm.contract_no.add_hidden = True\n dm.contract_no.readonly = True\n #dm.contract_no.editable = False\n\n dm.days.editable = False\n dm.profit.editable = False\n dm.rate_spreads.editable = False\n dm.interest.editable = False\n dm.project_rate.editable = False\n dm.keep_interest.editable = False\n dm.cost_rate.editable = False\n dm.tg_amount.editable = False\n dm.gl_amount.editable = False\n\n dm.collocation_rate.grid_hidden = True\n dm.external_rate.grid_hidden = True\n\n dm.bill_kind.xtype = \"combo\"\n dm.bill_kind.datasource = app.get_combo_data('纸质银承,纸质商承,电子银承,电子商承,福费廷,其他')\n\n \n dm.keep_expire.xtype = \"combo\"\n dm.keep_expire.datasource = app.get_combo_data('1-1,2-2')\n dm.keep_expire.default=1\n\n dm.keep_expire.form_cfg.listeners = \"\"\"@{select:function(comb){\n if(comb.value=='1'){\n Ext.getCmp(\"id_collocation_earnings\").getEl().dom.disabled = true;\n }\n else{\n Ext.MessageBox.alert('提示','种类2必须输入托管户收益');\n Ext.getCmp(\"id_collocation_earnings\").getEl().dom.disabled = false;\n }\n }}\"\"\"\n\n dm.collocation_earnings.default = 0\n\n dm.double_sell.xtype = \"combo\"\n dm.double_sell.datasource = app.get_combo_data('0-否,1-是')\n\n dm.double_sell.form_cfg.listeners = \"\"\"@{select:function(comb){\n if(comb.value=='1'){\n Ext.MessageBox.alert('提示','双卖必须输入远期买断行和远期双买利息');\n Ext.getCmp(\"id_dbsell_interest\").getEl().dom.disabled = false;\n\t\t\tExt.getCmp(\"id_forward_bank\").getEl().dom.disabled = false;\n }\n\t\telse\n\t\t{\n\t\t\tExt.getCmp(\"id_dbsell_interest\").getEl().dom.disabled = true;\n\t\t\tExt.getCmp(\"id_forward_bank\").getEl().dom.disabled = true;\n\t\t}\n }}\"\"\"\n\n dm.double_sell.default=0\n dm.dbsell_interest.default = 0\n #dm.dbsell_interest.form_cfg = {\"disabled\":True}\n\n dm.trading_day.xtype = \"datefield\"\n dm.expiring_day.xtype = \"datefield\"\n dm.start_day.xtype = \"datefield\"\n dm.deadline_day.xtype = \"datefield\"\n #dm.remark.xtype = \"textarea\"\n\n dm.start_day.grid_hidden = True\n dm.deadline_day.grid_hidden = True\n dm.bill_from.grid_hidden = True\n dm.approval_no.grid_hidden = True\n dm.custodian_bank.grid_hidden = True\n dm.forward_bank.grid_hidden = True\n dm.bill_count.grid_hidden = True\n\n dm.approval_no.default=\"PIAO\"\n dm.approval_no.form_cfg.minLength = 18\n dm.approval_no.form_cfg.maxLength = 18\n\n dm.status_id.xtype = \"combo\"\n dm.status_id.datasource = \"select * from flow_status_info\"\n dm.status_id.value_field = \"status_id\"\n dm.status_id.text_field = \"status_name\"\n\n dm.status_id.width = 40\n dm.status_id.editable=False\n\n dm.fund_source.xtype = \"combo\"\n dm.fund_source.datasource = app.get_combo_data('0-总行自营资金,1-总行理财资金,3-票据业务部,99-其他')\n dm.fund_source.form_cfg = {'editable':True, 'triggerAction':'all'}\n dm.fund_source.allow_blank = False\n\n dm.bill_count.align = 'right'\n dm.days.align='right'\n dm.amount.align = 'right'\n dm.project_rate.align = 'right'\n dm.deal_rate.align = 'right'\n dm.cost_rate.align='right'\n dm.rate_spreads.align='right'\n dm.profit.align = 'right'\n dm.dbsell_interest.align = 'right'\n dm.keep_interest.align = 'right'\n dm.collocation_earnings.align = 'right'\n\n dm.bill_count.vtype = 'int'\n #dm.amount.vtype = 'money'\n #dm.deal_rate.vtype = 'decimal'\n #dm.cost_rate.vtype = 'decimal'\n dm.amount.xtype = 'numberFieldFormat'\n dm.actually_paid.xtype = 'numberFieldFormat'\n\n dm.amount.renderer = js.format('$')\n dm.profit.renderer = js.format('$')\n dm.actually_paid.renderer = js.format('$')\n dm.interest.renderer = js.format('$')\n dm.tg_amount.renderer = js.format('$')\n dm.gl_amount.renderer = js.format('$')\n dm.dbsell_interest.renderer = js.format('$')\n dm.keep_interest.renderer = js.format('$')\n dm.collocation_earnings.renderer = js.format('$')\n\n dm.trading_day.edit_readonly = True\n dm.trading_day.allow_blank = False\n dm.expiring_day.allow_blank = False\n dm.counter_party.allow_blank = False\n dm.amount.allow_blank = False\n\n dm.bill_from.allow_blank = False\n dm.approval_no.allow_blank = False\n dm.bill_count.allow_blank = False\n\n dm.deal_rate.allow_blank = False\n dm.cost_rate.allow_blank = False\n\n return dm","sub_path":"pjtz/pub.py","file_name":"pub.py","file_ext":"py","file_size_in_byte":20344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"167652848","text":"# YouTube解説\nMOD = 1000000007\nn, k = [int(x) for x in input().split()]\nd = [0] * (k + 1)\n\nfor i in range(1, k + 1):\n d[i] = pow(k // i, n, MOD)\n\nfor i in range(k, 0, -1): # 大きいほうから\n for j in range(i * 2, k + 1, i): # iの倍数\n # d[6] = d'[6] - d[12] - d[18] ...\n d[i] -= d[j]\n d[i] %= MOD\nans = 0\nfor i, item in enumerate(d):\n ans += i * item\n ans %= MOD\nprint(ans)\n","sub_path":"Python_codes/p02715/s278791337.py","file_name":"s278791337.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"353511925","text":"# PLease Increase Brightness To MAX Level.\n\nimport glfw\nfrom OpenGL.GL import *\nimport math\nimport lookAt\nimport Perspective_projection\nimport Arithmetic\nfrom Vector3 import Vector3 as v3\nimport Vector3\n\nfrom shader import Shader\nfrom loaded_object import LoadedObject\nfrom light import DirLight, PointLight, SpotLight\n\n\nclass Window:\n def __init__(self, width: int, height: int, title: str):\n # Initialize window\n if not glfw.init():\n raise Exception(\"GLFW cannot be initialized!\")\n\n self._width, self._height = width, height\n self._window = glfw.create_window(width, height, 'AirBUS A380 Modeling', None, None)\n\n if not self._window:\n glfw.terminate()\n raise Exception(\"Window cannot be created!\")\n\n # Set resize handler\n glfw.set_window_size_callback(self._window, self._on_resize)\n # Set keyboard input handler\n glfw.set_key_callback(self._window, self._on_key_input)\n # Set window as current context\n glfw.make_context_current(self._window)\n\n # Set options\n glEnable(GL_DEPTH_TEST) #Enable Depth Buffer\n\t # glDepthFunc(GL_LESS)\n glEnable(GL_BLEND) #Colour\n\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)\n self._background_color_night = v3([0.0, 0.05, 0.1])\n self._background_color_day = v3([0.6, 0.7, 0.75])\n\n # Camera\n self.sel_camera: str = \"static\" # Selected camera mode\n self.update_camera: bool = True\n self._static_target: v3 = v3([0, 2.0, 0]) #Making camera look slightly up to the sky form the centre of the plane\n self._default_eye: v3 = v3([0, 8, 10]) #Default camera position, Camera is always looking along Z-axis ; called eye space\n\n # Matrices\n self._fov, self._near, self._far = None, None, None\n self._eye, self._target, self._up = None, None, None\n self.projection_matrix, self.view_matrix = None, None\n self._prepare_matrices()\n\n\n # Shaders\n self.shaders = {\n \"phong\": Shader(\"shaders/phong_vs.glsl\", \"shaders/phong_fs.glsl\"),\n \"light_source\": Shader(\"shaders/light_source_vs.glsl\", \"shaders/light_source_fs.glsl\"),\n }\n self.current_shader: Shader = None\n self._use_shader(self.shaders[\"phong\"])\n\n #Sensitivity WASD\n self.xTrans, self.yTrans, self.zTrans = 0,0,0\n\n # Scene\n self.scene = {\n \"Runway\": LoadedObject(\"data/floor.obj\", 0, 0, 0, 2.0), #position and scaling\n \"Center_Plane\": LoadedObject(\"data/A380.obj\", 0, 2.1, 0, scale=2),\n \"Moving_Plane\": LoadedObject(\"data/A380.obj\"),\n }\n\n # Lighting\n self._point_light_obj = LoadedObject(\"data/uv_sphere.obj\") # sphere to represent point light sources\n\n self.sun_moon = DirLight(amb=v3([0.05, 0.05, 0.05]), dif=v3([0.4, 0.4, 0.8]), spe=v3([0.4, 0.4, 0.8]),\n direction=v3([-0.2, -1.0, -0.3]), uni_name=\"dirLight\")\n point_lights = [\n #width, height, front\n (v3([10.0, 5.0, -8.0]), v3([1.0, 1.0, 1.0])), # white\n (v3([0.0, 0.2, 0.0]), v3([0.3, 0.3, 1.0])), #blue\n (v3([-10.0, 5.0, -8.0]), v3([1.0, 1.0, 0.3])), #yellow\n (v3([0.0, 5.0, 0.0]), v3([1.0, 0.3, 0.3])) # red\n ]\n self.point_lights = list(self._pl_gen(point_lights))\n\n self.spot_light_offset = v3([-1.0, 0.0, 0.0]) # Relative offset from moving plane\n self.spot_light_def_dir = v3([0.0, 0.0, 0.0]) # Default direction (same as moving plane)\n self.spot_light_angle_offset_x = 0 \n self.spot_light_angle_offset_y = 0\n self.spot_light = SpotLight(amb=v3([0.0, 0.0, 0.0]), dif=v3([0.0, 1.0, 0.5]), spe=v3([0.0, 1.0, 0.5]),\n k=v3([1.0, 0.07, 0.017]), pos=v3([0.0]*3), direction=self.spot_light_def_dir, #position is marked at headlight\n co=math.cos(math.radians(22.5)), oco=math.cos(math.radians(25.0)),\n uni_name=\"spotLight\", lss=self.shaders[\"light_source\"], obj=None)\n\n def _pl_gen(self, positions):\n \"\"\"Point lights generator.\"\"\"\n for i, (p, c) in enumerate(positions):\n light = PointLight(amb=0.05 * c, dif=1.0 * c, spe=1.0 * c,\n k=v3([1.0, 0.07, 0.017]), pos=p,\n uni_name=f\"pointLights[{i}]\", lss=self.shaders[\"light_source\"],\n obj=self._point_light_obj)\n yield light\n\n\n def _use_shader(self, shader: Shader) -> None:\n self.current_shader = shader\n self.current_shader.use()\n # Update matrices after changing shader\n self._update_projection()\n self._update_view()\n\n #Camera\n def _prepare_matrices(self) -> None:\n # Projection matrix\n self._fov = 45\n self._near = 0.1\n self._far = 100\n # View matrix\n self._eye: v3 = self._default_eye\n self._target: v3 = self._static_target\n self._up: v3 = v3([0, 1, 0])\n\n def _update_view(self) -> None:\n \"\"\"Recalculate view matrix and upload it to shader.\"\"\"\n self.view_matrix = lookAt.create_look_at(self._eye, self._target, self._up) \n self.current_shader.set_view(self.view_matrix) #Uploading to Shader \n\n def _update_projection(self) -> None:\n \"\"\"Recalculate projection matrix and upload it to shader.\"\"\"\n a = self._width / self._height\n self.projection_matrix = Perspective_projection.create_perspective_projection(self._fov, a, self._near, self._far)\n self.current_shader.set_projection(self.projection_matrix) #Uploading to Shader\n\n def _on_resize(self, _window, width, height) -> None:\n self._width, self._height = width, height\n glViewport(0, 0, self._width, self._height)\n self._update_projection()\n\n def _on_key_input(self, _window, key, _scancode, action, _mode) -> None:\n left_right = {glfw.KEY_LEFT: -0.03, glfw.KEY_RIGHT: 0.03}\n if key in left_right and action != glfw.RELEASE:\n self.spot_light_angle_offset_x += left_right[key]\n return\n \n up_down = {glfw.KEY_DOWN: 0.03, glfw.KEY_UP: -0.03}\n if key in up_down and action != glfw.RELEASE:\n self.spot_light_angle_offset_y += up_down[key]\n if(self.spot_light_angle_offset_y <= 1.0 and self.spot_light_angle_offset_y >= -0.2):\n self.spot_light_angle_offset_y += up_down[key]\n print(self.spot_light_angle_offset_y)\n else:\n if self.spot_light_angle_offset_y > 1.0:\n self.spot_light_angle_offset_y = 1.0\n elif self.spot_light_angle_offset_y < -0.2:\n self.spot_light_angle_offset_y = -0.2\n return\n\n if key is glfw.KEY_S and action != glfw.RELEASE:\n self.xTrans -= 0.05\n return\n elif key is glfw.KEY_W and action != glfw.RELEASE:\n self.xTrans += 0.05\n return\n elif key is glfw.KEY_Q and action != glfw.RELEASE:\n self.yTrans -= 0.05\n return\n elif key is glfw.KEY_E and action != glfw.RELEASE:\n self.yTrans += 0.05\n return\n elif key is glfw.KEY_D and action != glfw.RELEASE:\n self.zTrans -= 0.05\n return\n elif key is glfw.KEY_A and action != glfw.RELEASE:\n self.zTrans += 0.05\n return\n \n if action != glfw.PRESS:\n return\n cam = {glfw.KEY_1: \"static\", glfw.KEY_2: \"following\", glfw.KEY_3: \"moving\"}\n if key in cam:\n self.sel_camera = cam[key]\n self.update_camera = True\n\n def _set_daytime(self):\n blend_factor = (math.sin(glfw.get_time() * 0.1) + 1) / 2\n c = self._background_color_day * (1 - blend_factor) + self._background_color_night * blend_factor\n\n #Changing Intensity of Day Light\n self.sun_moon._diffuse = 0.9 * c\n self.sun_moon._specular = 0.9 * c\n glClearColor(c[0], c[1], c[2], 1) #RGBA\n\n def _move_objects(self) -> None:\n time = glfw.get_time()\n # Move and rotate Center_Plane\n rot_y = Arithmetic.create_from_y_rotation(-0.5 * time)\n translation = Arithmetic.create_from_translation(v3([0, math.sin(time) + 0.23, 0])) #move up_down (in y dir)\n\n model = Arithmetic.multiply(translation, self.scene[\"Center_Plane\"].pos) # up-down movement\n self.scene[\"Center_Plane\"].model = Arithmetic.multiply(rot_y, model) # rotation\n \n # Move and orientate Moving_Plane\n translation = v3([-5 + self.xTrans, 0.2+ self.yTrans, self.zTrans])\n o = self.scene[\"Moving_Plane\"]\n o.set_pos(translation)\n o.model = Arithmetic.multiply(Arithmetic.create_from_y_rotation(-self.spot_light_angle_offset_x - math.pi), o.model)\n o.model = Arithmetic.multiply(Arithmetic.create_from_z_rotation(-self.spot_light_angle_offset_y), o.model)\n\n # Move and orientate spotlight relatively to Moving_Plane\n pos = Arithmetic.multiply(Arithmetic.create_from_translation(self.spot_light_offset), o.model)\n self.spot_light.set_pos(Vector3.from_matrix44_translation(pos))\n light_dir = self._get_cockpit_look_dir() + self.spot_light_def_dir \n self.spot_light.set_dir(light_dir)\n\n def _get_cockpit_look_dir(self):\n angle = math.pi / 2 + self.spot_light_angle_offset_x #translation by math.pi\n return v3([math.sin(angle), 0.0, math.cos(angle)])\n\n def _process_camera(self) -> None:\n if not self.update_camera:\n return\n\n if self.sel_camera == \"static\":\n self._eye = self._default_eye\n self._target = self._static_target\n self.update_camera = False # Static camera needs to be calculated only once.\n elif self.sel_camera == \"following\":\n self._eye = self._default_eye\n self._target = Vector3.from_matrix44_translation(self.scene[\"Moving_Plane\"].model)\n elif self.sel_camera == \"moving\":\n m = Arithmetic.multiply(Arithmetic.create_from_translation(v3([-0.9, 0.0, 0])), self.scene[\"Moving_Plane\"].model) #plane cockpit view\n self._eye = Vector3.from_matrix44_translation(m)\n self._target = self._eye + self._get_cockpit_look_dir() # Front facing camera\n self._update_view()\n\n def _draw_light_sources(self) -> None:\n \"\"\"Draws light sources with appropriate shaders.\"\"\"\n self._use_shader(self.shaders[\"light_source\"])\n for light in self.point_lights:\n light.draw()\n self.spot_light.draw()\n\n def _draw_objects(self) -> None:\n \"\"\"Sets currently selected shader, then draws shaded objects.\"\"\"\n self._use_shader(self.shaders[\"phong\"]) #Select Phong Shader\n self.current_shader.set_v3(\"viewPos\", self._eye)\n\n # Use lights\n self.sun_moon.use_light(self.current_shader)\n for light in self.point_lights:\n light.use_light(self.current_shader)\n self.spot_light.use_light(self.current_shader)\n\n # Draw objects\n for o in self.scene.values():\n o.draw(self.current_shader)\n\n def main_loop(self) -> None:\n while not glfw.window_should_close(self._window):\n glfw.poll_events()\n\t # Clean the Back buffer and Depth buffer\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n\n # Update scene\n self._set_daytime()\n self._move_objects()\n self._process_camera()\n\n # Draw scene\n self._draw_light_sources()\n self._draw_objects()\n\n # Swap buffers\n glfw.swap_buffers(self._window)\n\n\ndef main():\n window = Window(1280, 720, \"AirBus A380 Modeling\")\n window.main_loop()\n glfw.terminate()\n\n\nif __name__ == '__main__':\n main()\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"51708010","text":"from django.conf.urls import patterns, include, url\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'minesweeper.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^$', 'minesweeper.views.home', name='home'),\n url(r'^new/game/$', 'minesweeper.views.new_game', name='new-game'),\n url(r'^uncover/$', 'minesweeper.views.uncover', name='uncover'),\n url(r'^resume/game/$', 'minesweeper.views.resume_game', name='resume-game'),\n)\n","sub_path":"minesweeper/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"386843045","text":"##################################################\n#\t\t\tcreateIndex.py\n#\n# Index a subset of Wikipedia, and write the\n# resulting inverted index to a file. This\n# index can then be queried by queryIndex.py.\n#\n# Arguments\n# arg1 - xml text file containing the original collection\n# arg2 - index file to output\n#\n# Author:\n# David Storch (dstorch)\n# May 2011\n##################################################\n\nimport sys\nimport PorterStemmer\nimport re\nimport math\nimport os\nfrom Weights import WeightHolder\nfrom parseCollection import XMLParser\n\n##################################################\n# GLOBALS\n##################################################\n\nstopWordSet = set()\n\npstemmer = PorterStemmer.PorterStemmer()\n\n# the number of pages in the collection\nN = -1\n\n# the number of words that the bottom sections\n# of characters the bottom sections of the wiki\n# page must exceed in order to not be considered a stub\nminimumStubChars = 1000\n\nweights = WeightHolder()\n\n##################################################\n\n\n##############################################################################################\n########### CONSTRUCTING THE INVERTED INDEX -- HELPER FUNCTIONS ####################\n##############################################################################################\n\ndef tokenize(text) :\n\t\n\t\t#split the terms into a list\n\t\tlistOfTerms = re.split('[^a-z0-9]+', text)\n\t\t\n\t\t# remove first and last list elements if they are ''\n\t\tif len(listOfTerms) > 0 :\n\t\t\tif listOfTerms[0] == '' :\n\t\t\t\tlistOfTerms.pop(0)\n\t\t\t\t\n\t\tif len(listOfTerms) > 0 :\n\t\t\tif listOfTerms[len(listOfTerms) - 1] == '' :\n\t\t\t\tlistOfTerms.pop()\n\t\t\t\n\t\treturn listOfTerms\n\ndef buildIndexDictionary(listOfTerms, bigDict) :\n\t\t\n\t# build the inverted index\n\tindex = 0\n\tfor term in listOfTerms :\n\t\tif term in stopWordSet :\n\t\t\tcontinue\n\t\tterm = PorterStemmer.stemWord(pstemmer, term)\n\t\tif term in bigDict :\n\t\t\tlittleDict = bigDict[term]\n\t\t\tif docID in littleDict :\n\t\t\t\tlittleDict[docID].append(index)\n\t\t\telse :\n\t\t\t\tlittleDict[docID] = [index]\n\t\telse :\n\t\t\tbigDict[term] = dict({docID : [index]})\n\t\tindex += 1\n\t\n\treturn bigDict\n\t\t\ndef computeWeights(bigDict, normalizationDict) :\n\t\n\t# calculate weights\n\tfor term in bigDict :\n\t\tidf = math.log(N / len(bigDict[term].keys()))\n\t\t\n\t\tlittleDict = bigDict[term]\n\t\tfor docID in littleDict :\n\t\t\tnormalizationDict[docID] += len(littleDict[docID])**2\n\t\t\n\t\tidfDict[term] = idf\n\t\n\t# take the square roots to get the final Euclidian normalization factors\n\tfor docID in normalizationDict :\n\t\tnormalizationDict[docID] = math.sqrt(normalizationDict[docID])\n\t\t\n\treturn bigDict, normalizationDict\n\t\ndef writeIndex(indexFile, bigDict, normalizationDict, positionMap) :\n\t\n\t# NOTE: reserve 21 bytes for the length of the dictionary\n\t# (last character is a newline)\n\t\n\t# determine byte-positions, not taking length of header into account\n\tcurrentBytes = 0\n\tfor term in bigDict:\n\t\tpositionMap[term] = currentBytes\n\t\tlittleDict = bigDict[term]\n\t\tcurrentBytes += len(str(idfDict[term]))\n\t\tfor docID in littleDict :\n\t\t\tcurrentBytes += len(\":\" + str(docID))\n\t\t\tfor pos in littleDict[docID] :\n\t\t\t\tcurrentBytes += len(\" \" + str(pos))\n\t\tcurrentBytes += 1\n\t\n\t# determine the length of the header dictionary\n\tdictionaryLength = 0\n\tfor term in positionMap :\n\t\tdictionaryLength += len(term + \" \" + str(positionMap[term]) + \"\\n\")\n\t\t\n\t# determine the length of the normalization dictionary\n\tnormLength = 0\n\tfor docID in normalizationDict :\n\t\tnormLength += len(str(docID) + \" \" + str(normalizationDict[docID]) + \"\\n\")\n\t\n\t# find length of the headers\n\tdictionaryLengthStr = str(dictionaryLength)\n\tnormLengthStr = str(normLength)\n\t\n\t# write dictionary length to the beginning of the file\n\tfor i in range(0, 20 - len(dictionaryLengthStr)) :\n\t\tindexFile.write('0')\n\tindexFile.write(dictionaryLengthStr + \"\\n\")\n\t\n\t# write the length of the normalization info to the beginning\n\tfor i in range(0, 20 - len(normLengthStr)) :\n\t\tindexFile.write('0')\n\tindexFile.write(normLengthStr + \"\\n\")\n\t\n\t# write the dictionary\n\tfor term in positionMap :\n\t\tposition = positionMap[term]\n\t\tindexFile.write(term + \" \" + str(position) + \"\\n\")\n\t\t\n\t# write the normalization info\n\tfor docID in normalizationDict :\n\t\tindexFile.write(str(docID) + \" \" + str(normalizationDict[docID]) + \"\\n\")\n\t\n\t# write the inverted index\n\tfor term in bigDict:\n\t\tlittleDict = bigDict[term]\n\t\tindexFile.write(str(idfDict[term]))\n\t\tfor docID in littleDict :\n\t\t\tindexFile.write(\":\" + str(docID))\n\t\t\tfor pos in littleDict[docID] :\n\t\t\t\tindexFile.write(\" \" + str(pos))\n\t\tindexFile.write(\"\\n\")\n\n\t\t \n##############################################################################################\n##############################################################################################\n##############################################################################################\n\nif __name__ == '__main__' :\n\t\n\t# filehandles\n\tcollection = open(sys.argv[1])\n\tindexFile = open(sys.argv[2], 'w')\n\tstopWords = open(sys.argv[3])\n\ttitleIndex = open(sys.argv[4], 'w')\n\tpzoneFile = open(sys.argv[5], \"w\")\n\t\n\t# create a set of stop words from the stopWords infile\n\t# assuming that there is one word per line\n\tfor line in stopWords:\n\t\tstopWordSet.add(str.strip(line))\n\t\n\t# extract docID, title, and text from the XML\n\txmlparse = XMLParser(collection)\n\tparsedPages = xmlparse.parseCollection()\n\t\n\t# maps from terms to smaller dictionaries\n\tbigDict = dict()\n\tzoneDict = dict()\n\t\n\t# maps from terms to idf\n\tidfDict = dict()\n\tzoneIdf = dict()\n\t\n\t# maps from docID to euclidian normalization factor\n\tnormalizationDict = dict()\n\tzoneNormalization = dict()\n\t\n\t# the number of documents\n\tN = float(len(parsedPages))\n\t\n\t# set up the inverted index\n\tfor p in parsedPages :\n\t\t\n\t\tdocID = p._id\n\t\t\n\t\t# write the title index\n\t\tstub1 = 0\n\t\tstub2 = 0\n\t\tif len(p._pzone) < weights.getMinimumStubChars() :\n\t\t\tstub1 = 1\n\t\tif len(p._text) < weights.getMinimumStubChars() :\n\t\t\tstub2 = 1\n\t\ttitleIndex.write(str(p._id) +\"\\t\"+str(stub1)+\"\\t\"+str(stub2)+\"\\t\"+p._title+\"\\n\")\n\n\t\t# tokenize different zones\n\t\tlistOfTerms = tokenize((p._text).lower())\n\t\tzoneTerms = tokenize((p._pzone).lower())\n\t\t\n\t\t# build the dictionaries\n\t\tbigDict = buildIndexDictionary(listOfTerms, bigDict)\n\t\tzoneDict = buildIndexDictionary(zoneTerms, zoneDict)\n\t\t\n\t\t# initialize all normalization factors to 0\n\t\tnormalizationDict[docID] = 0.0\n\t\tzoneNormalization[docID] = 0.0\n\t\t\n\t# pre-compute information for tf-idf weighting\n\tbigDict, normalizationDict = computeWeights(bigDict, normalizationDict)\n\tzoneDict, zoneNormalization = computeWeights(zoneDict, zoneNormalization)\n\t\n\t# a map from each term to absolute position\n\t# in the file---we want to be able to seek\n\t# to the correct position in the postings list\n\tpositionMap = dict()\n\tzonePosMap = dict()\n\t\n\t# write out the index files\n\twriteIndex(indexFile, bigDict, normalizationDict, positionMap)\n\twriteIndex(pzoneFile, zoneDict, zoneNormalization, zonePosMap)\n\n\t\n","sub_path":"dstorch/cs158/final/handinTest/createIndex.py","file_name":"createIndex.py","file_ext":"py","file_size_in_byte":6918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"229691319","text":"from persoana import Persoana\r\n\r\nclass Elev(Persoana):\r\n\t\r\n def __init__(self, nume, cnp, clasa):\r\n super(Elev, self).__init__(nume,cnp)\r\n self.clasa = clasa\r\n\r\n def __repr__(self):\r\n return \"Elevul {}, este in clasa {}.\".format(self.nume, self.clasa)\r\n\r\nif __name__ == \"__main__\":\r\n e = Elev(\"Stan Cristina\", 6160117232323, \"I A\")\r\n print(e)\r\n","sub_path":"Liceu/elev.py","file_name":"elev.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"76346178","text":"import socket\nimport struct\nimport time \nimport sys\nimport threading\nimport re\nfrom pyquaternion import Quaternion\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nfrom scipy.spatial.transform import Rotation\n\n\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\ns.bind(('', 7755))\nfig = plt.figure(figsize=(10, 10))\nax = Axes3D(fig)\nplt.xlabel(\"X axis\")\nplt.ylabel(\"Y axis\")\nax.set_xlim3d([-1.2, 1.2])\nax.set_ylim3d([-1.2, 1.2])\nax.set_zlim3d([-1.2, 1.2])\n\nquat = Quaternion((0, 0, 0, 1))\ndef get_data():\n global quat\n while(1):\n data, addr = s.recvfrom(1024) # buffer size is 1024 bytes\n a = re.findall(r\"[-+]?\\d*\\.\\d+|\\d+\", data)\n quat = Quaternion((float(a[3]),-float(a[1]),-float(a[2]),float(a[0])))\nx = threading.Thread(target=get_data)\nx.daemon = True\nx.start()\ntime.sleep(0.33)\n\nq_init = 0\nfor i in range(10):\n q_init += quat * 0.1\n\nwhile(1):\n q_delta = q_init.conjugate * quat\n del ax.lines[:]\n x = q_delta* Quaternion((0, 0, 0, 1)) * q_delta.conjugate\n ax.plot((0,x[1]), (0,x[2]), (0,x[3]), lw=2, c=\"r\")\n x = q_delta* Quaternion((0, 0, 1, 0)) * q_delta.conjugate\n ax.plot((0,x[1]), (0,x[2]), (0,x[3]), lw=2, c=\"b\")\n x = q_delta* Quaternion((0, 1, 0, 0)) * q_delta.conjugate\n ax.plot((0,x[1]), (0,x[2]), (0,x[3]), lw=2, c=\"g\")\n plt.pause(0.0001)\n\ns.close()\n\n","sub_path":"v4.py","file_name":"v4.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"470437487","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom .models import User\nfrom django.shortcuts import render, redirect, HttpResponseRedirect, reverse\nfrom django.contrib import messages\n\n# Create your views here.\ndef index(request):\n return render(request, 'main/index.html')\n\ndef register(request):\n result = User.objects.validate_registration(request.POST)\n if type(result) == list:\n for err in result:\n messages.error(request, err)\n return redirect('/')\n request.session['user_id'] = result.id\n request.session['name'] = result.alias\n messages.success(request, \"Successfully registered!\")\n return redirect('/pokes')\n\ndef login(request):\n result = User.objects.validate_login(request.POST)\n if type(result) == list:\n for err in result:\n messages.error(request, err)\n return redirect('/')\n request.session['user_id'] = result.id\n messages.success(request, \"Successfully logged in!\")\n return redirect('/pokes')\n\ndef logout(request):\n for key in request.session.keys():\n del request.session[key]\n return redirect('/')\n","sub_path":"apps/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"348566311","text":"import turtle\r\n\r\nob = turtle.Turtle()\r\n\r\nob.speed(20)\r\nob.getscreen().bgcolor(\"pink\")\r\nob.color(\"red\")\r\n\r\ndef circle(z, l, c):\r\n ob.lt(z)\r\n ob.fd(l)\r\n ob.rt(90)\r\n ob.color(c)\r\n ob.begin_fill()\r\n ob.circle(40)\r\n ob.end_fill()\r\n ob.home()\r\n\r\n\r\ncircle(110, 50, \"yellow\")\r\ncircle(70, 50, \"green\")\r\ncircle(98, 195, \"orchid\")\r\ncircle(85, 135, \"cyan\")\r\n\r\nturtle.done()\r\n\r\n","sub_path":"2_5235678443651203924.py","file_name":"2_5235678443651203924.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"410935558","text":"import requests\r\nimport math\r\nfrom bs4 import BeautifulSoup\r\nfrom sqlalchemy.ext.declarative import declarative_base\r\nfrom bottle import route, run, template\r\nfrom bottle import redirect, request\r\nfrom sqlalchemy.orm import sessionmaker\r\nfrom sqlalchemy import Column, String, Integer\r\nfrom sqlalchemy import create_engine\r\n\r\n\r\ndef get_news(page):\r\n tbl_list = page.table.findAll('table')\r\n news = tbl_list[1]\r\n titles = news.findAll('a', 'storylink')\r\n title_list = [titles[i].text for i in range(len(titles))]\r\n links_list = [title.attrs['href'] for title in titles]\r\n points = news.findAll('span', class_='score')\r\n points_list = [point.text for point in points]\r\n authors = news.findAll('a', 'hnuser')\r\n authors_list = [authors[i].text for i in range(len(authors))]\r\n news_inf = news.findAll('td', class_='subtext')\r\n comments_list = [inf.text.split('|')[4] for inf in news_inf]\r\n for i in range(len(comments_list)):\r\n if comments_list[i].find('comment') == -1:\r\n comments_list[i] = 0\r\n else:\r\n comments_list[i], _ = comments_list[i].split()\r\n comments_list[i] = int(comments_list[i])\r\n points_list[i], _ = points_list[i].split()\r\n points_list[i] = int(points_list[i])\r\n sorted_news = []\r\n for i in range(len(titles)):\r\n sorted_news.append({'author': authors_list[i],\r\n 'comments': comments_list[i],\r\n 'points': points_list[i],\r\n 'title': title_list[i],\r\n 'url': links_list[i]})\r\n return sorted_news\r\n\r\n\r\nBase = declarative_base()\r\nBase1 = declarative_base()\r\n\r\n\r\nclass News(Base):\r\n __tablename__ = \"news\"\r\n id = Column(Integer, primary_key=True)\r\n title = Column(String)\r\n author = Column(String)\r\n url = Column(String)\r\n comments = Column(Integer)\r\n points = Column(Integer)\r\n label = Column(String)\r\n\r\n\r\nclass Word(Base1):\r\n __tablename__ = \"words\"\r\n id = Column(Integer, primary_key=True)\r\n word = Column(String)\r\n num_word = Column(Integer)\r\n author = Column(String)\r\n num_auth = Column(Integer)\r\n url = Column(String)\r\n num_url = Column(Integer)\r\n label = Column(String)\r\n\r\n\r\nengine = create_engine(\"sqlite:///news.db\")\r\nBase.metadata.create_all(bind=engine)\r\nengine1 = create_engine(\"sqlite:///Words.db\")\r\nBase.metadata.create_all(bind=engine1)\r\nsession = sessionmaker(bind=engine)\r\nsession1 = sessionmaker(bind=engine1)\r\ns = session()\r\ns1 = session1()\r\n\r\nnews_list = []\r\nfor i in range(1):\r\n r = requests.get(\"https://news.ycombinator.com/newest?\" + 'i*30+1')\r\n page = BeautifulSoup(r.text, 'html.parser')\r\n news_list += get_news(page)\r\n\r\nfor i in range(len(news_list)):\r\n one = News(title=news_list[i]['title'],\r\n author=news_list[i]['author'],\r\n url=news_list[i]['url'],\r\n comments=news_list[i]['comments'],\r\n points=news_list[i]['points'])\r\n s.add(one)\r\n s.commit()\r\n\r\n\r\n\r\n@route('/add_label/', method='GET')\r\ndef add_label():\r\n label = request.GET.get('label').strip()\r\n id1 = request.GET.get('id').strip()\r\n s = session()\r\n record = s.query(News).filter(News.id == id1)\r\n record[0].label = label\r\n s.commit()\r\n redirect('/news')\r\n\r\nlabels = ['good', 'maybe', 'never']\r\n\r\n@route('/')\r\n@route('/news')\r\ndef new_list():\r\n s = session()\r\n rows = s.query(News).filter(News.label == None).all()\r\n return template('news_template', rows=rows)\r\n\r\n\r\n@route('/update_news')\r\ndef update_news():\r\n r = requests.get('https://news.ycombinator.com/newest')\r\n news_list = get_news(r.text)\r\n s = session()\r\n for n in news_list:\r\n rows = s.query(News).filter(News.author == n['author']).filter(News.title == n['title']).all()\r\n if rows == []:\r\n news = News(**n)\r\n s.add(news)\r\n s.commit\r\n redirect('/news')\r\n\r\n\r\n# run(host='localhost', port=8080)\r\n\r\n\r\ndef possibility(label):\r\n num_of_all = len(s.query(News).filter(News.label != None).all())\r\n label_rate = len(s.query(News).filter(News.label == label).all())\r\n result = label_rate / num_of_all\r\n return result\r\n\r\n\r\ndef possibility_author(label, author):\r\n num_of_all = len(s.query(News).filter(News.label == label).filter(News.author != None).all())\r\n author_rate = s1.query(Word).filter(Word.label == label).filter(Word.author == author).first()\r\n try:\r\n return author_rate.num_auth / num_of_all\r\n except AttributeError:\r\n return 1\r\n\r\n\r\ndef possibility_url(label, url):\r\n num_of_all = len(s.query(News).filter(News.label == label).filter(News.url != None).all())\r\n url_rate = s1.query(Word).filter(Word.label == label).filter(Word.url == url).first()\r\n try:\r\n return url_rate.num_url / num_of_all\r\n except AttributeError:\r\n return 1\r\n\r\n\r\ndef possibility_word(label, word_):\r\n num_of_all = 0\r\n query = s1.query(Word).filter(Word.label == label).filter(Word.word != None).all()\r\n for word in query:\r\n num_of_all += word.num_word\r\n word_rate = s1.query(Word).filter(Word.label == label).filter(Word.word == word_).first()\r\n try:\r\n return word_rate.num_word / num_of_all\r\n except AttributeError:\r\n return 1\r\n\r\ndef classificator():\r\n un_news = s.query(News).filter(News.label == None).all()\r\n for news in un_news:\r\n label_count = {'good': 0,\r\n 'maybe': 0,\r\n 'never': 0}\r\n for label in labels:\r\n rate_auth = math.log(possibility_author(label, news.author))\r\n rate_word = 0\r\n words = [word for word in news.title.split()]\r\n for word in words:\r\n rate_word += math.log(possibility_word(label, word))\r\n rate_url = math.log(possibility_url(label, news.url))\r\n label_count[label] = rate_auth + rate_url + rate_word + possibility(label)\r\n max = -1000000000\r\n for label in label_count:\r\n if label_count[label] > max:\r\n max = label_count[label]\r\n key = label\r\n if key == 'good':\r\n news.label = 'good!'\r\n elif key == 'maybe':\r\n news.label = 'maybe!'\r\n else:\r\n news.label = 'never!'\r\n s.commit()\r\n\r\nclassificator()\r\n\r\n@route('/')\r\n@route('/news1')\r\ndef new_list1():\r\n s = session()\r\n rows1 = s.query(News).filter(News.label == 'good!').all()\r\n rows2 = s.query(News).filter(News.label == 'maybe!').all()\r\n rows3 = s.query(News).filter(News.label == 'never!').all()\r\n return template('news_template1.tpl', rows1=rows1, rows2=rows2, rows3=rows3)\r\n\r\nrun(host='localhost', port=8080)\r\n","sub_path":"home/roofflex/Desktop/Python/LABNEWS/LAB.py","file_name":"LAB.py","file_ext":"py","file_size_in_byte":6730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"297321471","text":"import copy\nimport os\nimport itertools\nimport random\nfrom general_utils import get_logger\n\nimport toml\n\n\nclass Config(object):\n \"\"\"\n This class build configuration object from toml file.\n \"\"\"\n def __init__(self, filename):\n \"\"\"\n Args:\n filename: path to toml file\n \"\"\"\n with open(filename) as conffile:\n config = toml.loads(conffile.read())\n\n # general config\n self.path_keys = list(config['path'].keys())\n self.output_path = str(config['path'][\"output_path\"])\n self.model_output = str(config['path'][\"model_output\"])\n self.learning_curves_output = str(config['path'][\"learning_curves_output\"])\n self.log_path = str(config['path'][\"log_path\"])\n\n # embeddings\n self.dim = int(config[\"data\"][\"dim\"])\n self.dim_char = int(config[\"data\"][\"dim_char\"])\n self.glove_filename = str(config[\"data\"][\"glove_filename\"])\n # trimmed embeddings (created from glove_filename with build_data.py)\n self.trimmed_filename = str(config[\"data\"][\"trimmed_filename\"])\n\n # dataset\n self.data_type = str(config[\"data\"][\"data_type\"])\n self.dev_filename = str(config[\"data\"][\"dev_filename\"])\n self.test_filename = str(config[\"data\"][\"test_filename\"])\n self.train_filename = str(config[\"data\"][\"train_filename\"])\n _max_iter = int(config[\"data\"][\"max_iter\"])\n self.max_iter = _max_iter if _max_iter > 0 else None\n\n # vocab (created from dataset with build_data.py)\n self.words_filename = str(config[\"data\"][\"words_filename\"])\n self.tags_filename = str(config[\"data\"][\"tags_filename\"])\n self.chars_filename = str(config[\"data\"][\"chars_filename\"])\n\n # training\n self.search_params_keys = [k for k, v in config[\"hyperparameters\"].items()\n if isinstance(v, list)]\n self.search_params_vals = [config[\"hyperparameters\"][k] for k in self.search_params_keys]\n self.num_random_search = config[\"hyperparameters\"][\"num_random_search\"]\n self.train_embeddings = config[\"hyperparameters\"][\"train_embeddings\"]\n self.nepochs = config[\"hyperparameters\"][\"nepochs\"]\n self.dropout = config[\"hyperparameters\"][\"dropout\"]\n self.batch_size = config[\"hyperparameters\"][\"batch_size\"]\n self.lr_method = config[\"hyperparameters\"][\"lr_method\"]\n self.lr = config[\"hyperparameters\"][\"lr\"]\n self.lr_decay = config[\"hyperparameters\"][\"lr_decay\"]\n self.clip= config[\"hyperparameters\"][\"clip\"]\n self.nepoch_no_imprv = config[\"hyperparameters\"][\"nepoch_no_imprv\"]\n self.reload = config[\"hyperparameters\"][\"reload\"]\n\n # model hyperparameters\n self.hidden_size = config[\"hyperparameters\"][\"hidden_size\"]\n self.char_hidden_size = config[\"hyperparameters\"][\"char_hidden_size\"]\n\n # NOTE: if both chars and crf, only 1.6x slower on GPU\n # if crf, training is 1.7x slower on CPU\n self.crf = config[\"hyperparameters\"][\"crf\"]\n # if char embedding, training is 3.5x slower on CPU\n self.chars = config[\"hyperparameters\"][\"chars\"]\n\n # directory for training outputs\n if not os.path.exists(self.output_path):\n os.makedirs(self.output_path)\n # create instance of logger\n self.logger = get_logger(self.log_path)\n\n def save(self, filepath):\n result = {\n 'path': {},\n 'data': {},\n 'hyperparameters': {}\n }\n\n result['path'] = {\n 'output_path': self.output_path,\n 'model_output': self.model_output,\n 'learning_curves_output': self.learning_curves_output,\n 'log_path': self.log_path\n }\n\n result['data'] = {\n 'dim': self.dim,\n 'dim_char': self.dim_char,\n 'glove_filename': self.glove_filename,\n 'trimmed_filename': self.trimmed_filename,\n 'data_type': self.data_type,\n 'dev_filename': self.dev_filename,\n 'test_filename': self.test_filename,\n 'train_filename': self.train_filename,\n 'max_iter': self.max_iter if self.max_iter is not None else -1,\n 'words_filename': self.words_filename,\n 'tags_filename': self.tags_filename,\n 'chars_filename': self.chars_filename,\n }\n\n result['hyperparameters'] = {\n 'num_random_search': self.num_random_search,\n 'train_embeddings': self.train_embeddings,\n 'nepochs': self.nepochs,\n 'dropout': self.dropout,\n 'batch_size': self.batch_size,\n 'lr_method': self.lr_method,\n 'lr': self.lr,\n 'lr_decay': self.lr_decay,\n 'clip': self.clip,\n 'nepoch_no_imprv': self.nepoch_no_imprv,\n 'reload': self.reload,\n 'hidden_size': self.hidden_size,\n 'char_hidden_size': self.char_hidden_size,\n 'crf': self.crf,\n 'chars': self.chars,\n }\n\n with open(filepath, 'w', encoding='utf-8') as fd:\n toml.dump(result, fd)\n\n\n\ndef random_search(config):\n candidates = list(itertools.product(*config.search_params_vals))\n if len(candidates) <= 0:\n yield config\n\n random.shuffle(candidates)\n for i, params in zip(range(config.num_random_search), iter(candidates)):\n variant = copy.copy(config)\n for k, v in zip(config.search_params_keys, params):\n assert not isinstance(v, list)\n setattr(variant, k, v)\n\n for k in config.path_keys:\n path = getattr(variant, k)\n d = os.path.join(os.path.dirname(path), str(i))\n if not os.path.exists(d):\n os.makedirs(d)\n setattr(variant, k, os.path.join(d, os.path.basename(path)))\n yield variant\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":5879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"565814170","text":"import itertools\nfrom sqlalchemy import Column, Integer, String, Float\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nimport requests\nimport random\nimport sys\n\nBase = declarative_base()\n\nclass IataCodesCity(Base):\n __tablename__ = 'iatacodes_iata'\n id = Column(Integer, primary_key=True)\n code = Column(String(3))\n country_code = Column(String(2))\n name = Column(String(500))\n lat = Column(Float)\n lng = Column(Float)\n alternatenames = Column(String(1000))\n timezone = Column(String(50))\n gmt = Column(String(10))\n tch_code = Column(String(100))\n popularity = Column(Integer)\n geoname_id = Column(Integer)\n\n\n#engine = create_engine('sqlite:///iatacodes.db')\nengine = create_engine('postgresql://rigauser:au16jmddgmx9pa19@testiandodb-do-user-5009763-0.db.ondigitalocean.com:25060/rigadb?sslmode=require')\nBase.metadata.create_all(engine)\nBase.metadata.bind = engine\nDBSession = sessionmaker()\nDBSession.bind = engine\nsession = DBSession()\n\n\nallLetters = 'QWERTYUIOPASDFGHJKLZXCVBNM1234567890QWERTYUIOPASDFGHJKLZXCVBNM1234567890QWERTYUIOPASDFGHJKLZXCVBNM1234567890'\nallLetters = ''.join(random.sample(allLetters,len(allLetters)))\nfor codeItem in itertools.permutations(allLetters,r=3):\n iataCode = f\"{codeItem[0]}{codeItem[1]}{codeItem[2]}\"\n print(iataCode)\n iataCodeFromDb = session.query(IataCodesCity).filter(IataCodesCity.code == iataCode).first()\n if iataCodeFromDb is None:\n response = requests.get(\n f'https://iatacodes.org/api/v6/cities?api_key=d1aecda8-152a-478f-937f-0fe58702d44b&code={iataCode}',\n verify=False)\n if response.status_code == 200:\n resultData = response.json()['response']\n if len(resultData) != 0:\n data = resultData[0]\n iataCodeCity = IataCodesCity()\n iataCodeCity.code = data['code']\n iataCodeCity.alternatenames = data['alternatenames']\n iataCodeCity.country_code = data['country_code']\n iataCodeCity.geoname_id = data['geoname_id']\n iataCodeCity.gmt = data['gmt']\n iataCodeCity.lat = data['lat']\n iataCodeCity.lng = data['lng']\n iataCodeCity.name = data['name']\n iataCodeCity.popularity = data['popularity']\n iataCodeCity.tch_code = data['tch_code']\n iataCodeCity.timezone = data['timezone']\n try:\n session.add(iataCodeCity)\n session.commit()\n except Exception as e:\n session.rollback()\n session = DBSession()\n else:\n try:\n iataCodeCity = IataCodesCity()\n iataCodeCity.code = iataCode\n session.add(iataCodeCity)\n session.commit()\n except Exception as e:\n session.rollback()\n session = DBSession()\n else:\n pass\n\nQRS,lat,lon","sub_path":"Pandas/scrappingscripts/getdatafromiatacodes.org.py","file_name":"getdatafromiatacodes.org.py","file_ext":"py","file_size_in_byte":3119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"471264222","text":"import sys\nimport os\nimport random\n\n\ndef add_to_file(newUserName):\n\n if len(sys.argv) == 1:\n file_logs = open('usernames_file.txt', 'a')\n else:\n file_logs = open(sys.argv[1], 'a')\n file_logs.write(newUserName)\n file_logs.write('\\n')\n file_logs.close()\n\n\ndef find_str_in_file(newUserName):\n if len(sys.argv) == 1:\n file_logs = open('usernames_file.txt', 'r')\n print ('standart file')\n for element in file_logs:\n if element.rstrip() == newUserName:\n file_logs.close()\n return True\n else:\n if os.path.exists(sys.argv[1]):\n file_logs = open(sys.argv[1], 'r')\n for element in file_logs:\n if element.rstrip() == newUserName:\n file_logs.close()\n return True\n else:\n file_logs = open(sys.argv[1], 'w')\n file_logs.close()\n return False\n\n\ndef create_rand_list(newUserName, ELEMENTS_IN_RANDOM_LIST):\n list_rand_names = []\n index = 0\n while index < ELEMENTS_IN_RANDOM_LIST:\n number = random.randint(1, 100)\n if find_str_in_file(newUserName + str(number)) == 0:\n list_rand_names.append(newUserName + str(number))\n index = index + 1\n print (list_rand_names)\n\n\ndef main():\n ELEMENTS_IN_RANDOM_LIST = 5\n notExit = 1\n while(notExit):\n try:\n newUserName = input('enter username ')\n except ValueError:\n print('need a liters')\n else:\n finded_name = find_str_in_file(newUserName)\n if finded_name == 0:\n print('Name is OK ')\n add_to_file(newUserName)\n notExit = 0\n else:\n print('This name is reservd, u can use this names: ')\n create_rand_list(newUserName, ELEMENTS_IN_RANDOM_LIST)\nif __name__ == '__main__':\n main()\n","sub_path":"secondtask_Perminov.py","file_name":"secondtask_Perminov.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"322656188","text":"# LSTM Model for Next Word Prediction\n\nfrom keras.preprocessing.text import Tokenizer\nimport nltk\nfrom nltk.tokenize import word_tokenize\nimport numpy as np\nimport re\nfrom keras.utils import to_categorical\nfrom doc import training_data\n\ncleaned = re.sub(r'\\W+', ' ', training_data).lower()\ntokens = word_tokenize(cleaned)\ntrain_len = 3+1\ntext_sequences = []\n\nfor i in range(train_len,len(tokens)):\n seq = tokens[i-train_len:i]\n text_sequences.append(seq)\n\nsequences = {}\ncount = 1\n\nfor i in range(len(tokens)):\n if tokens[i] not in sequences:\n sequences[tokens[i]] = count\n count += 1\n\ntokenizer = Tokenizer()\ntokenizer.fit_on_texts(text_sequences)\nsequences = tokenizer.texts_to_sequences(text_sequences) \n\n#Collecting some information \nvocabulary_size = len(tokenizer.word_counts)+1\nn_sequences = np.empty([len(sequences),train_len], dtype='int32')\n\nfor i in range(len(sequences)):\n n_sequences[i] = sequences[i]\n\ntrain_inputs = n_sequences[:,:-1]\ntrain_targets = n_sequences[:,-1]\ntrain_targets = to_categorical(train_targets, num_classes=vocabulary_size)\nseq_len = train_inputs.shape[1]\n\nfrom keras.models import Sequential, load_model\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nfrom keras.layers import Embedding\n#model = load_model(\"mymodel.h5\")\n\nmodel = Sequential()\nmodel.add(Embedding(vocabulary_size, seq_len, input_length=seq_len))\nmodel.add(LSTM(50,return_sequences=True))\nmodel.add(LSTM(50))\nmodel.add(Dense(50,activation='relu'))\nmodel.add(Dense(vocabulary_size, activation='softmax'))\nprint(model.summary())\n\n# compile network\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\nmodel.fit(train_inputs,train_targets,epochs=500,verbose=1)\nmodel.save(\"mymodel.h5\")\n\nfrom keras.preprocessing.sequence import pad_sequences\ninput_text = input().strip().lower()\nencoded_text = tokenizer.texts_to_sequences([input_text])[0]\npad_encoded = pad_sequences([encoded_text], maxlen=seq_len, truncating='pre')\nprint(encoded_text, pad_encoded)\n\nfor i in (model.predict(pad_encoded)[0]).argsort()[-3:][::-1]:\n pred_word = tokenizer.index_word[i]\n print(\"The next word can be:\",pred_word)","sub_path":"LSTM/lstm.py","file_name":"lstm.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"354398595","text":"# coding: utf-8\nnum_N = int(input())\ndata = [list(map(int, input().split())) for __ in range(num_N)]\ndata.reverse()\n\nans = 0\n\nfor a, b in data:\n r = (a + ans) % b\n if r:\n ans += b - r\n\nprint(ans)","sub_path":"AGC_009/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"176445914","text":"import serial\n#from rover_common import aiolcm\n#from rover_msgs import GPSOdometry\n\ndef main():\n # lcm = aiolcm.AsyncLCM()\n\n serialPort = serial.Serial(\"/dev/ttyAMA0\")\n serialPort.baudrate = 19200\n serialPort.open()\n\n while (true):\n oneByte = serialPort.read();\n if (oneByte == '$'):\n fiveBytes = serialPort.read(5);\n if (fiveBytes == 'GPRMC'):\n# gpsOdometry = GPSOdometry()\n moreBytes = serialPort.read(51)\n# gpsOdometry.lattitude = float(moreBytes[12:22])\n# gpsOdometry.longitude = float(moreBytes[25:36])\n# gpsOdometry.speed = float(moreBytes[39:45])\n# gpsOdometry.bearing = float(moreBytes[46:51])\n# lcm.publish('/some channel', gpsOdometry.encode())\n print(\"Lattitude \" + str(float(moreBytes[12:22])))\n print(\"Longtitude \" + str(float(moreBytes[25:36])))\n print(\"Speed \" + str(float(moreBytes[39:45])))\n print(\"Bearing \" + str(float(moreBytes[46:51])))\n ","sub_path":"microcontrollers/gps/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"56824011","text":"\ndef elso_feladat(szam):\n hatvany=0\n binaris=list(str(bin(szam)[2:]))\n kitevok=[]\n for i in range(len(binaris)-1,-1,-1):\n if binaris[i]=='1':\n kitevok.append(hatvany)\n hatvany=hatvany+1\n return kitevok\nwhile True:\n try:\n n=int(input('Adj meg egy számot!'))\n print(elso_feladat(n))\n break\n except ValueError:\n print(\"Nem megfelelő a megadott érték!\")","sub_path":"beadando_1.py","file_name":"beadando_1.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"406246398","text":"from deepface import DeepFace\nimport imutils\nfrom imutils.video import VideoStream\nimport cv2\nimport time\nimport pandas as pd\n\n\nbackends = ['opencv', 'ssd', 'dlib', 'mtcnn']\nbackends = backends[1]\n\nprint(\"[INFO] starting video stream...\")\nvs = VideoStream(src=0).start()\n# vs = VideoStream(usePiCamera=True).start()\ntime.sleep(2.0)\ntotal = 0\n\nwhile True:\n frame = vs.read()\n base_frame = frame.copy()\n frame = imutils.resize(frame, width=480)\n original_size = base_frame.shape\n detected_aligned_face = DeepFace.detectFace(img_path=frame, detector_backend=backends)\n print(len(detected_aligned_face))\n #print(detected_aligned_face)\n\n # show the output frame\n cv2.imshow(\"Frame\", base_frame)\n key = cv2.waitKey(1) & 0xFF\n\n # if the 'k' key was pressed, write the *orignial* frame to disk\n # so we can later process it, and use it for regconition\n if key == ord(\"k\"):\n p = 'dataset/lvan/' + str(total) + '.png'\n print(p)\n cv2.imwrite(p, frame)\n total += 1\n\n # if the q key pressed, break from the loop\n elif key == ord(\"q\"):\n break\n\n # print the total faces saved and do a bit of cleanup\n\nprint(\"[INFO] {} face images stored\".format(total))\nprint(\"[INFO] cleaning up...\")\ncv2.destroyAllWindows()\nvs.stop()\n","sub_path":"create_dataset_with_deppface.py","file_name":"create_dataset_with_deppface.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"626937272","text":"import unittest\nimport os\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.common.keys import Keys\nimport time\n\n#testing INVALID Login to TarHeelReader.org\n\nclass IEInvalidLogin(unittest.TestCase):\n\n def setUp(self):\n iedriver = \"C:/Python27/Scripts/IEDriverServer\"\n os.environ[\"webdriver.ie.driver\"] = iedriver\n self.driver = webdriver.Ie(iedriver)\n #self.driver = webdriver.IE() # Get local session of IE\n \n def test_ie_invalid_login(self):\n driver = self.driver\n driver.get(\"http://www.tarheelreader.org\") # Load page\n self.assertIn(\"Tar Heel Reader\", driver.title)\n try:\n well = driver.find_element_by_xpath(\"//img[contains(@src,'http://tarheelreader3s.cs.unc.edu/themeV1/images/well.png')]\")# Find the main menu\n well.click()\n WebDriverWait(driver, 10).until(lambda s: s.find_element_by_class_name(\"navigationMenu\").is_displayed())\n except NoSuchElementException:\n assert 0, \"Can not find main menu\"\n \n #Find the login link and click, throw error otherwise\n try:\n login = driver.find_element_by_link_text(\"Log in\")\n login.click()\n except NoSuchElementException:\n assert 0, \"Can not find login\"\n \n #check if the cursor is on the user field of the form\n #type in user name\n try:\n user = driver.find_element_by_name(\"log\")\n user.send_keys(\"huynhl\")\n except NoSuchElementException:\n assert 0, \"Can not find user form\"\n \n #makes sure the cursor is on the password field\n #types an invalid password\n try:\n pw = driver.find_element_by_name(\"pwd\")\n pw.send_keys(\"thrt85384\")\n pw.send_keys(Keys.RETURN)\n except NoSuchElementException:\n assert 0, \"Can not find pwd form\"\n \n #if page logins in with an INVALID user/pwd then throw an error\n try:\n text = driver.find_element_by_xpath(\"//p[@class='message']\")\n except NoSuchElementException:\n assert 0, \"Invalid pwd test failed\"\n \n def tearDown(self):\n self.driver.quit()\n \nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"LearningScripts/InvalidLoginIE.py","file_name":"InvalidLoginIE.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"301412113","text":"import tortuga as t\nimport pila as pi\nimport pluma as p\n\n\ndef archivo_invalido():\n\t'''Imprime un mensaje de error cuando el archivo es inválido, y lanza un excepción de tipo ValueError.'''\n\tprint(\"Archivo de instrucciones inválido.\")\n\tprint('''\n\t\tEjemplo de un archivo válido:\n\n\t\t27.2\n\t\tX\n\t\tX X-F+G\n\t\tF FG+\n\n\t\tDonde la primera línea es el ángulo, la segunda el axioma y las siguientes líneas \\\n\t\tlas reglas de cambio, con los símbolos separados de su traducción por un espacio.''')\n\traise ValueError\n\n\ndef procesador(archivo):\n\t\"\"\"Recibe el archivo del fractal, devuelve el angulo, axioma y diccionario de reglas\"\"\"\n\ttry:\n\t\twith open(archivo) as archivo:\n\t\t\ttry:\n\t\t\t\tangulo = float(archivo.readline().rstrip('\\n'))\n\n\t\t\texcept ValueError:\n\t\t\t\tarchivo_invalido()\n\n\t\t\taxioma = archivo.readline().rstrip('\\n')\n\n\t\t\tif not axioma:\n\t\t\t\tarchivo_invalido()\n\n\t\t\treglas = {}\n\n\t\t\tfor linea in archivo:\n\n\t\t\t\ttry:\n\t\t\t\t\tprecesor, sucesor = linea.rstrip('\\n').split()\n\t\t\t\t\treglas[precesor] = sucesor\n\n\t\t\t\texcept ValueError:\n\t\t\t\t\tarchivo_invalido()\n\n\t\t\tif not reglas:\n\t\t\t\tarchivo_invalido()\n\n\texcept IOError:\n\t\tprint(f'No se encontró {archivo}.')\n\t\traise IOError\n\n\treturn angulo, axioma, reglas\n\n\ndef generador_sistema(axioma, reglas, n):\n\t\"\"\"\n\tGenera el sistema a partir de un axioma, diccionario de reglas y la cantidad\n\tde veces que deben aplicarse las mismas.\n\t:param axioma: cadena que define el estado inicial\n\t:param regals: lista de traducciones predecesor - sucesor\n\t:return: sistema L traducida\n\t\"\"\"\n\tif n == 1:\n\t\treturn axioma\n\n\tcadena_final = \"\"\n\n\tfor c in axioma:\n\t\tcadena_final += reglas.get(c, c)\n\n\treturn generador_sistema(cadena_final, reglas, n - 1)\n\n\ndef crear_svg(destino, sistema, angulo, iteraciones):\n\t\"\"\"\n\tRecibe como parametros el archivo .svg de destino, el sistema de comandos\n\ty el angulo de giro.\n\tPre-condiciones: el sistema debe haber sido generada previamente\n\ta partir de un axioma y un diccionario de traducciones.\n\tPost: Se genera el archivo .svg indicado contiendo las etiquetas xml generadas\n\ta partir de dibujar la secuencia de comandos utilizando la clase tortuga.\n\t\"\"\"\n\tunidad = 3\n\twith open(destino, 'w') as f:\n\n\t\tf.write(\n\t\t\tf'\\n')\n\t\ttortuguero = pi.Pila()\n\t\ttortuguero.apilar(t.Tortuga(0, 0, 270, p.Pluma()))\n\n\t\tdibujar(sistema, tortuguero, unidad, angulo, f)\n\n\t\tf.write('\\n')\n\n\ndef dibujar(secuencia, tortuguero, unidad, angulo, f):\n\t\"\"\"\n\tRecibe una secuencia de comandos, una pila de tortugas, una unidad , un angulo\n\ty el archivo en el cual se debe escribir.\n\tLa funcion escribe directamente sobre el archivo los comandos incluidos en la\n\tsecuencia.\n\t\"\"\"\n\tfor c in secuencia:\n\t\tif c == 'F' or c == 'G':\n\t\t\ttortuguero.ver_tope().avanzar(unidad, f)\n\n\t\tif c == 'f' or c == 'g':\n\t\t\ttortuguero.ver_tope().pluma.pluma_arriba()\n\t\t\ttortuguero.ver_tope().avanzar(unidad, f)\n\t\t\ttortuguero.ver_tope().pluma.pluma_abajo()\n\n\t\tif c == '+':\n\t\t\ttortuguero.ver_tope().girar_derecha(angulo)\n\n\t\tif c == '-':\n\t\t\ttortuguero.ver_tope().girar_izquierda(angulo)\n\n\t\tif c == '|':\n\t\t\ttortuguero.ver_tope().girar_derecha(180)\n\n\t\tif c == '[':\n\t\t\ttortuguero.apilar(tortuguero.ver_tope().clonar())\n\n\t\tif c == ']':\n\t\t\ttortuguero.desapilar()\n\n\t\tif c == 'a':\n\t\t\ttortuguero.ver_tope().obtener_pluma().cambiar_color('blue')\n\n\t\tif c == 'b':\n\t\t\ttortuguero.ver_tope().obtener_pluma().cambiar_color('red')\n\n\t\tif c == '1':\n\t\t\ttortuguero.ver_tope().obtener_pluma().cambiar_ancho(1)\n\n\t\tif c == 'a':\n\t\t\ttortuguero.ver_tope().obtener_pluma().cambiar_ancho(2)\n\n\t\tif c == 'L':\n\t\t\ttortuguero.ver_tope().circulo(unidad, f)\n","sub_path":"Trabajos_Practicos/TP3/entrega/funciones.py","file_name":"funciones.py","file_ext":"py","file_size_in_byte":3589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"266882742","text":"# -*- coding: utf-8 -*-\n\nfrom rate_limit import *\nfrom plugin_system import *\n\nimport re\n\nimport logging\nlog = logging.getLogger(__name__)\n\n\n@pluginfunction(\n 'cve',\n 'parse a CVE handle',\n ptypes.PARSE,\n ratelimit_class=RATE.NO_SILENCE | RATE.GLOBAL\n)\ndef parse_cve(data, **_):\n cves = re.findall(r'(CVE-\\d\\d\\d\\d-\\d+)', data.upper())\n if not cves:\n return\n\n log.info('detected CVE handle')\n return {\n 'msg': ['https://security-tracker.debian.org/tracker/%s' % c for c in cves]\n }\n\n\n","sub_path":"plugins/cve.py","file_name":"cve.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"233997996","text":"from dnd import dice\n\nimport discord\n\nimport asyncio\nimport sys\nimport os\nimport random\nimport configparser\n\nclient = discord.Client()\nbotConfig = configparser.ConfigParser()\nconfig = configparser.ConfigParser()\n\nbotVersion = \"6.2.2\"\n\nbotAuthTokenPath = None\nbotHomeChannelID = None\nbotControllerRole = None\nbotCommandPrefix = None\nfroggyQuotesPath = None\n\nworkingPath = \"./\"\n\n# create and save configuration files for each server when it joins them\n\ndef getBotConfiguration():\n\tglobal botAuthTokenPath\n\tglobal botHomeChannelID\n\tglobal botControllerRole\n\tglobal botCommandPrefix\n\tglobal froggyQuotesPath\n\n\tbotConfig.read('./bot.conf')\n\n#\tconfig['FROG_CONFIG'] = {'TokenPath': \"./token.txt\",\n#\t\t\t\t\t\t\t'BotHomeChannelID': \"454470370817343488\",\n#\t\t\t\t\t\t\t'BotControllerRole': \"Frog\",\n#\t\t\t\t\t\t\t'BotCommandPrefix': \"!\",\n#\t\t\t\t\t\t\t'FroggyQuotesPath': \"./resources/frogquotes.txt\"\n#\t\t\t\t\t\t\t}\n\n\tbotAuthTokenPath = botConfig['FROG_CONFIG']['BotAuthTokenPath']\n\tbotHomeChannelID = botConfig['FROG_CONFIG']['BotHomeChannelID']\n\tbotControllerRole = botConfig['FROG_CONFIG']['BotControllerRole']\n\tbotCommandPrefix = botConfig['FROG_CONFIG']['BotCommandPrefix']\n\tfroggyQuotesPath = botConfig['FROG_CONFIG']['FroggyQuotesPath']\n\ndef getBotConfigOption(option):\n\treturn botConfig['FROG_CONFIG'][option]\n\ndef getServerConfigOption(serverID, option):\n\tconfig = configparser.ConfigParser()\n\tconfig.read(\"server_configurations/\" + serverID + \".conf\")\n\treturn config[serverID][option]\n\ndef getRandomFroggyQuote():\n\treturn random.choice(open(froggyQuotesPath).read().splitlines())\n\ndef percent():\n\treturn random.randint(0, 100)\n\n@client.event\nasync def on_ready():\n\tprint(\"logged in as \" + client.user.name + \" (\" + client.user.id + \")\")\n\tawait client.change_presence(game=discord.Game(name = \"froggy being a fool\", type = 3))\n\t\n\ttry:\n\t\tservers = list(client.servers)\n\t\tfor x in range(len(servers)):\n\t\t\tchannel = client.get_channel(getServerConfigOption(str(servers[x].id), 'BotHomeChannelID'))\n\t\t\tawait channel.send(\"yea what's up? :white_check_mark: (v\" + str(botVersion) + \")\")\n\texcept Exception as exception:\n\t\tawait client.get_channel(botHomeChannelID).send(\":bangbang: Exception in on_ready: `\" + exception.__class__.__name__ + '`:\\n```' + str(exception) + \"```\")\n\t\treturn\n\n@client.event\nasync def on_server_join(server):\n\ttry:\n\t\tfor c in server.channels:\n\t\t\tif not c.type == discord.ChannelType.text:\n\t\t\t\tif not c.permissions_for(server.me).sends:\n\t\t\t\t\tcontinue\n\t\t\t\t\n\t\t#await client.send(c, \"yea what's up? :white_check_mark:\")\n\t\t\n\t# TODO: include more information about server\n\texcept Exception as exception:\n\t\tawait client.get_channel(botHomeChannelID).send(\":bangbang: Exception in on_server_join: `\" + exception.__class__.__name__ + '`:\\n```' + str(exception) + \"```\" + \"\\nserver: \" + server.id)\n\t\treturn\n\n@client.event\nasync def on_message(message):\n\ttry:\n\t\tchannel = message.channel\n\n\t\t#try:\n\t\t#\tprint(message.user.name + \"#\" + message.user.discriminator + \": \" + message.message)\n\t\t#except:\n\t\t#\tprint(message.user.id + \" does not want to be printed in the terminal!\")\n\t\t\t\n\t\tif message.content.startswith(botCommandPrefix + \"help\"):\n\t\t\tawait channel.send(\"List of commands:\\n\\n`!help` - this dialog.\\n`!fcuk` - responds with a random frog quote\\n`!roll` - rolls a dice with the specified number of sides\\narguments:\\nsides: number of sides on the die\\nmodifier: DnD modifier\\n`!check` - DnD skill check\\ninternally calls `!roll 20 [modifier]`\\n`!percent` - random percent between 0 and 100.\\n`!setplaying` - sets the playing status for the bot\\n\\nfrogbot version \" + str(botVersion))\n#\t\t\tawait client.send(message.channel, \"List of commands:\\n\\n`!help` - this dialog.\\n`!fcuk` - responds with a random frog quote\\n`!roll` - rolls a dice with the specified number of sides\\narguments:\\nsides: number of sides on the die\\nmodifier: DnD modifier\\n`!check` - DnD skill check\\ninternally calls `!roll 20 [modifier]`\\n`!percent` - random percent between 0 and 100.\\n`!setplaying` - sets the playing status for the bot\\n`!restart` - restarts the bot\\n\\nfrogbot version \" + str(botVersion))\n\t\t\treturn\n\t\telif message.content.startswith(botCommandPrefix + \"fcuk\"):\n\t\t\tawait channel.send(getRandomFroggyQuote())\n\t\t\treturn\n\t#\tTODO: this\n\t#\tif message.content.startswith(botCommandPrefix + \"sins\"):\n\t#\t\tawait client.send(message.channel, \"I heard Minecraft?\")\n\t#\t\treturn\n\t\telif message.content.startswith(botCommandPrefix + \"check\"):\n\t\t\tawait message.channel.send(abilityCheck(message.content))\n\t\t\treturn\n\t\telif message.content.startswith(botCommandPrefix + \"roll\"):\n\t\t\tawait message.channel.send(rollDice(message.content))\n\t\t\treturn\n\t\telif message.content.startswith(botCommandPrefix + \"percent\"):\n\t\t\tawait channel.send(str(percent()) + \"%\")\n\t\t\treturn\n\t#\tTODO: restrict this to admins\n\t#\tTODO: !setwatching\n\t\telif message.content.startswith(botCommandPrefix + \"setplaying\"):\n\t\t\t# strip the first word\n\t\t\tstring = message.content.split(' ', 1) # skip first word (\"!setplaying\")\n\t\t\t\n\t\t\ttry:\n\t\t\t\tawait channel.send(\"aye\")\n\t\t\t\tgameName = string[1]\n\n\t\t\t\tif gameName == \"none\":\n\t\t\t\t\tawait client.change_presence(game=discord.Game(name=\"froggy being a fool\", type=3))\n\t\t\t\telse:\n\t\t\t\t\tawait client.change_presence(game=discord.Game(name=gameName, type=3))\n\t\t\texcept IndexError:\n\t\t\t\tawait channel.send(\"no game name provided\")\n\t\t\t\t\n\t\t\treturn\n#\t\telse if message.content.startswith(\"!restart\"):\n#\t\t\tawait client.send(message.channel, \"bye bye :wave::skin-tone-2:\")\n\t\t\t\n#\t\t\tos.fsync()\n\t\t\t\n#\t\t\tos.execv(\"./frogbot.py\", sys.argv)\n#\t\t\tsys.exit()\n#\t\t\treturn\n#\t\telse:\n#\t\t\tawait client.send(message.channel, \"what\")\n\texcept Exception as exception:\n\t\tawait channel.send(\":bangbang: Exception in on_message: `\" + exception.__class__.__name__ + '`:\\n```' + str(exception) + \"```\")\n\t\treturn\n\nprint(\"Starting with \", len(sys.argv), \" arguments.\")\nprint(str(sys.argv))\n\nos.chdir(workingPath)\n\ngetBotConfiguration()\ngetAuthToken = open(botAuthTokenPath, \"r\")\nclient.run(getAuthToken.read())\nsys.exit()\n","sub_path":"frogbot.py","file_name":"frogbot.py","file_ext":"py","file_size_in_byte":5948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"24281318","text":"'''\nTop K Frequent Elements\n2020_12_11\nTime: O(nlogn)\nSpace: O(n)\n思考流程:\n1.用counter這API去計算出現次數,好處是會自動排大小\n2.再用most_common抓出出現前多k次得數字\n'''\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n ans = []\n count = Counter(nums)\n for i in count.most_common(k):\n ans += [i[0]]\n return ans\n ","sub_path":"Medium/topKFrequentElements.py","file_name":"topKFrequentElements.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"468798653","text":"\"\"\"\n Checks for duplicates in final json files\n\"\"\"\n\n# Imports\nimport json\n\n\ndef is_duplicate_edge(filename):\n edge_id_list = []\n duplicate_list = []\n jsonfile = json.load(open(filename))\n for dict in jsonfile:\n edge_id = dict['source'] + '@' + dict['target']\n if edge_id not in edge_id_list:\n edge_id_list.append(edge_id)\n else:\n duplicate_list.append(edge_id)\n\n return duplicate_list\n\n\ndef is_duplicate_node(filename):\n node_id_list = []\n duplicate_list = []\n jsonfile = json.load(open(filename))\n for dict in jsonfile:\n node_id = dict['name']\n if node_id not in node_id_list:\n node_id_list.append(node_id)\n else:\n duplicate_list.append(node_id)\n\n print(duplicate_list)\n\n\nis_duplicate_node('nodes.json')\n# is_duplicate_edge('edges.json')\n\n\n","sub_path":"SLKlib/duplicate_check.py","file_name":"duplicate_check.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"590629327","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'todo_list'\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^new_item/$', views.new_item, name='new_item'),\n \n #url(r'^(?P[0-9]+)/mark_box/$', views.mark_box, name='mark_box'),####\n \n]\n\n","sub_path":"todo/todo_list/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"537001439","text":"# Clase para parsear y dibujar archivos .obj\n\n#1. o -> Reviso si tengo una línea llamada o, si existe, la clave de mi HashMap es el valor de o, sino es el nombre del archivo\n#2. # -> Comentarios, ignoradas a menos que contenga #Fin Archivo\n#3. v -> Función de carga de vértices. Guardarlos en una lista\n#4. f -> Función de carga de caras. Tomar la posición dada-1 y buscarlo en la lista de vértices\n\n#Función de dibujado: glDrawElements y glDrawArrays (prioridad)\n\n# Cambiar el parser para que todo se guarde en un mismo array -> de append a concat\n# Agregar propiedades para que tengamos los vértices listos para hacer DrawElements y otro para DrawArrays\n\nfrom os import listdir\nfrom os.path import isfile, join\n\nclass ObjHandler():\n def __init__(self):\n self.__name = \"\"\n # self.__numVertx = 0\n # self.__numFaces = 0\n\n self.__arrays = []\n self.__elements = []\n self.__arrayElements = [] # DrawArrays\n self.__normals = []\n self.__faceNormals = []\n self.__vertexNormals = []\n self.__textures = []\n self.__faceTextures = []\n self.__vertexTextures = []\n \n self.__loaded = {}\n\n def load_objs(self, assets_path):\n onlyfiles = [f for f in listdir(assets_path) if isfile(join(assets_path, f))]\n for file in onlyfiles:\n print(\"INCIO DE CARGA DE\", file)\n f = open(join(assets_path, file), \"r\")\n filename = file.split('.')[0]\n self.__name = filename\n file_lines = f.readlines()\n for line in file_lines:\n metadata = line.replace(\"\\n\", \"\").split(' ')\n line_type = metadata[0]\n line_info = metadata[1:]\n while(\"\" in line_info):\n line_info.remove('')\n self.__load_line(line_type, line_info)\n self.__eof()\n \n\n def __load_line(self, line_type, line):\n if (line_type == 'o'):\n self.__load_name(line)\n elif (line_type == 'v'):\n self.__load_vertex(line)\n elif (line_type == 'vn'):\n self.__load_vertexnormal(line)\n elif (line_type == 'vt'):\n self.__load_vertextexture(line)\n elif (line_type == 'f'):\n self.__load_face(line)\n elif (line_type == \"#\"):\n self.__comment(line)\n # print(\"El tipo de línea es:\", line_type)\n # types = {\n # 'o': self.__load_name(line),\n # 'v': self.__load_vertex(line),\n # 'f': self.__load_face(line),\n # '#': self.__eof(line)\n # }\n # return types.get(line_type, 'Invalid')\n \n def __load_name(self, line):\n #Carga del nombre\n self.__name = line[0]\n \n def __load_vertex(self, line):\n #Carga del vértice\n # self.__numVertx = self.__numVertx + 1\n #for value in line:\n self.__arrays = self.__arrays + [(float(line[0]), float(line[1]), float(line[2]))]\n\n def __load_vertexnormal(self, line):\n #Carga de normales de un vértice\n self.__normals = self.__normals + [(float(line[0]), float(line[1]), float(line[2]))]\n\n def __load_vertextexture(self, line):\n textureW = max(0, min(float(line[0]), 1))\n textureH = max(0, min(float(line[1]), 1))\n #Carga de texturas\n self.__textures = self.__textures + [(textureW, textureH)]\n\n def __load_face(self, line):\n #Carga de la cara\n # self.__numFaces = self.__numFaces + 1\n for face in line:\n if (\"/\" in face):\n faces = face.split('/')\n if (len(faces) > 2):\n self.__load_face_textures(faces)\n else:\n self.__load_face_normals(faces)\n else: \n for face in line:\n self.__elements = self.__elements + [(int(face) - 1)]\n self.__arrayElements = self.__arrayElements + [self.__arrays[int(face) - 1]]\n\n def __load_face_normals(self, faces):\n vertexFace = faces[0]\n normalFace = faces[1]\n\n #Carga de caras de vértices\n self.__elements = self.__elements + [(int(vertexFace) - 1)]\n self.__arrayElements = self.__arrayElements + [self.__arrays[int(vertexFace) - 1]]\n\n #Carga de caras de normales\n self.__faceNormals = self.__faceNormals + [(int(normalFace) - 1)]\n self.__vertexNormals = self.__vertexNormals + [self.__normals[int(normalFace) - 1]]\n\n def __load_face_textures(self, faces):\n vertexFace = faces[0]\n normalFace = faces[1]\n textureFace = faces[2]\n\n #Carga de caras de vértices\n self.__elements = self.__elements + [(int(vertexFace) - 1)]\n self.__arrayElements = self.__arrayElements + [self.__arrays[int(vertexFace) - 1]]\n\n #Carga de caras de normales\n self.__faceNormals = self.__faceNormals + [(int(normalFace) - 1)]\n self.__vertexNormals = self.__vertexNormals + [self.__normals[int(normalFace) - 1]]\n\n #Carga de texturas\n self.__faceTextures = self.__faceTextures + [(int(textureFace) - 1)]\n self.__vertexTextures = self.__vertexTextures + [self.__textures[int(textureFace) - 1]]\n \n def __comment(self, line):\n # Comentarios del archivo\n comment = \" \".join(line)\n print(\"COMENTARIO DEL ARCHIVO:\", comment)\n\n def __eof(self):\n #Revisión de última línea\n print(\"FIN DE CARGA DE ARCHIVO\")\n self.__save()\n\n def __save(self):\n # Guarda el objeto cargado\n print(\"GUARDANDO DATOS EN CLAVE:\", self.__name)\n self.__loaded.update({ \n self.__name: {\n \"Name\": self.__name,\n \"Arrays\": self.__arrays, \n \"Elements\": self.__elements, \n \"ArrayElements\": self.__arrayElements,\n \"Normals\": self.__normals,\n \"FaceNormals\": self.__faceNormals,\n \"VertexNormals\": self.__vertexNormals,\n \"Textures\": self.__textures,\n \"FaceTextures\": self.__faceTextures,\n \"VertexTextures\": self.__vertexTextures\n } \n })\n self.__reset()\n \n def __reset(self):\n # Reseteo de variables\n self.__name = \"\"\n\n self.__arrays = []\n self.__elements = []\n self.__arrayElements = [] # DrawArrays\n self.__normals = []\n self.__faceNormals = []\n self.__vertexNormals = []\n self.__textures = []\n self.__faceTextures = []\n self.__vertexTextures = []\n\n def get_obj(self, obj_name):\n # Obtención de un objeto guardado\n return self.__loaded[obj_name]\n\n def get_all(self):\n # Obtención de todas las keys\n return list(self.__loaded.keys())","sub_path":"handlers/objHandlerv3.py","file_name":"objHandlerv3.py","file_ext":"py","file_size_in_byte":6833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"465614767","text":"from account.models import Profile\n\nfrom tourney.models import City\nfrom ckeditor_uploader.widgets import CKEditorUploadingWidget\nfrom django import forms\nfrom .models import *\nfrom django.contrib import admin\n\n\nclass ArticleForm(forms.ModelForm):\n short_article = forms.CharField(widget=CKEditorUploadingWidget())\n article = forms.CharField(widget=CKEditorUploadingWidget())\n\n class Meta:\n model = Article\n fields = \"__all__\"\n\n\nclass ArticleAdmin(admin.ModelAdmin):\n form = ArticleForm\n list_display = ('title', \"author\", \"created_at\", \"type\", \"city\")\n\n def save_form(self, request, form, change):\n if request.user.is_staff and not request.user.is_superuser:\n if change:\n if \"city\" in form.initial:\n city_id = form.initial[\"city\"]\n city = City.objects.get(pk=city_id)\n form.instance.city_id = city_id\n form.instance.city = city\n else:\n form.instance.city_id = None\n form.instance.city = None\n\n if \"author\" in form.initial:\n user_id = form.initial[\"author\"]\n user = User.objects.get(pk=user_id)\n form.instance.author_id = user_id\n form.instance.author = user\n else:\n form.instance.author_id = None\n form.instance.author = None\n else:\n profile = Profile.objects.get(user=request.user)\n form.instance.city = profile.city\n if profile.city is not None:\n form.instance.city_id = profile.city.pk\n else:\n form.instance.city_id = None\n form.instance.author = request.user\n form.instance.author_id = request.user.pk\n return form.save(commit=False)\n\n def has_change_permission(self, request, obj=None):\n default_permission = super(ArticleAdmin, self).has_change_permission(request, obj)\n if request.user.is_superuser:\n return default_permission\n else:\n profile = Profile.objects.get(user=request.user)\n if obj is None or obj.city == profile.city:\n return default_permission\n else:\n return False\n\n def get_form(self, request, obj=None, **kwargs):\n if request.user.is_staff and not request.user.is_superuser:\n self.exclude = ('city', 'author',)\n form = super(ArticleAdmin, self).get_form(request, obj, **kwargs)\n return form\n\n def get_queryset(self, request):\n qs = super(ArticleAdmin, self).get_queryset(request)\n if request.user.is_superuser:\n return qs\n profile = Profile.objects.get(user=request.user)\n return qs.filter(city=profile.city)\n\n\nadmin.site.register(Article, ArticleAdmin)\n","sub_path":"apps/apps/news/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"652452049","text":"\nimport pandas as pd\n# Contenant l'algorithme du Truth Finder\nimport TruthFinder as tf \n\n\n# Majority vote \ndef majorityVote(dataframe,data_truth):\n dataframe[\"Object\"]=[str(x) for x in dataframe[\"Object\"]]\n dataframe[\"Property\"]=[str(x) for x in dataframe[\"Property\"]]\n dataframe[\"ObjectProperty\"] = dataframe[\"Object\"]+dataframe[\"Property\"]\n resultat = pd.DataFrame(columns=['Object','Property','Value'])\n u=0\n for o_p in dataframe[\"ObjectProperty\"].unique():\n indices = dataframe[\"ObjectProperty\"] == o_p\n df = dataframe.loc[indices]\n dic = dict(df.Value.value_counts())\n max_ = 0\n key = 0\n #print(dic)\n for i in range(len(dic)):\n if list(dic.values())[i] > max_:\n max_ = list(dic.values())[i]\n key = list(dic.keys())[i]\n resultat.loc[u] = [list(df.Object)[0],list(df.Property)[0],key]\n u+=1\n \n data_truth1 = tf.get_truth_to_dict(data_truth)\n resultat = tf.get_truth_to_dict(resultat)\n evaluation_r = tf.evaluation(data_truth1,resultat,dataframe)\n \n return evaluation_r\n\n\n\n# Compute the covrage of data\ndef get_cavrage(dataframe):\n total = 0\n manque = 0\n for o, df_object in dataframe.groupby(by=['Object']):\n nbr_source = len(df_object[\"Source\"].unique())\n nbr_property = len(df_object[\"Property\"].unique())\n nbr_data = df_object.shape[0]\n nbr_totale = nbr_source*nbr_property\n total +=nbr_totale\n manque += 1*(nbr_totale-nbr_data)\n return (1-manque/total)","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"580057523","text":"from appium import webdriver\nimport time\n\ndesired_caps = {}\ndesired_caps['platformName'] = 'Android' # 打开什么平台的app,固定的 > 启动安卓平台\ndesired_caps['platformVersion'] = '7.1.2' # 安卓系统的版本号:adb shell getprop ro.build.version.release\ndesired_caps['deviceName'] = 'V1938T' # 手机/模拟器的型号:adb shell getprop ro.product.model\ndesired_caps['appPackage'] = 'com.allsaprk.dh.allspark' # app的名字:\n # 安卓8.1之前:adb shell dumpsys activity | findstr \"mFocusedActivity\"\n # 安卓8.1之后:adb shell dumpsys activity | findstr \"mResume\"\ndesired_caps['appActivity'] = '.activity.LoginActivity' # 同上↑\ndesired_caps['unicodeKeyboard'] = True # 为了支持中文\ndesired_caps['resetKeyboard'] = True # 设置成appium自带的键盘\n# 去打开app,并且返回当前app的操作对象\ndriver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps) \n\ndriver.find_element_by_id('com.allsaprk.dh.allspark:id/et_user').send_keys('18408223928')\ndriver.find_element_by_id('com.allsaprk.dh.allspark:id/et_pass').send_keys('a12345678')\ndriver.find_element_by_id('com.allsaprk.dh.allspark:id/bt_login').click()\ntime.sleep(3)\n# 点击收索框\ndriver.find_element_by_id('com.allsaprk.dh.allspark:id/rl_right').click()\ntime.sleep(3)\n# 搜索框内输入a\ndriver.find_element_by_id('com.allsaprk.dh.allspark:id/et_search').send_keys('a')\n\ne =driver.find_element_by_android_uiautomator('new UiSelector().text(\"佛系投资\")')\nassert e.text==\"佛系投资\"\nprint(\"通过\")\n\n","sub_path":"AppiumTest1/test_02火种源.py","file_name":"test_02火种源.py","file_ext":"py","file_size_in_byte":1766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"464745175","text":"import parlai.core.build_data as build_data\nimport os\nfrom parlai.core.build_data import DownloadableFile\nimport copy\nimport json\nimport os\n\n\n\"\"\"\nFile added by Akshay which downloads the Twitter Customer Care dataset and creates a task\n\n\"\"\"\nRESOURCES = [\n DownloadableFile(\n 'https://raw.githubusercontent.com/AkshayAgarwal13/ParlAi_Test/main/train.txt',\n 'train.txt',\n '61fc2cd964fb935ea1cd736c149755495075695312ecc60b21eb10419f6b8ad7',\n zipped=False,\n ),\n\n DownloadableFile(\n 'https://raw.githubusercontent.com/AkshayAgarwal13/ParlAi_Test/main/valid.txt',\n 'valid.txt',\n '61fc2cd964fb935ea1cd736c149755495075695312ecc60b21eb10419f6b8ad7',\n zipped=False,\n ),\n\n DownloadableFile(\n 'https://raw.githubusercontent.com/AkshayAgarwal13/ParlAi_Test/main/test.txt',\n 'test.txt',\n '61fc2cd964fb935ea1cd736c149755495075695312ecc60b21eb10419f6b8ad7',\n zipped=False,\n ),\n]\n\n\ndef build(opt):\n dpath = os.path.join(opt['datapath'], 'Customer_Care')\n version = None\n\n if not build_data.built(dpath, version_string=version):\n print('[building data: ' + dpath + ']')\n if build_data.built(dpath):\n # An older version exists, so remove these outdated files.\n build_data.remove_dir(dpath)\n build_data.make_dir(dpath)\n\n # Download the data.\n for downloadable_file in RESOURCES[:3]:\n downloadable_file.download_file(dpath)\n\n # Mark the data as built.\n build_data.mark_done(dpath, version_string=version)","sub_path":"parlai/tasks/customer_care/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"26464093","text":"\"\"\"\nЗадание #1: Создайте структуру с именем student, содержащую поля: фамилия и инициалы, номер группы, успеваемость\n(массив из пяти элементов). Создать массив из десяти элементов такого типа, упорядочить записи по возрастанию среднего\nбалла. Добавить возможность вывода фамилий и номеров групп студентов, имеющих оценки, равные только 4 или 5.\n\"\"\"\nimport re\nfrom typing import List\n\n\nclass Student:\n def __init__(self, name: str, group_number: str, grades: List[int]):\n self.name = name\n self.group_number = group_number\n self.grades = grades\n\n regular_name = '[А-Я][а-я]{1,20}\\s[А-Я]\\.[А-Я]\\.'\n reg_name = re.compile(regular_name)\n\n @property\n def name(self):\n return self._name\n\n @name.setter\n def name(self, value, reg_name=reg_name):\n if isinstance(value, str) and reg_name.findall(value):\n self._name = value\n else:\n raise ValueError('name должен быть типом данных str и записан в формате Фамилия И.О.')\n\n @property\n def group_number(self):\n return self._group_number\n\n @group_number.setter\n def group_number(self, group):\n if isinstance(group, str):\n self._group_number = group\n else:\n raise ValueError('group_number должен быть типом данных str')\n\n @property\n def grades(self):\n return self._grades\n\n @grades.setter\n def grades(self, values):\n if isinstance(values, list) and len(values) == 5:\n for value in values:\n if 0 < value < 6:\n self._grades = values\n else:\n raise ValueError('grades must be 1-5')\n else:\n raise ValueError('grades должен быть типом данных list с длиной 5')\n\n def __lt__(self, other):\n return sum(self.grades) < sum(other.grades)\n\n\ndef show_students():\n for j in range(len(students)):\n print(f\"ФИО: {students[j].name}, \"\n f\"Группа: {students[j].group_number}, \"\n f\"Оценки: {[x for x in students[j].grades]}\\n\")\n\n\ndef sort_by_average_score():\n students.sort()\n show_students()\n\n\ndef show_good_students():\n bad_grades = [1, 2, 3]\n for j in students:\n for value in j.grades:\n if value in bad_grades:\n break\n else:\n print(f\"{j.name}\")\n\n\nstudents = []\n\nif __name__ == '__main__':\n for i in range(0, 4):\n students_name = input(f'Введите для {i+1}-го ученика ФИО: ')\n students_group = input(f\"Введите для {i+1}-го ученика группу: \")\n students_grades = [int(input(f'Введите {x+1}-ую оценку от 1 до 5: ')) for x in range(0, 5)]\n students.append(Student(students_name, students_group, students_grades))\n\n show_students()\n\n while True:\n controls = input(\"1 - упорядочить записи по возрастанию среднего балла учеников\\n\"\n \"2 - показать учеников, у которых оценки 4, 5\\n\"\n \"0 - выйти из программы\\n-->\")\n if controls == '1':\n sort_by_average_score()\n elif controls == '2':\n show_good_students()\n elif controls == '0':\n exit()\n else:\n print(\"Нет такого действия!\")\n\n\n\"\"\"\nЗадание #2: Создайте структуру с именем train, содержащую поля: название пункта назначения, номер поезда, время\nотправления. Ввести данные в массив из пяти элементов типа train, упорядочить элементы по номерам поездов. Добавить\nвозможность вывода информации о поезде, номер которого введен пользователем. Добавить возможность сортировки массив по\nпункту назначения, причем поезда с одинаковыми пунктами назначения должны быть упорядочены по времени отправления.\n\"\"\"\n\n\nclass Train:\n def __init__(self, destination, train_number, departure_time):\n self.destination = destination\n self.train_number = train_number\n self.departure_time = departure_time\n\n @property\n def destination(self):\n return self._destination\n\n @destination.setter\n def destination(self, value):\n if isinstance(value, str):\n self._destination = value\n else:\n raise ValueError('destination должен быть типом данных str')\n\n @property\n def train_number(self):\n return self._train_number\n\n @train_number.setter\n def train_number(self, value):\n if isinstance(value, int):\n self._train_number = value\n else:\n raise ValueError('train_number должен быть типом данных int')\n\n @property\n def departure_time(self):\n return self._departure_time\n\n @departure_time.setter\n def departure_time(self, value):\n if isinstance(value, str):\n self._departure_time = value\n else:\n raise ValueError('departure_time должен быть типом данных str')\n\n def __lt__(self, other):\n return self.train_number < other.train_number\n\n\ntrains = []\ndestination_list = []\n\n\ndef sort_by_train_number():\n trains.sort()\n for j in range(len(trains)):\n print(f\"Номер поезда: {trains[j].train_number}, \"\n f\"отправка: {trains[j].departure_time}, \"\n f\"пункт назначения: {trains[j].destination}\\n\")\n\n\ndef sort_by_destination():\n sort_list = sorted(trains, key=lambda x: (x.destination[0], x.departure_time[0]))\n for j in range(len(sort_list)):\n print(f\"Номер поезда: {sort_list[j].train_number}, \"\n f\"отправка: {sort_list[j].departure_time}, \"\n f\"пункт назначения: {sort_list[j].destination}\\n\")\n\n\nif __name__ == '__main__':\n # train1 = Train('Lviv', 253, '18.40')\n # train2 = Train('Kyiv', 19, '12.30')\n # train3 = Train('Odesa', 456, '09.40')\n # train4 = Train('Rivne', 753, '20.10')\n # train5 = Train('Kyiv', 45, '06.35')\n #\n # trains = [train1, train2, train3, train4, train5]\n\n for i in range(0, 5):\n trains_destination = input(f'Введите для {i}-го поезда пункт назначения: ')\n trains_number = int(input(f'Введите для {i}-го поезда его номер: '))\n trains_departure_time = input(f'Введите для {i}-го поезда время отправления: ')\n trains.append(Train(trains_destination, trains_number, trains_departure_time))\n\n for i in range(len(trains)):\n print(f\"Номер поезда: {trains[i].train_number}, \"\n f\"отправка: {trains[i].departure_time}, \"\n f\"пункт назначения: {trains[i].destination}\\n\")\n\n while True:\n controls = input(\"1 - посмотреть информацию о поезде\\n\"\n \"2 - отсортировать поезда по номерам\\n\"\n \"3 - отсортировать поезда по пунктам назначения\\n\"\n \"0 - выйти из программы\\n-->\")\n if controls == '1':\n number_of_train = input(\"Введите номер поезда, ��тоб узнать о нем информацию: \")\n for i in range(len(trains)):\n if trains[i].train_number == int(number_of_train):\n print(f\"Номер поезда: {trains[i].train_number}, \"\n f\"отправка: {trains[i].departure_time}, \"\n f\"пункт назначения: {trains[i].destination}\\n\")\n elif controls == '2':\n sort_by_train_number()\n elif controls == '3':\n sort_by_destination()\n elif controls == '0':\n exit()\n else:\n print(\"Нет такого действия!\")\n\n\"\"\"\nЗадание #3:\nСоздайте класс Грузовик\nУ которого есть параметры Марка, год производства, максимальная скорость и кол-во км сколько ему нужно проехать\nКласс должен уметь:\n - получать марку, год производства грузовика\n - получать за какое время грузовик проедет заданное количество км\n\"\"\"\n\n\nclass Truck:\n def __init__(self, model, year, speed, distance):\n self.model = model\n self.year = year\n self.speed = speed\n self.distance = distance\n\n def get_info(self):\n print(f'{self.model}, год {self.year}')\n\n def get_time(self):\n print(f'Грузовик {self.model} проедет заданное количество км за {self.distance/self.speed} ч')\n\n\nmodel_truck_1 = input(\"Введите модель грузовика: \")\nyear_truck_1 = int(input(\"Введите год производства грузовика: \"))\nspeed_truck_1 = int(input(\"Введите максимальную скорость: \"))\ndistance_truck_1 = int(input(\"Введите дистанцию, которую он должен проехать в км: \"))\n\ntruck_1 = Truck(model_truck_1, year_truck_1, speed_truck_1, distance_truck_1)\ntruck_1.get_info()\ntruck_1.get_time()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"13476792","text":"from django.urls import path, re_path\n\nfrom . import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path(\"\", views.index, name=\"index\"),\n path(\"login\", views.login_view, name=\"login\"),\n path(\"logout\", views.logout_view, name=\"logout\"),\n path(\"register\", views.register, name=\"register\"),\n path(\"create_list\", views.newlist, name=\"newlist\"),\n re_path(r'^categories/(?P\\w+)/$', views.categories, name=\"categories\"),\n path(\"view//\", views.viewdetail, name=\"details\"),\n path(\"status//\", views.savestatus, name=\"savestatus\"),\n path(\"watchlist\", views.watchlist, name=\"watchlist\"),\n path(\"watchlist-hangle/\", views.watchlist_handle, name=\"watchlist_handle\"),\n # path(\"watchlist_add/\", views.watchlist_add, name=\"watchlist_add\"),\n # path(\"watchlist_remove/\", views.watchlist_remove, name=\"watchlist_remove\"),\n path(\"comment/\", views.comments, name=\"comments\"),\n path(\"view-from-watchlist/\", views.viewfromwatchlist, name=\"viewfromwatchlist\"),\n] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n","sub_path":"fullstack/showcase/level1/commerce/auctions/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"576198095","text":"try:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\nconfig = {\n 'description':'Chores manager for Bridge Rd',\n 'author':'aphid',\n 'url':'URL to get it at',\n 'download_url':'Where to download it',\n 'author_email':'wbchilds@gmail.com',\n 'version':'1.0',\n 'install_requires':['nose'],\n 'packages':['chores'],\n 'scripts':[],\n 'name':'chores'\n}\n\nsetup(**config)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"614078580","text":"\"\"\"Derivation of variable `rsns`.\"\"\"\n\nfrom iris import Constraint\n\nfrom ._derived_variable_base import DerivedVariableBase\n\n\nclass DerivedVariable(DerivedVariableBase):\n \"\"\"Derivation of variable `rsns`.\"\"\"\n\n # Required variables\n _required_variables = {\n 'vars': [{\n 'short_name': 'rsds',\n 'field': 'T2{frequency}s'\n }, {\n 'short_name': 'rsus',\n 'field': 'T2{frequency}s'\n }]\n }\n\n def calculate(self, cubes):\n \"\"\"Compute surface net downward shortwave radiation.\"\"\"\n rsds_cube = cubes.extract_strict(\n Constraint(name='surface_downwelling_shortwave_flux_in_air'))\n rsus_cube = cubes.extract_strict(\n Constraint(name='surface_upwelling_shortwave_flux_in_air'))\n\n rsns_cube = rsds_cube - rsus_cube\n\n return rsns_cube\n","sub_path":"esmvaltool/preprocessor/_derive/rsns.py","file_name":"rsns.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"582220738","text":"from js9 import j\n\nJSBASE = j.application.jsbase_get_class()\n\n\nclass Config(JSBASE):\n\n def __init__(self, instance=\"main\", location=None, template=None, data={}):\n \"\"\"\n jsclient_object is e.g. j.clients.packet.net\n \"\"\"\n\n JSBASE.__init__(self)\n\n self.location = j.data.text.toStr(location)\n self.instance = j.data.text.toStr(instance)\n self.error = False # if this is true then need to call the configure part\n self._template = template\n if not j.data.types.string.check(template):\n if template is not None:\n raise RuntimeError(\"template needs to be None or string:%s\"%template)\n if self.instance is None:\n raise RuntimeError(\"instance cannot be None\")\n\n self.reset()\n if not j.sal.fs.exists(self.path):\n j.sal.fs.createDir(j.sal.fs.getDirName(self.path))\n self.new = True\n dataOnFS = {}\n else:\n self.load()\n # this is data on disk, because exists, should already apply to template\n # without decryption so needs to go to self._data\n dataOnFS = self.data # now decrypt\n\n # make sure template has been applied !\n data2, error = j.data.serializer.toml.merge(tomlsource=self.template, tomlupdate=dataOnFS, listunique=True)\n\n if data != {}:\n # update with data given\n data, error = j.data.serializer.toml.merge(tomlsource=data2, tomlupdate=data, listunique=True)\n self.data = data\n else:\n # now put the data into the object (encryption)\n self.data = data2\n\n # do the fancydump to make sure we really look at differences\n if j.data.serializer.toml.fancydumps(self.data) != j.data.serializer.toml.fancydumps(dataOnFS):\n self.logger.debug(\"change of data in config, need to save\")\n self.save()\n\n def reset(self):\n self._data = {}\n self.loaded = False\n self._path = None\n self._nacl = None\n self.new = False\n\n @property\n def path(self):\n self.logger.debug(\"init getpath:%s\" % self._path)\n if not self._path:\n self._path = j.sal.fs.joinPaths(j.data.text.toStr(j.tools.configmanager.path), self.location, self.instance + '.toml')\n self.logger.debug(\"getpath:%s\" % self._path)\n return self._path\n\n @property\n def nacl(self):\n if not self._nacl:\n if j.tools.configmanager.keyname:\n self._nacl = j.data.nacl.get(sshkeyname=j.tools.configmanager.keyname)\n else:\n self._nacl = j.data.nacl.get()\n return self._nacl\n\n def instance_set(self, instance):\n \"\"\"\n will change instance name & delete data\n \"\"\"\n self.instance = instance\n self.load(reset=True)\n\n def load(self, reset=False):\n \"\"\"\n @RETURN if 1 means did not find the toml file so is new\n \"\"\"\n if reset or self._data == {}:\n if not j.sal.fs.exists(self.path):\n raise RuntimeError(\"should exist at this point\")\n else:\n content = j.sal.fs.fileGetContents(self.path) \n try:\n self._data = j.data.serializer.toml.loads(content)\n except Exception as e:\n if \"deserialization failed\" in str(e):\n raise RuntimeError(\"config file:%s is not valid toml.\\n%s\"%(self.path,content))\n raise e \n for key, val in self.template.items():\n ttype = j.data.types.type_detect(self.template[key])\n if ttype.BASETYPE == \"string\":\n if key in self._data:\n self._data[key] = self._data[key].strip()\n\n def save(self):\n # at this point we have the config & can write (self._data has the encrypted pieces)\n j.sal.fs.writeFile(\n self.path, j.data.serializer.toml.fancydumps(self._data))\n\n def delete(self):\n j.sal.fs.remove(self.path)\n\n @property\n def template(self):\n if self._template is None or self._template == '':\n obj = eval(self.location)\n if hasattr(obj,\"_child_class\"):\n obj._child_class\n myvars={}\n try:\n exec(\"from %s import TEMPLATE;template=TEMPLATE\"%obj._child_class.__module__,myvars)\n except Exception as e:\n if \"cannot import name\" in str(e):\n raise RuntimeError(\"cannot find TEMPLATE in %s, please call the template: TEMPLATE\"%obj._child_class.__module__)\n raise e \n else:\n myvars={}\n try:\n exec(\"from %s import TEMPLATE;template=TEMPLATE\"%obj.__module__,myvars)\n except Exception as e:\n if \"cannot import name\" in str(e):\n raise RuntimeError(\"cannot find TEMPLATE in %s, please call the template: TEMPLATE\"%obj._child_class.__module__)\n raise e\n self._template = myvars[\"template\"]\n if j.data.types.string.check(self._template):\n try:\n self._template = j.data.serializer.toml.loads(self._template)\n except Exception as e:\n if \"deserialization failed\" in str(e):\n raise RuntimeError(\"config file:%s is not valid toml.\\n%s\"%(self.path,self._template))\n raise e \n\n return self._template\n\n @property\n def data(self):\n res = {}\n if self._data == {}:\n self.load()\n for key, item in self._data.items():\n if key not in self.template:\n self.logger.warning(\"could not find key:%s in template, while it was in instance:%s\"%(key,self.path))\n self.logger.debug(\"template was:%s\\n\"%self.template)\n self.error=True\n else:\n ttype = j.data.types.type_detect(self.template[key])\n if key.endswith(\"_\"):\n if ttype.BASETYPE == \"string\":\n if item != '' and item != '\"\"':\n res[key] = self.nacl.decryptSymmetric(item, hex=True).decode()\n else:\n res[key] = ''\n else:\n res[key] = item\n else:\n res[key] = item\n return res\n\n @data.setter\n def data(self, value):\n if j.data.types.dict.check(value) is False:\n raise TypeError(\"value needs to be dict\")\n\n changed = False\n for key, item in value.items():\n ch1 = self.data_set(key, item, save=False)\n changed = changed or ch1\n\n if changed:\n # raise RuntimeError()\n self.logger.debug(\"changed:\\n%s\" % self)\n self.save()\n\n def data_set(self, key, val, save=True):\n if key not in self.template:\n raise RuntimeError(\n \"Cannot find key:%s in template for %s\" % (key, self))\n\n if key not in self._data or self._data[key] != val:\n ttype = j.data.types.type_detect(self.template[key])\n if key.endswith(\"_\"):\n if ttype.BASETYPE == \"string\":\n if val != '' and val != '\"\"':\n val = self.nacl.encryptSymmetric(val, hex=True, salt=val)\n if key in self._data and val == self._data[key]:\n return False\n self._data[key] = val\n if save:\n self.save()\n return True\n else:\n return False\n\n @property\n def yaml(self):\n return j.data.serializer.toml.fancydumps(self._data)\n\n def __str__(self):\n out = \"config:%s:%s\\n\\n\" % (self.location, self.instance)\n out += j.data.text.indent(self.yaml)\n return out\n\n __repr__ = __str__\n","sub_path":"JumpScale9/tools/configmanager/Config.py","file_name":"Config.py","file_ext":"py","file_size_in_byte":8072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"228845858","text":"class Rectangulo():\n base=0\n altura=0\n def __init__(self,x,y):\n self.base=x\n self.altura=y\n def superficie(self):\n return (self.base*self.altura)\n\nx=Rectangulo(int(input('ingrese base: ')),int(input('ingrese altura: ')))\n\nprint(x.superficie())\n","sub_path":"TP2/Ejercicio1.py","file_name":"Ejercicio1.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"100198941","text":"from token import Token, TokenType\nimport units\n\nclass Lexer:\n\tdef __init__(self, stream):\n\t\tself.stream = stream\n\t\tself.token_putback = None\n\n\tdef getToken(self):\n\t\tif self.token_putback is not None:\n\t\t\ttoken = self.token_putback\n\t\t\tself.token_putback = None\n\t\t\treturn token\n\n\t\treturn self.getNextToken()\n\n\tdef ungetToken(self, token):\n\t\t# maintain efficiency O(n)\n\t\tif self.token_putback is not None:\n\t\t\traise RuntimeError(\"fatal: ungetToken() called more than once\")\n\n\t\tself.token_putback = token\n\n\tdef peekToken(self):\n\t\tif self.token_putback is not None:\n\t\t\treturn self.token_putback\n\n\t\ttoken = self.getToken()\n\t\tself.ungetToken(token)\n\t\treturn token\n\n\tdef getNextToken(self):\n\t\twhile True:\n\t\t\tch = self.stream.get()\n\t\t\tif ch is None:\n\t\t\t\tbreak\n\n\t\t\tif ch == \" \" or ch == \"\\t\":\n\t\t\t\tcontinue\n\t\t\tif ch == \"+\":\n\t\t\t\treturn Token(TokenType.PLUS, \"\", self.stream.tell())\n\t\t\tif ch == \"-\":\n\t\t\t\treturn Token(TokenType.MINUS, \"\", self.stream.tell())\n\t\t\tif ch == \"^\":\n\t\t\t\treturn Token(TokenType.CARET, \"\", self.stream.tell())\n\t\t\tif ch.isdigit():\n\t\t\t\tchar = self.stream.tell()\n\t\t\t\ts = ch\n\n\t\t\t\twhile True:\n\t\t\t\t\tch = self.stream.get()\n\t\t\t\t\tif ch is None:\n\t\t\t\t\t\tbreak\n\t\t\t\t\tif ch.isdigit():\n\t\t\t\t\t\ts += ch\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.stream.unget()\n\t\t\t\t\t\tbreak\n\n\t\t\t\treturn Token(TokenType.ICONST, s, char)\n\t\t\tif ch == \".\":\n\t\t\t\treturn Token(TokenType.PERIOD, \"\", self.stream.tell())\n\t\t\tif ch == \",\":\n\t\t\t\treturn Token(TokenType.COMMA, \"\", self.stream.tell())\n\t\t\tif self.isStartUnitChar(ch):\n\t\t\t\tif ch == \"E\" or ch == \"e\":\n\t\t\t\t\tpeek = self.stream.peek()\n\t\t\t\t\tif peek is not None and not peek.isalpha():\n\t\t\t\t\t\treturn Token(TokenType.ENOT, ch, self.stream.tell())\n\n\t\t\t\tchar = self.stream.tell()\n\t\t\t\ts = ch\n\n\t\t\t\twhile True:\n\t\t\t\t\tch = self.stream.get()\n\t\t\t\t\tif ch is None:\n\t\t\t\t\t\t#if it's a start unit char, but not end unit char\n\t\t\t\t\t\tif not self.isEndUnitChar(s[-1]):\n\t\t\t\t\t\t\ts = s[:-1]\n\t\t\t\t\t\t\tself.stream.unget()\n\t\t\t\t\t\tbreak\n\n\t\t\t\t\tif self.isUnitChar(ch):\n\t\t\t\t\t\ts += ch\n\t\t\t\t\telse:\n\t\t\t\t\t\t#if it's a start unit char, but not end unit char\n\t\t\t\t\t\tif not self.isEndUnitChar(s[-1]):\n\t\t\t\t\t\t\ts = s[:-1]\n\t\t\t\t\t\t\tself.stream.unget()\n\t\t\t\t\t\tself.stream.unget()\n\t\t\t\t\t\tbreak\n\n\t\t\t\treturn Token(TokenType.SCONST, s, char)\n\t\t\tif ch== \"⋅\":\n\t\t\t\treturn Token(TokenType.DOT, \"\", self.stream.tell())\n\t\t\tif ch == \"/\":\n\t\t\t\treturn Token(TokenType.SLASH, \"\", self.stream.tell())\n\n\t\t\treturn Token(TokenType.ERR, ch, self.stream.tell())\n\t\treturn Token(TokenType.DONE, \"\", self.stream.tell())\n\n\t@staticmethod\n\tdef isStartUnitChar(ch):\n\t\treturn ch.isalpha() or ch in units.start_unitsymbols\n\n\t@staticmethod\n\tdef isUnitChar(ch):\n\t\treturn ch.isalpha() or ch in units.start_unitsymbols or ch in units.middle_unitsymbols or ch in units.end_unitsymbols\n\n\t@staticmethod\n\tdef isEndUnitChar(ch):\n\t\treturn ch.isalpha() or ch in units.end_unitsymbols\n","sub_path":"lexer.py","file_name":"lexer.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"364527966","text":"'''\nContext Manager\n__enter__, __exit__, exception\n\n원하는 타이밍에 정확하게 리소스를 할당 및 제공, 반환하는 역할\nwith 문에 사용 가능\n'''\n\n# ex1\n\nfile = open('./testfile1.txt', 'w')\ntry:\n file.write('context manager test1\\n contextlib test1')\nfinally:\n file.close()\n \n \n# ex2\n\nwith open('./testfile2.txt', 'w') as f:\n f.write('context manager test2\\n contextlib test2')\n \n\n \n# ex3 class 형태로 구현\n\nclass MyFileWriter():\n def __init__(self, file_name, method):\n print('MyFileWriter started : __init__')\n self.file_obj = open(file_name, method)\n \n def __enter__(self):\n print('MyFileWriter started : __enter__')\n return self.file_obj\n \n def __exit__(self, exc_type, value, trace_back) :\n print('MyFileWriter started : __exit__')\n if exc_type :\n print(f'Logging exception {(exc_type, value, trace_back)}')\n self.file_obj.close()\n\nwith MyFileWriter('./testfile3.txt', 'w') as f :\n # as f 에서 __enter__ 실행\n f.write('context manager test3\\n contextlib test3')\n # with 문이 끝나면 __exit__ 실행\n\n\n\n\n","sub_path":"python_base/closure/context_manager.py","file_name":"context_manager.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"582998476","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 2 13:11:59 2017\n\n@author: RD1874\n\"\"\"\nfrom Data_treatment import convert_time_data\nfrom Data_treatment import data\nfrom Alea_model import alea_model\n#from Show_result import show \n\nfilepath='data'\n#Start data _learn \ndays=0\nhours=0\nminutes=0\nstart_learn=convert_time_data(days,hours,minutes)\n\n#Learn Time data < 1ans\ndays=60\nhours=0\nminutes=0\nTime_data_learn=convert_time_data(days,hours,minutes)\n\n\n\n#Time step\ndays=0\nhours=0\nminutes=10\nTime_step=convert_time_data(days,hours,minutes)\n\n\nInputs_TANK = []\nOutput_TANK = 'P_elec_PAC_DHW'\n\npreprocessing='P_TANK'\nclass_Data=data(Inputs_TANK,Output_TANK,start_learn,filepath,preprocessing,Time_data_learn)\n\n\n#load Output\nInputs=False\nOutput=True\nData_learn_Output=class_Data.get_data_learn(Time_step,Inputs,Output)\n\nseason_time=int(24*60/Time_step)\nweek=int(24*60/Time_step)\nName='features_Tank'\n\n\n\"\"\"\n#show prediction\ninterval_prediction=5\n#Title xlabel, ylabel\nlegend_prediction=['electric Power Tank Temperatures Prediction','Times in hours','electric power Tank in Watt']\n\nfilepath_figure='/features/'\n#Show residus\ninterval_residus=2\nextrema_residus=1\n#Title xlabel, ylabel\nlegend_residus=['Error of prediction' ,'Times in hours','Residus']\n\nshow_month=['January','February','March','April','May'\\\n ,'June','July','August','September','October'\\\n ,'November','December']\n\n\n#estimate_number_show=len(show_month)-network_P_TANK.predict)/pictures_freq\n#print(estimate_number_show)\n\nshow_result=show(filepath_figure,legend=legend_prediction,show_month=show_month,Time_step=Time_step,\\\n predict=season_time,start_learn=0\\\n ,size_learn=int(Time_data_learn/Time_step),interval=interval_prediction,\\\n pictures_freq=1,extrema_residus=extrema_residus,legend_residus=legend_residus,\\\n interval_residus=interval_residus)\n\"\"\"\n\nmodel=alea_model(Name,season_time,season_time)\nnew_data=model.model_P_tank_data(Data_learn_Output)\n\n\n\n","sub_path":"Test_alea_model.py","file_name":"Test_alea_model.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"520168086","text":"import os\nimport matplotlib.pyplot as plt\n\nlabels = [file for file in os.listdir() if file.startswith('results_') and file.endswith('.txt')]\n\nlabel_dict = {}\n\nfor file in labels:\n with open(file, 'r') as f:\n for line in f:\n a, b = line.split(' ')[:2]\n b = b.strip('\\n')\n if b not in label_dict:\n label_dict[b] = [a]\n else:\n label_dict[b].append(a)\n\nlabels = []\nlengths = []\nfor k, v in label_dict.items():\n labels.append(k)\n lengths.append(len(v))\n\nplt.bar(labels, lengths)\nplt.xlabel('Label')\nplt.ylabel('Number of images')\nplt.show()\n","sub_path":"CV/utils/extras.py","file_name":"extras.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"620706088","text":"import numpy as np\n\nxarr = np.array([1.1, 1.2, 1.3, 1.4, 1.5])\nyarr = np.array([2.1, 2.2, 2.3, 2.4, 2.5])\ncond = np.array([True, False, True, True, False])\n\n# 透過cond選取xarr 或 yarr的一般條件式寫法\nresult = [(x if c else y) for x, y, c in zip(xarr, yarr, cond)]\nprint(result)\n\n# 透過np.where的簡潔撰寫方式\nresult = np.where(cond, xarr, yarr)\nprint(result)\n\n# 進一步解釋 np.where\narr = np.random.randn(4, 4)\nprint(arr)\nprint(arr > 0)\n\nresult = np.where(arr > 0, 2, -2)\nprint(result)\n\nresult = np.where(arr > 0, 2, arr) # set only positive values to 2\nprint(result)\n","sub_path":"E01_python_for_data_analysis/04_NumPy/0411_numpy_where.py","file_name":"0411_numpy_where.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"563705360","text":"# Copyright 2018 Otis Elevator Company. All rights reserved.\r\n# Use of this source code is govered by the MIT license which\r\n# can be found in the LICENSE file.\r\n\r\n# Author: Jeremy Mill: jeremy.mill@otis.com\r\n\r\n# Otis udp_rx software has been designed to utilize information\r\n# security technology described Part 774 of the EAR Category 5 Part 2\r\n# but has been made publicly available in accordance with Part 742.15(b)\r\n# and is therefore not subject to U.S. export regulations.\r\n# Before you download this software be aware that the country in which you\r\n# are located may have restrictions related to the import, possession, use\r\n# and/or reexport of encryption items. It is your responsibility to comply\r\n# with any applicable laws and regulations pertaining the import, possession,\r\n# use and/or reexport of encryption items.\r\n\r\n'''This script is for testing udp_rx receive side functionality on windows'''\r\n\r\nimport socket\r\n\r\nUDP_IP = \"\"\r\nUDP_PORT = 50300\r\n\r\nsock = socket.socket(socket.AF_INET, # Internet\r\n socket.SOCK_DGRAM) # UDP\r\nsock.bind((UDP_IP, UDP_PORT))\r\n\r\nprint(\"python - sockets built\\n\")\r\ncounter = 0\r\nwhile True:\r\n print(\"python - awaiting new connection...\")\r\n data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes\r\n counter += 1\r\n print(\"python - \", counter)\r\n print(\"python - received message: {}\\tfrom: {}\".format(data, addr))","sub_path":"python_helpers/win_rx_udp.py","file_name":"win_rx_udp.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"270007913","text":"import pathlib\nimport collections\n\n\n\"\"\" Constants that are predefined and should not be changed during normal operations\"\"\"\n\n# Path constants relative to this file's location\n\n# Path to the base folder\nROOT = pathlib.Path(__file__).parent.parent\n\nBIN = ROOT / \"bin\" # Bash scripts\nCONFIG = ROOT / \"config\" # Config files\n\n# Mosquitto config paths\n_mosquitto_config_key = [\"ABS\", \"LOCAL\"]\n_mosquitto_config_tuple = collections.namedtuple(\"mosquitto_config\", _mosquitto_config_key)\n\n_abs_config = pathlib.Path('/etc/mosquitto/mosquitto.conf') # Default mosquitto.conf file\n_local_config = CONFIG / \"mosquitto\" # Directory in which local .conf files are located\n\nMOSQUITTO = _mosquitto_config_tuple(ABS=_abs_config, LOCAL=_local_config)","sub_path":"PyMosq/constants/path.py","file_name":"path.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"43522880","text":"import json\nimport redis\nimport time\n\nif __name__ == '__main__':\n\n DEBUG_UPLOAD_LIMIT = 1000\n\n r = redis.StrictRedis(host='localhost', port=6379, db=0)\n\n print('Upload json as true-string.')\n with open('data.json', encoding='cp1251') as input_file:\n test_data = json.load(input_file)\n count = len(test_data)\n start = time.time()\n\n index = 0 # не надо эту строку в коде, это для интерпритатора PyCharm\n for index, data in enumerate(test_data):\n if DEBUG_UPLOAD_LIMIT and index == DEBUG_UPLOAD_LIMIT:\n break\n # r.set('data:%s' % index, str(data).lower())\n # value = str(data).lower().encode('cp1251').decode('iso-8859-1')\n value = str(data).lower().encode('utf-8')\n r.set('obj:%s' % index, value)\n r.save()\n\n end = time.time()\n print('\\t', 'Were upload:', index, 'units')\n print('\\t', 'Time left:', end - start, 'sec')\n","sub_path":"011.files/upload_as_string.py","file_name":"upload_as_string.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"555289816","text":"Import('env')\n\npre_nodelist = env.Command(\n target='#src/Makefile',\n source=['#src/Makefile.in'],\n action='echo \"aaa\" > ${TARGET}')\n\nif env['PLATFORM'] == 'local':\n nodelist = env.Command(\n target='#${PLATFORM}/out/aaa',\n source=['#src/x.file'],\n action='''\necho \"build PLATFORM=$PLATFORM in `pwd`\"\necho aaa > ${TARGET.dir}/aaa\necho yyy > src/y.file\necho zzz > src/z.file\n''')\nelse:\n nodelist = env.Command(\n target='#${PLATFORM}/out/aaa',\n source=['#src/x.file'],\n action='''\necho \"build PLATFORM=$PLATFORM in `pwd`\"\ncat src/* > ${TARGET.dir}/aaa\n''')\n\nif env['PLATFORM'] == 'local':\n env.SideEffect('#src/y.file', nodelist)\n env.SideEffect('#src/z.file', nodelist)\nelse:\n env.Depends(nodelist, '#src/y.file')\n env.Depends(nodelist, '#src/z.file')\n\nnodelist2 = env.Command(\n target='out/bbb',\n source='src/b.file',\n action='echo \"bbb in `pwd` target=${TARGET} source=${SOURCE.dir}\"')\nenv.Depends(nodelist2, nodelist)\n#env.AlwaysBuild(nodelist2)\n","sub_path":"SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"55608987","text":"import sys\n#sys.path.append(\"\"\"/config.json\"\"\")\n### In future, JSconfig needed for authentication of credential to GCS\nfrom UploadToGCP import uploadBlob\nfrom DownloadFromGCP import downloadBlob\nfrom ramandataingest import spcToJsonConverter\nfrom ramandataingest import directoryContainingSpcFiles\nfrom gcstobigquery import gcstoBigQuery\n#Libraries needed to Run the Function\nfrom google.cloud import storage\nfrom google.cloud import storage\nimport spc\nimport json\nimport os\nimport logging\nimport pandas as pd\nfrom datetime import datetime\nfrom log import log\n\nlog_path = os.getcwd()\ndatestring = datetime.strftime(datetime.now(), '%Y_%m_%d')\nlog_file_name = str(log_path)+'\\log\\MainLogs'+'_'+str(datestring)+'.log'\nlogging.basicConfig(filename=log_file_name,level=logging.INFO,format=\"%(asctime)s:%(levelname)s,%(lineno)d:%(name)s.%(funcName)s:%(message)s\")\nlogging.info('Logging Started')\nprint(\"...files are getting logged...\")\n\n#Default config\nconfig = {\n #Input Location\n 'Input_Environment_Type':\"gcs\",\n 'Input_Environment_Location':\"raw-raman-spc\",\n #InterMediary Location\n 'Required':\"yes\",\n 'No_Of_Intermediates':\"2\",\n 'Intermediary_Environment_Type':\"local,gcs\",\n 'Intermediary_Environment_Location':\"test_data,sample-json-files\",\n #OutPut Location\n 'Output_Environment_Type':\"bigquery\",\n 'Output_Environment_Location':\"poms_ds\" \n}\n\ndef main():\n\n #Recording logging data\n # log_path = os.getcwd()\n # log(log_path)\n\n#need to comment it from 49-64\n Process_Control= {\n \"Input_Environment\": {\n 'Type': os.getenv(\"Input_Environment_Type\"), #Possible Values bigquery,gcs,local\n 'Location': os.getenv(\"Input_Environment_Location\")\n },\n \"Intermediary_Environment\":{\n 'Required': os.getenv(\"Required\"),# Possible Values Yes/No\n 'No_Of_Intermediates': os.getenv(\"No_Of_Intermediates\"), #Possible Values 0,1,2. For now 2 is max limit\n 'Type': os.getenv(\"Intermediary_Environment_Type\").split(','), #[###could be array of strings.],\n 'Location': os.getenv(\"Intermediary_Environment_Location\").split(',') #[###could be array of strings.]\n },\n \"Output_Environment\": {\n 'Type': os.getenv(\"Output_Environment_Type\"),\n 'Location': os.getenv(\"Output_Environment_Location\")\n },\n }\n\n config['Input_Environment_Type']= os.getenv(\"Input_Environment_Type\")\n config['Input_Environment_Location'] = os.getenv(\"Input_Environment_Location\")\n #InterMediary Location\n config['Required'] = os.getenv(\"Required\")\n config['No_Of_Intermediates'] = os.getenv(\"No_Of_Intermediates\")\n config['Intermediary_Environment_Type'] = os.getenv(\"Intermediary_Environment_Type\").split(',')\n config['Intermediary_Environment_Location'] = os.getenv(\"Intermediary_Environment_Location\").split(',')\n #OutPut Location\n config['Output_Environment_Type'] = os.getenv(\"Output_Environment_Type\")\n config['Output_Environment_Location'] = os.getenv(\"Output_Environment_Location\")\n\n\n ###Configuration One: Local-->Local\n #spctojsonconverter\n ###Configuration Two: GCS--->GCS\n #downloadtoGCS\n #spctojsonconverter\n #uploadtoGCS\n ####Configuration Three: GCS-->(JSON)GCS-->BigQuery\n #downloadtLocal\n #spctojsonconverter\n #uploadtoGCS\n #json_bucket_to_bigquery\n ### In future, JSconfig needed for authentication of credential to GCS\n\n\n # if (Process_Control['Input_Environment']['Type']=='local') & (Process_Control['Output_Environment']['Type']=='local'):\n if (config['Input_Environment_Type']=='local') & (config['Output_Environment_Type']=='local'):\n logging.info('local to local was successful')\n\n try:\n\n directoryContainingSpcFiles(config['Input_Environment_Location'],config['Output_Environment_Location'])\n except Exception:\n logging.info('local to local was failure')\n logging.exception(Exception)\n elif (config['Input_Environment_Type']=='gcs') & (config['Output_Environment_Type']=='gcs'):\n \n if (config['Required']=='yes') & (config[\"No_Of_Intermediates\"]=='1'):\n logging.info('gcs to gcs was successful')\n try:\n cwd = os.getcwd()\n logging.info('Current Directory: '+cwd)\n exportJsonPath = cwd + '/raman_docker/test_data'\n logging.info('exportJsonPath:' + exportJsonPath)\n jsConfigPath = cwd + '/raman_docker'\n os.chdir(exportJsonPath)\n logging.info('exportJsonPath current directory:' + exportJsonPath)\n downloadBlob(jsConfigPath + '/GCSConfigJson.json',config['Input_Environment_Location'], exportJsonPath)\n\n directoryContainingSpcFiles(os.chdir(exportJsonPath))\n uploadBlob(jsConfigPath + '/GCSConfigJson.json',config['Output_Environment_Location'], exportJsonPath)\n except Exception:\n logging.info('gcs to gcs was failure')\n logging.exception(Exception)\n else:\n logging.raiseException(\"INVALID INTERMEDIARY VALUES\")\n ##Process_Control['Input_Environment']['Location'][0]-->Local\n ##Process_Control['Input_Environment']['Location'][1]-->GCS\n elif (config['Input_Environment_Type']=='gcs') & (config['Output_Environment_Type']=='bigquery'):\n if (config['Required']=='yes') & (config[\"No_Of_Intermediates\"]=='2'):\n logging.info('gcs to bigquery was successful')\n try:\n cwd = os.getcwd()\n logging.info('Current Directory: '+cwd)\n exportJsonPath = cwd + '/raman_docker/test_data'\n logging.info('exportJsonPath:' + exportJsonPath)\n jsConfigPath = cwd + '/raman_docker'\n os.chdir(exportJsonPath)\n logging.info('exportJsonPath current directory:' + exportJsonPath)\n downloadBlob(jsConfigPath+'/GCSConfigJson.json',config['Input_Environment_Location'],exportJsonPath)\n try:\n directoryContainingSpcFiles(os.chdir(exportJsonPath))\n except:\n pass\n uploadBlob(jsConfigPath+'/GCSConfigJson.json' ,config['Intermediary_Environment_Location'][1],exportJsonPath)\n gcstoBigQuery(jsConfigPath+'/GCSConfigJson.json',jsConfigPath+'/bigQueryAPIEnable.json',config['Intermediary_Environment_Location'][1],config['Output_Environment_Location'])\n except Exception:\n logging.info('gcs to bigquery was failure')\n logging.exception(Exception)\n else:\n logging.raiseException(\"INVALID INTERMEDIARY VALUES\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"wavelabs_main.py","file_name":"wavelabs_main.py","file_ext":"py","file_size_in_byte":6703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"631344662","text":"game = [[1, 2, 3],\n[4, 5, 6],\n[7, 8, 9]]\n\ndef askplayer1():\n ask = input(\"Player 1: What row and column would you like to place X in? *use only numbers separate with a slash (i.e. 1/2 for row 1/column 2) \")\n try:\n z = ask.split(\"/\")\n row = int(z[0])\n column = int(z[1])\n\n game[row][column] = \"X\"\n except:\n print (\"Follow the rules of submission.\")\n\n for each in game:\n print (each)\n\ndef askplayer2():\n ask = input(\"Player 2: What row and column would you like to place O in? *use only numbers separate with a slash (i.e. 1/2 for row 1/column 2) \")\n try:\n z = ask.split(\"/\")\n row = int(z[0])\n column = int(z[1])\n\n game[row][column] = \"O\"\n except:\n print (\"Follow the rules of submission.\")\n\n for each in game:\n print (each)\n\ndef winner():\n if game[0][0] == game[1][0] and game[1][0] == game[2][0]:\n print (\"Player %s wins!\" % game[0][0])\n elif game[0][1] == game[1][1] and game[1][1] == game[2][1]:\n print (\"Player %s wins!\" % game[0][1])\n elif game[0][2] == game[1][2] and game[1][2] == game[2][2]:\n print (\"Player %s wins!\" % game[0][2])\n elif game[0][0] == game[0][1] and game[0][1] == game[0][2]:\n print (\"Player %s wins!\" % game[0][0])\n elif game[1][0] == game[1][1] and game[1][1] == game[1][2]:\n print (\"Player %s wins!\" % game[1][0])\n elif game[2][0] == game[2][1] and game[2][1] == game[2][2]:\n print (\"Player %s wins!\" % game[2][0])\n elif game[0][0] == game[1][1] and game[1][1] == game[2][2]:\n print (\"Player %s wins!\" % game[0][0])\n elif game[0][2] == game[1][1] and game[1][1] == game[2][0]:\n print (\"Player %s wins!\" % game[0][2])\n else:\n return (\"Keep playing.\")\n \nwhile True:\n askp1 = askplayer1()\n checkwin = winner()\n askp2 = askplayer2()\n checkwin = winner()\n \n#Still have to end this final loop once someone wins the game.\n","sub_path":"tic-tac-toe-draw.py","file_name":"tic-tac-toe-draw.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"243787552","text":"#!/usr/bin/env python\n\"\"\"A script for fetching public utility data from reporting agency servers.\"\"\"\n\nimport logging\nimport sys\nimport argparse\nimport warnings\nimport concurrent.futures\nimport pudl\nfrom pudl.settings import SETTINGS\nimport pudl.constants as pc\n\n# Create a logger to output any messages we might have...\nlogger = logging.getLogger(pudl.__name__)\nlogger.setLevel(logging.INFO)\nhandler = logging.StreamHandler()\nformatter = logging.Formatter('%(message)s')\nhandler.setFormatter(formatter)\nlogger.addHandler(handler)\n\n# require modern python\nif not sys.version_info >= (3, 6):\n raise AssertionError(\n f\"PUDL requires Python 3.6 or later. {sys.version_info} found.\"\n )\n\n\ndef parse_command_line(argv):\n \"\"\"\n Parse command line arguments. See the -h option.\n\n :param argv: arguments on the command line must include caller file name.\n \"\"\"\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n '-q',\n '--quiet',\n dest='verbose',\n action='store_false',\n help=\"Quiet mode. Suppress download progress indicators and warnings.\",\n default=True\n )\n parser.add_argument(\n '-z',\n '--zip',\n dest='unzip',\n action='store_false',\n help=\"Do not unzip downloaded data files.\",\n default=True\n )\n parser.add_argument(\n '-c',\n '--clobber',\n action='store_true',\n help=\"Clobber existing zipfiles in the datastore if they exist.\",\n default=False\n )\n parser.add_argument(\n '-d',\n '--datadir',\n type=str,\n help=\"\"\"Path to the top level datastore directory. (default:\n %(default)s).\"\"\",\n default=SETTINGS['data_dir']\n )\n parser.add_argument(\n '-s',\n '--sources',\n nargs='+',\n choices=pc.data_sources,\n help=\"\"\"List of data sources which should be downloaded.\n (default: %(default)s).\"\"\",\n default=pc.data_sources\n )\n parser.add_argument(\n '-y',\n '--years',\n dest='years',\n nargs='+',\n help=\"\"\"List of years for which data should be downloaded. Different\n data sources have differet valid years. If data is not available for a\n specified year and data source, it will be ignored. If no years are\n specified, all available data will be downloaded for all requested data\n sources.\"\"\",\n default=[]\n )\n parser.add_argument(\n '-n',\n '--no-download',\n dest='no_download',\n action='store_true',\n help=\"Do not download data files, only unzip ones that are already present.\",\n default=False\n )\n parser.add_argument(\n '-t',\n '--states',\n nargs='+',\n choices=pc.cems_states.keys(),\n help=\"\"\"List of two letter US state abbreviations indicating which\n states data should be downloaded. Currently only applicable to the EPA's\n CEMS dataset.\"\"\",\n default=pc.cems_states.keys()\n )\n\n arguments = parser.parse_args(argv[1:])\n return arguments\n\n\ndef main():\n \"\"\"Main function controlling flow of the script.\"\"\"\n\n args = parse_command_line(sys.argv)\n\n # Generate a list of valid years of data to download for each data source.\n # If no years were specified, use the full set of valid years.\n # If years were specified, keep only th years which are valid for that\n # data source, and optionally output a message saying which years are\n # being ignored because they aren't valid.\n yrs_by_src = {}\n for src in args.sources:\n if not args.years:\n yrs_by_src[src] = pc.data_years[src]\n else:\n yrs_by_src[src] = [int(yr) for yr in args.years\n if int(yr) in pc.data_years[src]]\n bad_yrs = [int(yr) for yr in args.years\n if int(yr) not in pc.data_years[src]]\n if args.verbose and bad_yrs:\n warnings.warn(f\"Invalid {src} years ignored: {bad_yrs}.\")\n\n with concurrent.futures.ThreadPoolExecutor() as executor:\n for src in args.sources:\n for yr in yrs_by_src[src]:\n executor.submit(pudl.datastore.update, src, yr, args.states,\n clobber=args.clobber,\n unzip=args.unzip,\n datadir=args.datadir,\n no_download=args.no_download)\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"scripts/update_datastore.py","file_name":"update_datastore.py","file_ext":"py","file_size_in_byte":4507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"546835005","text":"from django.shortcuts import render, redirect\n\nimport requests\n\nfrom django.http import HttpResponse\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import login, authenticate\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom django.core import serializers\n\nfrom django.http import JsonResponse\n\nfrom rest_framework import generics\n\nfrom rest_framework import status\n\nfrom rest_framework.response import Response\nfrom rest_framework.renderers import JSONRenderer\n\nfrom .models import Location, Rating, ProfileProps, ProfileHasSeen, ProfileLimbo\n\nfrom .serializers import LocationSerializer\n\n\nimport json\n\n\n# Create your views here.\n\n# def index(request):\n# r = requests.get('http://httpbin.org/status/418')\n# print(r.text)\n# return HttpResponse('
    ' + r.text + '
    ')\n\ndef index(request):\n location_list = Location.objects.all()\n\n # print(location_list)\n\n context = {'location_list': location_list}\n return render(request, 'index.html', context)\n\n@csrf_exempt \ndef signup(request):\n if request.method == 'POST':\n\n response = json.loads(request.body)\n\n username = response['username']\n\n password = response['password']\n\n user = User.objects.create_user(username, 'myemail@crazymail.com', password)\n\n user.save()\n\n return render(request, 'index.html')\n\n@csrf_exempt \ndef submit(request):\n if request.method == 'POST':\n\n response = json.loads(request.body)\n\n p = Location.objects.create(author=User.objects.get(username=response['user']), name=response['name'], lon=response['lon'], lat=response['lat'], desc=response['desc'], city=response['city'], road=response['road'], house_number=response['house_number'])\n\n return render(request, 'index.html')\n\n@csrf_exempt \ndef rate(request):\n if request.method == 'POST':\n\n response = json.loads(request.body)\n\n author = User.objects.get(username=response['author'])\n location = Location.objects.get(name=response['location'])\n comment=response['comment']\n\n p = Rating.objects.create(author=author, location=location, comment=comment)\n\n return JsonResponse(json.loads(request.body), safe=False)\n\n@csrf_exempt \ndef get_loc_database(request):\n if request.method == 'POST':\n response = list(Location.objects.values())\n\n return JsonResponse(response, safe=False)\n if request.method == 'GET':\n response = list(Location.objects.values())\n\n return JsonResponse(response, safe=False)\n\n@csrf_exempt \ndef get_ratings(request):\n if request.method == 'POST':\n response = json.loads(request.body)\n response = Location.objects.get(id=response)\n\n # print(response.objects.values(\"username\"))\n\n response = ProfileHasSeen.objects.filter(place=response)\n\n response_list = list(response.values())\n\n query_id = list(response.values(\"profile_id\")[0].values())[0]\n\n for i in range(len(response_list)):\n # print(response_list[i])\n query_id = list(response.values(\"profile_id\")[i].values())[0]\n # print(User.objects.get(id=query_id))\n response_list[i]['profile_id'] = str(User.objects.get(id=query_id))\n\n print(response_list)\n\n return JsonResponse(response_list, safe=False)\n\n@csrf_exempt \ndef get_comments(request):\n if request.method == 'POST':\n response = json.loads(request.body)\n response = Location.objects.get(id=response)\n\n # print(response.objects.values(\"username\"))\n\n response = Rating.objects.filter(location=response)\n\n response_list = list(response.values())\n\n query_id = list(response.values(\"author\")[0].values())[0]\n\n for i in range(len(response_list)):\n # print(response_list[i])\n query_id = list(response.values(\"author\")[i].values())[0]\n # print(User.objects.get(id=query_id))\n response_list[i]['author'] = str(User.objects.get(id=query_id))\n\n print(response_list)\n\n return JsonResponse(response_list, safe=False)\n\n\n@csrf_exempt \ndef get_profile_props(request):\n if request.method == 'POST':\n response = str(request.body.decode(\"utf-8\") )\n response = User.objects.get(username=response)\n \n\n # print(response.objects.values(\"username\"))\n\n response = ProfileProps.objects.filter(profile=response)\n\n response = list(response.values())[0]\n\n # query_id = list(response.values(\"author_id\")[0].values())[0]\n\n # for i in range(len(response_list)):\n # print(response_list[i])\n # query_id = list(response.values(\"author_id\")[i].values())[0]\n # print(User.objects.get(id=query_id))\n # response_list[i]['username'] = str(User.objects.get(id=query_id))\n\n # print(response_list)\n\n return JsonResponse(response, safe=False)\n\n\n@csrf_exempt \ndef change_profile_props(request):\n if request.method == 'POST':\n response = json.loads(request.body)\n profile = response['profile']\n age = response['age']\n lunch = response['lunch']\n \n profile = User.objects.get(username=profile)\n\n response = ProfileProps.objects.get(profile=profile)\n\n response.age = age\n response.lunch = lunch\n\n response.save()\n\n return JsonResponse(json.loads(request.body), safe=False)\n\n@csrf_exempt \ndef add_profile_props(request):\n if request.method == 'POST':\n\n response = json.loads(request.body)\n\n profile = response['profile']\n age = response['age']\n lunch = response['lunch']\n\n profile = User.objects.get(username=profile)\n\n # p = Rating.objects.create(author=author, location=location, popularity=popularity, attractiveness=attractiveness, vfp=vfp, atmo=atmo)\n\n response = ProfileProps.objects.create(profile=profile, age=age, lunch=lunch)\n\n return JsonResponse(json.loads(request.body), safe=False)\n\n\n@csrf_exempt \ndef add_profile_seen(request):\n if request.method == 'POST':\n\n response = json.loads(request.body)\n\n profile = response['profile']\n place = response['place']\n liked = response['liked']\n\n profile = User.objects.get(username=profile)\n place = Location.objects.get(name=place)\n if liked == \"true\":\n liked = True\n elif liked == \"false\":\n liked = False\n\n ProfileHasSeen.objects.create(profile=profile, place=place, liked=liked)\n\n return JsonResponse(json.loads(request.body), safe=False)\n\n@csrf_exempt \ndef get_profile_seen(request):\n if request.method == 'POST':\n\n response = json.loads(request.body)\n\n profile = response['profile']\n profile = User.objects.get(username=profile)\n\n response = ProfileHasSeen.objects.filter(profile=profile)\n\n response = list(response.values())\n\n for r in response:\n r['place_id'] = Location.objects.filter(id=r['place_id']).values()[0]['name']\n\n return JsonResponse(response, safe=False)\n\n@csrf_exempt \ndef get_profile_not_seen(request):\n if request.method == 'POST':\n\n profile = json.loads(request.body)['profile']\n\n profile = User.objects.get(username=profile)\n\n seen = ProfileHasSeen.objects.filter(profile=profile)\n\n seen = list(seen.values())\n\n response = Location.objects.all()\n\n response = list(response.values())\n\n # print(response)\n\n to_del = []\n\n index = 0\n\n # IN HASSEENS\n\n for r in response:\n for s in seen:\n if r['id'] == s['place_id']:\n to_del.append(index)\n index = index + 1\n\n for index in sorted(to_del, reverse=True):\n del response[index]\n\n # IN LIMBO\n\n limbo = ProfileLimbo.objects.filter(profile=profile)\n\n limbo = list(limbo.values())\n\n to_del = []\n\n index = 0\n\n for r in response:\n for l in limbo:\n if r['id'] == l['place_id']:\n to_del.append(index)\n index = index + 1\n\n for index in sorted(to_del, reverse=True):\n del response[index]\n\n return JsonResponse(response, safe=False)\n\n\n@csrf_exempt \ndef delete_rated_place(request):\n if request.method == 'POST':\n loaded = json.loads(request.body)\n \n for x in loaded:\n id = x['id']\n ProfileHasSeen.objects.get(id=id).delete()\n\n return JsonResponse(json.loads(request.body), safe=False)\n\n@csrf_exempt \ndef reset_rated_places(request):\n if request.method == 'POST':\n loaded = str(request.body.decode(\"utf-8\") )\n\n profile_id = loaded\n\n profile = User.objects.get(username=profile_id)\n\n ProfileHasSeen.objects.filter(profile_id=profile.id).delete()\n ProfileLimbo.objects.filter(profile_id=profile.id).delete()\n\n\n return JsonResponse(loaded, safe=False)\n\n@csrf_exempt \ndef delete_comment(request):\n if request.method == 'POST':\n loaded = json.loads(request.body)\n\n id = loaded\n Rating.objects.get(id=id).delete()\n\n # for x in loaded:\n # id = x['id']\n # ProfileHasSeen.objects.get(id=id).delete()\n\n return JsonResponse(json.loads(request.body), safe=False)\n\n@csrf_exempt \ndef add_limbo(request):\n if request.method == 'POST':\n response = json.loads(request.body)\n\n profile = response['profile']\n place = response['place']\n\n profile = User.objects.get(username=profile)\n place = Location.objects.get(name=place)\n\n\n ProfileLimbo.objects.create(profile=profile, place=place)\n\n return JsonResponse(json.loads(request.body), safe=False)\n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"365235019","text":"import json\n\nwith open(\"data.json\", \"r\") as json_data:\n data_ = json.load(json_data)\n\nnicks_ = []\nfor i in data_[\"info\"]:\n nicks_.append(value for value in i.values())\n\nprint(nicks_)\nprint(data_[\"info\"])\n","sub_path":"homework_17_messanger/111.py","file_name":"111.py","file_ext":"py","file_size_in_byte":210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"56992650","text":"'''\nProgram for poker game\n'''\ndef is_straight(hand):\n '''\n Straight Function\n '''\n stng_values = \"--23456789TJQKA\"\n hand_values = []\n for i in hand:\n hand_values.append(stng_values.index(i[0]))\n hand_values.sort()\n for i in range(len(hand_values) - 1):\n if hand_values[i] - hand_values[i+1] != -1:\n return False\n return True\n\ndef is_flush(hand):\n '''\n Flush Function\n '''\n values_set = set({})\n for i in hand:\n values_set.add(i[1])\n return len(values_set) == 1\n\ndef is_four(hand):\n '''\n Function for 4 of a kind\n '''\n # count = 1\n # stng_values = \"--23456789TJQKA\"\n # hand_values = []\n # for i in hand:\n # hand_values.append(stng_values.index(i[0]))\n # hand_values.sort()\n # for i in range(len(hand_values) - 1):\n # if hand_values[i] - hand_values[i+1] == 0:\n # count += 1\n # if count==4:\n # return True\n # return False\n hand_values = [f_1 for f_1, s in hand]\n set_val = set(hand_values)\n if len(set_val) != 2:\n return False\n for f_1 in set_val:\n if hand_values.count(f_1) == 4:\n return True\n return False\n\ndef is_three(hand):\n '''\n Function for 3 of a kind\n '''\n # count = 1\n # stng_values = \"--23456789TJQKA\"\n # hand_values = []\n # for i in hand:\n # hand_values.append(stng_values.index(i[0]))\n # hand_values.sort()\n # for i in range(len(hand_values) - 1):\n # if hand_values[i] - hand_values[i+1] == 0:\n # count += 1\n # if count==3:\n # return True\n # return False\n hand_values = [f_1 for f_1, s in hand]\n set_val = set(hand_values)\n if len(set_val) <= 2:\n return False\n for f_1 in set_val:\n if hand_values.count(f_1) == 3:\n return True\n return False\n\ndef is_onepair(hand):\n '''\n Function for one pair\n '''\n hand_values = [f_1 for f_1, s in hand]\n set_val = set(hand_values)\n onepair = [f_1 for f_1 in set_val if hand_values.count(f_1) == 2]\n if len(onepair) == 1:\n return True\n return False\n\ndef is_full(hand):\n '''\n Full hand function\n '''\n hand_values = [f_1 for f_1, s in hand]\n set_val = set(hand_values)\n if len(set_val) != 2:\n return False\n for f_1 in set_val:\n if hand_values.count(f_1) == 3:\n return True\n return False\n\ndef is_twopair(hand):\n '''\n Function for two pair\n '''\n hand_values = [f_1 for f_1, s in hand]\n set_val = set(hand_values)\n twopairs = [f_1 for f_1 in set_val if hand_values.count(f_1) == 2]\n if len(twopairs) != 2:\n return False\n return True\n\ndef hand_rank(hand):\n '''\n Function for hand rank\n '''\n rank = 0\n if is_straight(hand) and is_flush(hand):\n rank = 1\n elif is_four(hand):\n rank = 2\n elif is_full(hand):\n rank = 3\n elif is_flush(hand):\n rank = 4\n elif is_straight(hand):\n rank = 5\n elif is_three(hand):\n rank = 6\n elif is_twopair(hand):\n rank = 7\n elif is_onepair(hand):\n rank = 8\n else:\n rank = 0\n return rank\n\ndef poker(hands):\n '''Poker function\n '''\n return max(hands, key=hand_rank)\n\nif __name__ == \"__main__\":\n COUNT = int(input())\n HANDS = []\n for x in range(COUNT):\n line = input()\n ha = line.split(\" \")\n HANDS.append(ha)\n print(' '.join(poker(HANDS)))\n ","sub_path":"cspp1-practice/m16/codecamppoker3/poker.py","file_name":"poker.py","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"336578581","text":"import pickle\n\nclass GameNode:\n def __init__(self):\n self._children = []\n def addchild(self, link, node):\n self._children.append((link, node))\n @staticmethod\n def run(node):\n for choice in node.display():\n if isinstance(choice, tuple):\n GameNode.save(node, choice[1])\n elif not node._children or choice == 'Q':\n return\n else:\n GameNode.run(node._children[choice][1])\n return\n @staticmethod\n def save(node, savepath):\n with open(savepath, \"wb\") as sf:\n pickle.dump(node, sf)\n @staticmethod\n def load(savefile):\n with open(savefile, \"rb\") as lf:\n node=pickle.load(lf)\n return node","sub_path":"ttyavg.py","file_name":"ttyavg.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"438858443","text":"# -*- coding: utf-8 -*-\n##############################################################################\n# \n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see . \n#\n##############################################################################\n\nimport openerp.addons.decimal_precision as dp\nfrom openerp.osv import fields, osv, orm\nimport logging\n_logger = logging.getLogger(__name__)\nfrom openerp.tools.translate import _\nfrom openerp import netsvc\n\n#Issue333\nclass quality_proposal(osv.osv):\n _name = \"quality.proposal\"\n _inherit = ['mail.thread', 'ir.needaction_mixin']\n _description = \"Quality Proposal\"\n _order = \"name desc\"\n \n _columns = {\n 'name': fields.char('Name', size=16, readonly=True, required=True),\n 'quality_issue': fields.char('Quality Issue', size=64, required=True),\n 'date': fields.date('Date', select=True, required=True),\n 'product_id': fields.many2many('product.product', 'quality_product', 'proposal_id', 'product_id', string='Product', domain=[('type','<>','service')],states={'done': [('readonly', True)]}),\n 'importance': fields.selection([('low', 'Low'),\n ('normal', 'Normal'),\n ('urgent', 'Urgent'),\n ], 'Importance', select=True, required=True),\n 'state': fields.selection([('draft', 'New'),\n ('cancel', 'Cancelled'),\n ('invest', 'Investigation'),\n ('done', 'Accepted'),\n ], 'Status', readonly=True, select=True, required=True),\n 'expected_date': fields.date('Estimated Completion Date', select=True),\n 'user_id': fields.many2one('res.users', 'Responsible', required=True, change_default=True, select=True, track_visibility='always'),\n 'feature': fields.text('Improvement Requests', required=True),\n 'comment_yes': fields.text('Comment - What can be achieved'),\n 'comment_no': fields.text('Comment - What can not be achieved'),\n }\n\n _defaults = {\n 'date': fields.date.context_today,\n 'state': 'draft',\n 'name': lambda obj, cr, uid, context: '/',\n #'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'purchase.order', context=c),\n }\n _sql_constraints = [\n ('name_uniq', 'unique(name, company_id)', 'Order Reference must be unique per Company!'),\n ]\n\n def create(self, cr, uid, vals, context=None):\n if vals.get('name','/')=='/':\n vals['name'] = self.pool.get('ir.sequence').get(cr, uid, 'quality.proposal') or '/'\n order = super(quality_proposal, self).create(cr, uid, vals, context=context)\n return order\n\n def write(self, cr, uid, ids, vals, context=None):\n if vals.get('user_id'):\n self.write(cr, uid, ids, {'message_follower_ids':[(4,self.pool.get('res.users').browse(cr, uid, vals['user_id']).partner_id.id)]})\n return super(quality_proposal, self).write(cr, uid, ids, vals, context=context)\n\n def copy(self, cr, uid, id, default=None, context=None):\n if not default:\n default = {}\n default.update({\n 'state':'draft',\n 'name': self.pool.get('ir.sequence').get(cr, uid, 'quality.proposal'),\n })\n return super(quality_proposal, self).copy(cr, uid, id, default, context)\n\n def tender_cancel(self, cr, uid, ids, context=None):\n #purchase_order_obj = self.pool.get('purchase.order')\n #for purchase in self.browse(cr, uid, ids, context=context):\n # for purchase_id in purchase.purchase_ids:\n # if str(purchase_id.state) in('draft'):\n # purchase_order_obj.action_cancel(cr,uid,[purchase_id.id])\n return self.write(cr, uid, ids, {'state': 'cancel'})\n\n def tender_invest(self, cr, uid, ids, context=None):\n return self.write(cr, uid, ids, {'state':'invest'} ,context=context)\n\n def tender_reset(self, cr, uid, ids, context=None):\n return self.write(cr, uid, ids, {'state': 'draft'})\n\n def tender_done(self, cr, uid, ids, context=None):\n return self.write(cr, uid, ids, {'state':'done'}, context=context)\n\n def wkf_confirm_order(self, cr, uid, ids, context=None):\n pass\n\n\nquality_proposal()\n\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n\n","sub_path":"product_proposal_enhance/quality_proposal.py","file_name":"quality_proposal.py","file_ext":"py","file_size_in_byte":5191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"557970712","text":"import calendar\nfrom operator import itemgetter\nfp = open('final_data.txt')\ntip_toll_dict = {}\ntotal_trips = {}\nfor lines in fp:\n\tline = lines.strip().split('\\t')\n\tkey = line[0]\n\ttip_toll = line[1].strip()\n\ttip = tip_toll.split(',')[0].strip()\n\ttoll = tip_toll.split(',')[1].strip()\n\t#key = key.strip()\n\tkey = key.replace(\"'\", \"\")\n\tkey = key.replace(\"(\", \"\")\n\tkey = key.replace(\")\", \"\")\n\tkey = key.replace(\",\", \"-\")\n\tif tip_toll_dict.get(key) == None:\n\t\ttip_toll_dict[key] = [float(tip), float(toll)]\n\telse:\n\t\tinitial_tip, initial_toll = tip_toll_dict[key]\n\t\tinitial_toll += float(toll)\n\t\tinitial_tip += float(tip)\n\t\ttip_toll_dict[key] = [initial_tip, initial_toll]\n\n#print tip_toll_dict\n\nfp1 = open('/Users/pratyush1/Documents/NYU/Assignments/Big_Data_Spring_16/project/Final_Scripts/yellow2014-2015/top_pickdrop_comb/final_data.csv')\nfor lines1 in fp1:\n\tline1 = lines1.strip().split(',')\n\tkey1 = line1[0]\n\t#key1 = line1[0].strip()\n\ttrips1 = line1[1].strip()\n\ttotal_trips[key1] = trips1\n\nfw = open('final_data.csv', 'w')\nfw.write('Pickup & Dropoff, Average tip amount')\nfor data in tip_toll_dict.keys():\n\ttip, toll = tip_toll_dict[data]\n\ttrips = total_trips[data]\n\ta = round(float(tip)/int(trips), 4)\n\tb = round(float(toll)/int(trips), 4)\n\tfw.write('\\n')\n\tfw.write(str(data) + ', '+ str(a))\n\t#print(\"%s,%s,%s\" %(data, a, b))\nfw.close()","sub_path":"Reduce_Files_Aggregation_Scripts/tip_toll_by_pickup-dropoff/tip-toll.py","file_name":"tip-toll.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"556103142","text":"import json\nfrom music_browser import MusicBrowser\nfrom music_browser.plugins import SpotifyPlugin\nfrom music_browser.serializer import MusicBrowserSerializer\n\n\ndef browser_search(query):\n spotify = SpotifyPlugin(\n client_id=\"97e316da02e94644b332c3ad77554c68\", client_secret=\"9b999c62cf324a428a335a7d87b3d0a9\"\n )\n browser = MusicBrowser(search_plugin=spotify, completion_plugins=[spotify])\n tracks = browser.search(query)\n\n for simple_track in tracks:\n print(simple_track)\n\n return tracks\n\n\nif __name__ == \"__main__\":\n tracks = browser_search(\"Lovers on the sun\")\n\n with open(\"samples_output/browser_tracks.json\", \"w\") as spotify_tracks:\n json.dump(tracks, spotify_tracks, indent=4, cls=MusicBrowserSerializer)\n","sub_path":"samples/browser_search.py","file_name":"browser_search.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"364055362","text":"import os\nimport abjad\nimport tsmakers\n\nprint(os.path.dirname(__file__))\n\nprint(\" \")\nfile_name = os.path.basename(__file__)\nfile_name = os.path.splitext(file_name)[0]\nillust_path = \"../../a_rua_dos_cataventos/segments/illustrations\"\nnew_file = illust_path+\"/\"+str(file_name)+\".ly\"\nprint(new_file)\n\n \n\ncontainer = abjad.Container(\"c''4 d''8 e''16 e''32 e''4 e''4 e''4\")\nmeters = [(3, 4), (4, 4), (5, 4)]\nmeters = [abjad.Meter(_) for _ in meters]\n\n\nargument = [(0, 4), (4, 4), (8, 4), (12, 4), (16, 4)]\nfor meter in abjad.Meter.fit_meters(container, meters):\n print(meter.implied_time_signature)\n \n \n \n \n# for staff in score:\n# for container in staff:\n# leaf = abjad.get.leaf(container, 0)\n# time_signature = abjad.get.indicator(leaf, abjad.TimeSignature)\n# abjad.Meter.rewrite_meter(container[:], time_signature)\n#\n#\nabjad.f(container)\n ","sub_path":"tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"77672390","text":"from contact import Contact\nimport sys\n\nclass CRM:\n\n # As a user, upon starting the CRM, I am presented with a prompt to add, modify, delete, display all, search by attribute, and exit.\n def main_menu(self):\n try:\n while True:\n self.print_main_menu()\n user_selected = int(input())\n self.call_option(user_selected)\n except ValueError:\n sys.exit('Goodbye')\n \n \n\n def print_main_menu(self):\n print('[1] Add a new contact')\n print('[2] Modify an existing contact')\n print('[3] Delete a contact')\n print('[4] Display all the contacts')\n print('[5] Search by attribute')\n print('[6] Exit')\n print('Enter a number: ')\n\n\n def __repr__(self): \n return f'{self.print_main_menu()} '\n\n def call_option(self, user_selected):\n if user_selected == 1:\n self.add_new_contact()\n elif user_selected == 2:\n self.modify_existing_contact()\n elif user_selected == 3:\n self.delete_contact()\n elif user_selected == 4:\n self.display_all_contacts()\n elif user_selected == 5:\n self.search_by_id()\n elif user_selected == 6:\n exit('Take Care!')\n \n \n # As a user, if I select add I am prompted to enter a 'first name', 'last name', 'email' and 'note'.\n def add_new_contact(self):\n first_name = input(('Enter First Name: '))\n last_name = input(('Enter Last Name: '))\n email = input(('Enter Email Address: '))\n note = input(('Enter a Note: '))\n\n # Contact.create(first_name, last_name, email, note)\n Contact.create(\n first_name=first_name,\n last_name=last_name,\n email=email,\n note=note\n )\n\n\n # As a user, if I select modify I am prompted to enter an id for the contact to be modified.\n def modify_existing_contact(self):\n id_x = int(input('Enter your ID\\n'))\n contact_finder = Contact.get(id=id_x)\n\n\n contact_attribute = input('Which attribute do you want to edit?: ')\n new_value = input('New value to be?: ') \n\n\n if id_x == contact_finder.id:\n if contact_attribute == 'first name': \n contact_finder.first_name = new_value\n contact_finder.save()\n elif contact_attribute == 'last name': \n contact_finder.last_name = new_value\n contact_finder.save()\n elif contact_attribute == 'email': \n contact_finder.email = new_value\n contact_finder.save()\n elif contact_attribute == 'note': \n contact_finder.note = new_value\n contact_finder.save()\n \n \n \n def delete_contact(self):\n id_x = int(input('Enter your ID'))\n c = Contact.get(id=id_x)\n c.delete_instance()\n \n def display_all_contacts(self):\n for contact in Contact.select():\n print(contact.first_name, contact.last_name)\n \n\n \n def search_by_id(self):\n get_id = input(\"What's your ID?\")\n contact = Contact.get(id=get_id)\n print(contact)\n\n\n\n# Contact.create('John', 'fruc', 'john@john.com', 'rock on')\n# # print(Contact.contacts_list)\n\n# a_crm_app = CRM()\n# print(a_crm_app.modify_existing_contact() )\n# a_crm_app.main_menu()\n\n\n\ncrm1 = CRM()\nprint(crm1.main_menu())\n# crm1.display_all_contacts()\n# Contact.create('John', 'fruc', 'john@john.com', 'rock on')\n# crm1.display_all_contacts()\n# crm1.delete_contact()\n# crm1.display_all_contacts()\n# crm1.modify_existing_contact() \n\n\n# crm1.display_all_contacts()\n\n# crm1.add_new_contact()\n","sub_path":"crm.py","file_name":"crm.py","file_ext":"py","file_size_in_byte":3336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"412091560","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\"\"\"\nTools for scheduling observations.\n\"\"\"\n\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\n\nimport copy\nfrom abc import ABCMeta, abstractmethod\n\nimport numpy as np\n\nfrom astropy import units as u\n\nfrom .utils import time_grid_from_range, stride_array\n\n__all__ = ['ObservingBlock', 'TransitionBlock', 'Scheduler',\n 'SequentialScheduler', 'PriorityScheduler', 'Transitioner']\n\n\nclass ObservingBlock(object):\n \"\"\"\n An observation to be scheduled, consisting of a target and associated\n constraints on observations.\n \"\"\"\n @u.quantity_input(duration=u.second)\n def __init__(self, target, duration, priority, configuration={}, constraints=None):\n \"\"\"\n Parameters\n ----------\n target: `~astroplan.FixedTarget'\n Target to observe\n\n duration : `~astropy.units.Quantity`\n exposure time\n\n priority: integer or float\n priority of this object in the target list. 1 is highest priority,\n no maximum\n\n configuration : dict\n Configuration metadata\n\n constraints : list of `~astroplan.constraints.Constraint` objects\n The constraints to apply to this particular observing block. Note\n that constraints applicable to the entire list should go into the\n scheduler.\n\n \"\"\"\n self.target = target\n self.duration = duration\n self.priority = priority\n self.configuration = configuration\n self.constraints = constraints\n self.start_time = self.end_time = None\n\n def __repr__(self):\n orig_repr = object.__repr__(self)\n if self.start_time is None or self.end_time is None:\n return orig_repr.replace('object at',\n '({0}, unscheduled) at'\n .format(self.target.name))\n else:\n s = '({0}, {1} to {2}) at'.format(self.target.name, self.start_time,\n self.end_time)\n return orig_repr.replace('object at', s)\n\n @classmethod\n def from_exposures(cls, target, priority, time_per_exposure,\n number_exposures, readout_time=0 * u.second,\n configuration={}):\n duration = number_exposures * (time_per_exposure + readout_time)\n ob = cls(target, duration, priority, configuration)\n ob.time_per_exposure = time_per_exposure\n ob.number_exposures = number_exposures\n ob.readout_time = readout_time\n return ob\n\nclass TransitionBlock(object):\n \"\"\"\n Parameterizes the \"dead time\", e.g. between observations, while the\n telescope is slewing, instrument is reconfiguring, etc.\n \"\"\"\n def __init__(self, components, start_time=None):\n \"\"\"\n Parameters\n ----------\n components : dict\n A dictionary mapping the reason for an observation's dead time to\n `~astropy.units.Quantity` objects with time units\n\n start_time : `~astropy.units.Quantity`\n Start time of observation\n \"\"\"\n self.start_time = start_time\n self.components = components\n self._components = None\n self.duration = None\n\n def __repr__(self):\n orig_repr = object.__repr__(self)\n comp_info = ', '.join(['{0}: {1}'.format(c, t)\n for c, t in self.components.items()])\n if self.start_time is None or self.end_time is None:\n return orig_repr.replace('object at', ' ({0}, unscheduled) at'.format(comp_info))\n else:\n s = '({0}, {1} to {2}) at'.format(comp_info, self.start_time, self.end_time)\n return orig_repr.replace('object at', s)\n\n @property\n def end_time(self):\n return self.start_time + self.duration\n\n @property\n def components(self):\n return self._components\n\n @components.setter\n def components(self, val):\n duration = 0*u.second\n for t in val.values():\n duration += t\n\n self._components = val\n self.duration = duration\n\n\nclass Scheduler(object):\n \"\"\"\n Schedule a set of `~astroplan.scheduling.ObservingBlock` objects\n \"\"\"\n\n __metaclass__ = ABCMeta\n\n def __call__(self, blocks):\n \"\"\"\n Parameters\n ----------\n blocks : list of `~astroplan.scheduling.ObservingBlock` objects\n The observing blocks to schedule. Note that the input\n `~astroplan.scheduling.ObservingBlock` objects will *not* be\n modified - new ones will be created and returned.\n\n Returns\n -------\n schedule : list\n A list of `~astroplan.scheduling.ObservingBlock` objects and\n `~astroplan.scheduling.TransitionBlock` objects with populated\n ``start_time`` and ``end_time`` attributes\n \"\"\"\n # these are *shallow* copies\n copied_blocks = [copy.copy(block) for block in blocks]\n new_blocks, already_sorted = self._make_schedule(copied_blocks)\n if not already_sorted:\n block_time_map = {block.start_time : block for block in new_blocks}\n new_blocks = [block_time_map[time] for time in sorted(block_time_map)]\n return new_blocks\n\n @abstractmethod\n def _make_schedule(self, blocks):\n \"\"\"\n Does the actual business of scheduling. The ``blocks`` passed in should\n have their ``start_time` and `end_time`` modified to reflect the\n schedule. Any necessary `~astroplan.scheduling.TransitionBlock` should\n also be added. Then the full set of blocks should be returned as a list\n of blocks, along with a boolean indicating whether or not they have been\n put in order already.\n\n Parameters\n ----------\n blocks : list of `~astroplan.scheduling.ObservingBlock` objects\n Can be modified as it is already copied by ``__call__``\n\n Returns\n -------\n new_blocks : list of blocks\n The blocks from ``blocks``, as well as any necessary\n `~astroplan.scheduling.TransitionBlock` objects\n already_sorted : bool\n If True, the ``new_blocks`` come out pre-sorted, otherwise they need\n to be sorted.\n \"\"\"\n raise NotImplementedError\n return new_blocks, already_sorted\n\n\nclass SequentialScheduler(Scheduler):\n \"\"\"\n A scheduler that does \"stupid simple sequential scheduling\". That is, it\n simply looks at all the blocks, picks the best one, schedules it, and then\n moves on.\n\n Parameters\n ----------\n start_time : `~astropy.time.Time`\n the start of the observation scheduling window.\n end_time : `~astropy.time.Time`\n the end of the observation scheduling window.\n constraints : sequence of `~astroplan.constraints.Constraint` objects\n The constraints to apply to *every* observing block. Note that\n constraints for specific blocks can go on each block individually.\n observer : `~astroplan.Observer`\n The observer/site to do the scheduling for.\n transitioner : `~astroplan.scheduling.Transitioner` or None\n The object to use for computing transition times between blocks\n gap_time : `~astropy.units.Quantity` with time units\n The minimal spacing to try over a gap where nothing can be scheduled.\n\n \"\"\"\n @u.quantity_input(gap_time=u.second)\n def __init__(self, start_time, end_time, constraints, observer,\n transitioner=None, gap_time=30*u.min):\n self.constraints = constraints\n self.start_time = start_time\n self.end_time = end_time\n self.observer = observer\n self.transitioner = transitioner\n self.gap_time = gap_time\n\n @classmethod\n @u.quantity_input(duration=u.second)\n def from_timespan(cls, center_time, duration, **kwargs):\n \"\"\"\n Create a new instance of this class given a center time and duration.\n\n Parameters\n ----------\n center_time : `~astropy.time.Time`\n Mid-point of time-span to schedule.\n\n duration : `~astropy.units.Quantity` or `~astropy.time.TimeDelta`\n Duration of time-span to schedule\n \"\"\"\n start_time = center_time - duration/2.\n end_time = center_time + duration/2.\n return cls(start_time, end_time, **kwargs)\n\n def _make_schedule(self, blocks):\n for b in blocks:\n if b.constraints is None:\n b._all_constraints = self.constraints\n else:\n b._all_constraints = self.constraints + b.constraints\n b._duration_offsets = u.Quantity([0*u.second, b.duration/2,\n b.duration])\n\n new_blocks = []\n current_time = self.start_time\n while (len(blocks) > 0) and (current_time < self.end_time):\n\n # first compute the value of all the constraints for each block\n # given the current starting time\n block_transitions = []\n block_constraint_results = []\n for b in blocks:\n # first figure out the transition\n if len(new_blocks) > 0:\n trans = self.transitioner(new_blocks[-1], b, current_time,\n self.observer)\n else:\n trans = None\n block_transitions.append(trans)\n transition_time = 0*u.second if trans is None else trans.duration\n\n times = current_time + transition_time + b._duration_offsets\n\n constraint_res = []\n for constraint in b._all_constraints:\n constraint_res.append(constraint(self.observer, [b.target],\n times))\n # take the product over all the constraints *and* times\n block_constraint_results.append(np.prod(constraint_res))\n\n # now identify the block that's the best\n bestblock_idx = np.argmax(block_constraint_results)\n\n if block_constraint_results[bestblock_idx] == 0.:\n # if even the best is unobservable, we need a gap\n new_blocks.append(TransitionBlock({'nothing_observable': self.gap_time},\n current_time))\n current_time += self.gap_time\n else:\n # If there's a best one that's observable, first get its transition\n trans = block_transitions.pop(bestblock_idx)\n if trans is not None:\n new_blocks.append(trans)\n current_time += trans.duration\n\n # now assign the block itself times and add it to the schedule\n newb = blocks.pop(bestblock_idx)\n newb.start_time = current_time\n current_time += self.gap_time\n newb.end_time = current_time\n newb.constraints_value = block_constraint_results[bestblock_idx]\n\n new_blocks.append(newb)\n\n return new_blocks, True\n\n\nclass PriorityScheduler(Scheduler):\n \"\"\"\n A scheduler that optimizes a prioritized list. That is, it\n finds the best time for each ObservingBlock, in order of priority.\n \"\"\"\n @u.quantity_input(gap_time=u.second)\n def __init__(self, start_time, end_time, constraints, observer,\n transitioner=None, gap_time=30*u.min, slew_time=5*u.min):\n \"\"\"\n Parameters\n ----------\n start_time : `~astropy.time.Time`\n the start of the observation scheduling window.\n end_time : `~astropy.time.Time`\n the end of the observation scheduling window.\n constraints : sequence of `~astroplan.constraints.Constraint`\n The constraints to apply to *every* observing block. Note that\n constraints for specific blocks can go on each block individually.\n observer : `~astroplan.Observer`\n The observer/site to do the scheduling for.\n transitioner : `~astroplan.scheduling.Transitioner` or None\n The object to use for computing transition times between blocks.\n Not currently used in this Scheduler.\n gap_time : `~astropy.units.Quantity` with time units\n The minimal spacing to try over a gap where nothing can be scheduled.\n slew_time : `~astropy.units.Quantity` with time units\n The time required between observations.\n Used instead of transitioner (for now)\n \"\"\"\n self.constraints = constraints\n self.start_time = start_time\n self.end_time = end_time\n self.observer = observer\n self.transitioner = transitioner\n self.gap_time = gap_time\n self.slew_time = slew_time\n\n @classmethod\n @u.quantity_input(duration=u.second)\n def from_timespan(cls, center_time, duration, **kwargs):\n \"\"\"\n Create a new instance of this class given a center time and duration.\n\n Parameters\n ----------\n center_time : `~astropy.time.Time`\n Mid-point of time-span to schedule.\n\n duration : `~astropy.units.Quantity` or `~astropy.time.TimeDelta`\n Duration of time-span to schedule\n \"\"\"\n start_time = center_time - duration/2.\n end_time = center_time + duration/2.\n return cls(start_time, end_time, **kwargs)\n\n def _make_schedule(self, blocks):\n\n # Combine individual constraints with global constraints, and\n # retrieve priorities from each block to define scheduling order\n _all_times = []\n _block_priorities = np.zeros(len(blocks))\n for i,b in enumerate(blocks):\n if b.constraints is None:\n b._all_constraints = self.constraints\n else:\n b._all_constraints = self.constraints + b.constraints\n b._duration_offsets = u.Quantity([0*u.second, b.duration/2, b.duration])\n _block_priorities[i] = b.priority\n _all_times.append(b.duration)\n\n # Define a master schedule\n # Generate grid of time slots, and a mask for previous observations\n\n # Find the minimum required time step\n # TODO: a common factorization of all times is probably better long-term\n time_resolution = min(min(_all_times),self.slew_time)\n times = time_grid_from_range([self.start_time,self.end_time],\n time_resolution=time_resolution)\n is_open_time = np.ones(len(times),bool)\n\n # Sort the list of blocks by priority\n sorted_indices = np.argsort(_block_priorities)\n\n new_blocks = []\n unscheduled_blocks = []\n # Compute the optimal observation time in priority order\n for i in sorted_indices:\n b = blocks[i]\n\n # Compute possible observing times by combining object constraints\n # with the master schedule mask\n constraint_scores = np.zeros(len(times))\n for constraint in b._all_constraints:\n applied_constraint = constraint(self.observer, [b.target],\n times=times)\n applied_score = np.asarray(applied_constraint[0],np.float32)\n constraint_scores = constraint_scores + applied_score\n\n # Add up the applied constraints to prioritize the best blocks\n # And then remove any times that are already scheduled\n constraint_scores[is_open_time == False] = 0\n\n # Select the most optimal time\n _is_scheduled = False\n total_duration = b.duration + self.slew_time\n if np.all(constraint_scores == 0):\n # No further calculation if no times meet the constraints\n _is_scheduled = False\n else:\n # calculate the number of time slots needed for this exposure\n _stride_by = np.int(np.ceil(total_duration / time_resolution))\n\n # Stride the score arrays by that number\n _strided_scores = stride_array(constraint_scores,_stride_by)\n\n # Collapse the sub-arrays\n # (run them through scorekeeper again? Just add them?\n # If there's a zero anywhere in there, def. have to skip)\n good = np.all(_strided_scores > 1e-5, axis=1)\n sum_scores = np.zeros(len(_strided_scores))\n sum_scores[good] = np.sum(_strided_scores[good], axis=1)\n\n # If an optimal block is available, _is_scheduled=True\n best_time_idx = np.argmax(sum_scores)\n new_start_time = times[best_time_idx]\n _is_scheduled = True\n\n # And remove it from the master time list\n is_open_time[best_time_idx:best_time_idx+_stride_by] = False\n\n if _is_scheduled is False:\n print(\"could not schedule\",b.target.name)\n unscheduled_blocks.append(b)\n continue\n# best_time_idx = np.argmax(constraint_scores)\n# new_start_time = times[best_time_idx]\n else:\n # now assign the block itself times and add it to the schedule\n newb = b\n newb.start_time = new_start_time\n newb.end_time = new_start_time + total_duration\n newb.constraints = b._all_constraints\n new_blocks.append(newb)\n\n already_sorted = False\n return new_blocks, already_sorted\n\n\nclass Transitioner(object):\n \"\"\"\n A class that defines how to compute transition times from one block to\n another.\n \"\"\"\n u.quantity_input(slew_rate=u.deg/u.second)\n def __init__(self, slew_rate=None, instrument_reconfig_times=None):\n \"\"\"\n Parameters\n ----------\n slew_rate : `~astropy.units.Quantity` with angle/time units\n The slew rate of the telescope\n instrument_reconfig_times : dict of dicts or None\n If not None, gives a mapping from property names to another\n dictionary. The second dictionary maps 2-tuples of states to the\n time it takes to transition between those states (as an\n `~astropy.units.Quantity`).\n \"\"\"\n self.slew_rate = slew_rate\n self.instrument_reconfig_times = instrument_reconfig_times\n\n def __call__(self, oldblock, newblock, start_time, observer):\n \"\"\"\n Determines the amount of time needed to transition from one observing\n block to another. This uses the parameters defined in\n ``self.instrument_reconfig_times``.\n\n Parameters\n ----------\n oldblock : `~astroplan.scheduling.ObservingBlock` or None\n The initial configuration/target\n newblock : `~astroplan.scheduling.ObservingBlock` or None\n The new configuration/target to transition to\n start_time : `~astropy.time.Time`\n The time the transition should start\n observer : `astroplan.Observer`\n The observer at the time\n\n Returns\n -------\n transition : `~astroplan.scheduling.TransitionBlock` or None\n A transition to get from ``oldblock`` to ``newblock`` or `None` if\n no transition is necessary\n \"\"\"\n components = {}\n if self.slew_rate is not None:\n # use the constraints cache for now, but should move that machinery\n # to observer\n from .constraints import _get_altaz\n from astropy.time import Time\n\n aaz = _get_altaz(Time([start_time]), observer,\n [oldblock.target, newblock.target])['altaz']\n # TODO: make this [0] unnecessary by fixing _get_altaz to behave well in scalar-time case\n sep = aaz[0].separation(aaz[1])[0]\n\n components['slew_time'] = sep / self.slew_rate\n if self.instrument_reconfig_times is not None:\n components.update(self.compute_instrument_transitions(oldblock, newblock))\n\n if components:\n return TransitionBlock(components, start_time)\n else:\n return None\n\n def compute_instrument_transitions(self, oldblock, newblock):\n components = {}\n for conf_name, old_conf in oldblock.configuration.items():\n if conf_name in newblock:\n conf_times = self.instrument_reconfig_times.get(conf_name,\n None)\n if conf_times is not None:\n new_conf = newblock[conf_name]\n ctime = conf_times.get((old_conf, new_conf), None)\n if ctime is not None:\n s = '{0}:{1} to {2}'.format(conf_name, old_conf,\n new_conf)\n components[s] = ctime\n return components\n","sub_path":"astroplan/scheduling.py","file_name":"scheduling.py","file_ext":"py","file_size_in_byte":21213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"128843767","text":"# -*- coding: utf-8 -*-\n\n\n\ndef summation(val1,val2):\n val1 = str(val1)\n val2=str(val2)\n rem = 0\n result = \"\"\n #making the digits equal\n if len(val1) > len(val2):\n rev = val2[::-1]\n for i in range(len(val1)-len(val2)):\n rev = rev +'0'\n val2 = rev[::-1]\n else:\n rev = val1[::-1]\n for i in range(len(val2)-len(val1)):\n rev = rev +'0'\n val1 = rev[::-1]\n \n for i in range(len(val1)-1,-1,-1):\n temp = int(val1[i]) + int(val2[i]) + rem\n if temp > 9:\n rem = 1\n result = result + str(temp % 10)\n else:\n result = result + str(temp)\n rem = 0\n return result[::-1]\n\n\ndef multiple(val1,val2):\n val1 = str(val1)\n val2=str(val2)\n rem = 0\n result = \"\"\n sumvalue = \"\" \n total = '0'\n counter = 0 \n first = len(val1)\n second = len(val2)\n \n for i in range(second-1,-1,-1):\n for j in range(first-1,-1,-1):\n current = int(val2[i]) * int(val1[j]) + rem\n if current > 9:\n if j==0:\n sumvalue+=str(current%10)\n sumvalue+=str(current//10)\n else:\n rem = current //10\n sumvalue += str(current%10)\n else:\n rem = 0\n sumvalue += str(current)\n sumvalue=sumvalue[::-1]\n \n for k in range(counter):\n sumvalue+='0'\n #print(sumvalue)\n total = summation(total,sumvalue)\n sumvalue =\"\"\n rem = 0\n counter+=1\n return total \n #print(total)\n \nif __name__==\"__main__\":\n val1 = input(\"input number 1 :-\")\n val2 = input(\"input number 2 :-\")\n print(summation(val1,val2)) \n #print(multiple(val1,val2))\n\n ","sub_path":"week 1/summation/summation.py","file_name":"summation.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"398562414","text":"import turtle\nimport math\nimport time\n\nclass User:\n\n #Sets the attributes for a new User object.\n def __init__(self, user_name, user_id, update):\n self.user_name = user_name\n self.user_id = user_id\n self.connections = []\n # self.status_update = update\n\n #Returns user_name\n def getUserName(self):\n return self.user_name\n\n #Returns user_id\n def getUserId(self):\n return self.user_id\n\n #Lists connections\n def getConnections(self):\n return self.connections\n\n #Adds a connection (passed in as a parameter) to the user's list of connections\n def addConnection(self, connection_id):\n self.connections.append(connection_id)\n #\n # def getStatusUpdate(self):\n # return self.update\n\n\nclass Network:\n\n #Initialize network\n def __init__(self):\n self.users = []\n\n #Gives you the number of total users in the network\n def numUsers(self):\n return len(self.users)\n\n #Check if passed username is taken, and if not, add username to Network\n def addUser(self, username):\n\n for user in self.users:\n if username == user.getUserName():\n print(\"Sorry, that name is taken. Try again.\")\n return\n\n user_id = len(self.users)\n\n self.users.append(User(username, user_id))\n time.sleep(0.5)\n print(\"A new user, \\\"\" + username + \",\\\" has been created!\")\n\n\n #Return userId connected to given username\n ##If username does not exist,\n ## set user_id = -1 which means that the username is not there\n def getUserId(self, username):\n\n #4 conditionals\n\n user_id = -1\n\n for user in self.users:\n if username == user.getUserName(): #\"user\" is referring to the current username in self.users\n user_id = user.getUserId()\n\n\n return user_id\n\n #Create connection between two users\n def addConnection(self, user1, user2):\n #4 cases to check:\n ##1. If users are both in the network\n ##2. If users are already connected\n ##3. If user is trying to connect to self\n ##4. Connect them\n\n ## maybe later-- if blocked?\n\n #Creates new variables to hold user 1 and user 2's IDs\n user1_id = self.getUserId(user1)\n user2_id = self.getUserId(user2)\n\n user1 = self.users[user1_id]\n user2 = self.users[user2_id]\n\n #A conditional to check if user1 and/or user2 exist\n if user1_id == user2_id:\n print(\"You can't connect to yourself. Please try again.\")\n return\n\n if user1_id == -1 or user2_id == -1:\n print (\"One or two of the users do not exist. Please try again.\")\n return\n\n if user1_id in user2.getConnections(): #Does it matter whether user1_id is user1_id or \"user1\"\n print(\"Those users are already connected!\")\n return\n\n else:\n user1.addConnection(user2_id)\n user2.addConnection(user1_id)\n return\n\n #Prints out existing users\n def printUsers(self):\n print(\"Network Users:\")\n for user in self.users:\n print(\"\\tUser {}: {}\".format(user.getUserId()+1,user.getUserName()))\n\n\n #Print out all the connections of the given username\n def printConnections(self, username):\n user = self.users[self.getUserId(username)]\n connections = user.getConnections()\n print(\"{}'s connections:\".format(user.getUserName()))\n for friendID in connections:\n friend = self.users[friendID]\n print(\"\\t{}\".format(friend.getUserName()))\n\n\n # def addStatusUpdate(self, update):\n #\n\ndef main():\n # Define the program flow for your user interface here.\n\n #Creates new \"myNetwork\" object in the \"Network\" class\n myNetwork = Network()\n done = False\n while not done:\n\n action = input(\"\\n~~~\\nWhat would you like to do?\\n(Type \\\"show\\\" to display instructions)\\n\")\n\n #1. Print a user\n #2. Add a user\n #3. Add a connection\n #4. Print connections\n #5. Print users\n #6. Be able to quit the program\n #7. Deals with anything else (such as input you haven't defined)\n\n if action == \"show\":\n print(\"\"\"\\n\n\n USERS\n -----\n Make a new user account (make)\n Print existing users (print users)\n\n CONNECTIONS\n -----------\n Add a connection to an existing user account (add c)\n Print a user\\'s connections (print c)\n\n QUIT\n ----\n Quit the program (q)\n \"\"\")\n if action == \"make\":\n userInput = input(\"Choose a username: \")\n print(\"\\n\")\n myNetwork.addUser(userInput)\n\n if action == \"print users\":\n print(\"\\n\")\n myNetwork.printUsers()\n time.sleep(1)\n\n\n if action == \"add c\":\n user1 = input(\"Please print your username: \")\n user2 = input(\"Who would you like to connect to? \")\n print(\"\\n\")\n myNetwork.addConnection(user1, user2)\n print(\"Connection made!\")\n time.sleep(1)\n\n\n if action == \"print c\":\n userInput = input(\"Whose connections would you like to see? \")\n print(\"\\n\")\n myNetwork.printConnections(userInput)\n time.sleep(1)\n\n\n if action == \"q\":\n done = True\n\n else:\n print(\"Sorry, I don't understand that. Please try again.\")\n time.sleep(1)\n\n\n\n\n# Runs your program.\nif __name__ == '__main__':\n main()\n","sub_path":"socialNetwork.py","file_name":"socialNetwork.py","file_ext":"py","file_size_in_byte":5697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"101692405","text":"#!/usr/bin/env python3\nfrom urllib import request\nimport json\n\nimport argparse\nimport sys\n\nfrom threading import Thread\nfrom download import Download\n\nimport analysis\nimport util\n\nfilename = 'repos.txt'\n\ndef query(size):\n url = 'https://api.github.com'\n api = '/search/repositories'\n query = 'language:c&stars:>10&per_page='+size\n response = request.urlopen(url+api+\"?q=\"+query)\n s = response.read().decode('utf8')\n j = json.loads(s)\n f = open(filename, 'w')\n for item in j['items']:\n f.write(item['clone_url'] + \"\\t\" + str(item['stargazers_count']))\n f.write('\\n')\n f.close()\n print('result saved to '+filename)\n\ndef download(directory):\n Download(filename, t='git', directory=directory).download()\n\n'''\noutput format:\n[\n {\n 'name': 'linux-linux'\n 'url': 'http://github.com/linux/linux'\n 'loc': 34353\n 'size': 1245\n 'assert': 1152\n }\n]\n'''\ndef analyze(folder='tmp'):\n result = []\n print(\"doing loc analysis\")\n (locDict, assertDict) = analysis.loc(folder)\n print('doing size analysis')\n sizeDict = analysis.size(folder)\n # print('doing assert analysis')\n # assertDict = analysis.countAssert('tmp')\n # print('extracting urls')\n # urlDict = analysis.url(filename)\n for k in locDict.keys():\n d = {}\n d['name'] = k\n # d['url'] = urlDict[k]\n d['loc'] = locDict[k]\n d['size'] = sizeDict[k]\n d['assert'] = assertDict[k]\n result.append(d)\n s = json.dumps(result)\n print(s)\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-q', '--query', help='How many result to query github api')\nparser.add_argument('-d', '--download', help='Directory to download repos')\nparser.add_argument('-a', '--analyze', help='analyze repos')\nargs = parser.parse_args()\n\nif len(sys.argv)==1:\n parser.print_help()\nif (args.query):\n query(args.query)\nif (args.download):\n download(args.download)\nif (args.analyze):\n analyze(args.analyze)\n","sub_path":"SyntacticPatchingV1/scripts/backup/github_query_download/github.py","file_name":"github.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"438248241","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nimport csv\nimport os\nimport django\nfrom decimal import *\n\n\n\n#precisa dessa parte para falar com o models.py alem disso eu inseri o projeto no PYTHONPATH no windows\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"relatorios.settings\")\ndjango.setup()\nfrom extratos.models import *\n\n\ndef conferencia():\n\twith open('temp.txt', 'rt', encoding = \"utf-8\") as csvfile:\n\t\tdados = csv.reader(csvfile, delimiter=',', quotechar='\"')\n\t\tlista = []\n\t\tfor row in dados:\n\t\t\tlista.append(row)\n\n\tprop_saldo = {}\n\tresultado = []\n\tfor row in lista:\n\t\t#achou um proprietario? pega o codigo dele.\n\t\tif row[1] == \"3\" and row[2] == \"2\":\n\t\t\tcod_prop = int(row[17])\n \t\t#pegar o saldo final desse proprietario\n\n \t#confia que nunca tem outro proprietario antes do saldo do proprietario que esta na variavel!!!\n\t\tif row[1] == \"8\" and row[2] == \"2\":\n\n\t\t\tsaldo_arquivo = row[6].replace(\".\" , \"\").replace(\",\" , \".\")\n\n\t\t\tprop_saldo[cod_prop] = saldo_arquivo\n\n\terros = []\n\tfor cod_prop, saldo in prop_saldo.items():\n\t\ttry:\n\t\t\tp = Proprietario.objects.get(cod_proprietario = cod_prop )\n\t\texcept:\n\t\t\treturn(\"O proprietário %s não foi importado\" % (cod_prop,) )\n\t\tlancamentos = Lancamento.objects.filter(cod_proprietario = p.id)\n\n\n\t\tsaldo_db = p.saldo_anterior\n\t\tfor lancamento in lancamentos:\n\t\t\tif lancamento.credito == True:\n\t\t\t\tsaldo_db += lancamento.valor\n\t\t\telse:\n\t\t\t\tsaldo_db -= lancamento.valor\n\n\t\tresultado.append([cod_prop,saldo,saldo_db])\n\n\n\t\tif Decimal(saldo_db) != Decimal(saldo):\n\t\t\terros.append(cod_prop)\n\n\n\n\n\n\treturn erros, resultado\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"relatorios/extratos/confere_saldos.py","file_name":"confere_saldos.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"413206177","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom scipy.stats import linregress\n\nimport lib\n\nfeatures, targets, validate_features, validate_targets, dateRange = lib.loadNNData()\n\ntargets = np.sum(targets, axis=1)\nvalidate_targets = np.sum(validate_targets, axis=1)\nindex = np.arange(len(targets))\nslope, intercept, r_value, p_value, std_err = linregress(index,np.squeeze(targets))\n\nhistIndex = np.arange(len(targets))\nfutureIndex = np.arange(len(targets),len(targets)+len(validate_targets))\n\npredictions=[pred*slope+intercept for pred in futureIndex] \n\npredIndex = np.arange(len(targets),len(targets)+len(predictions))\n\n\nplt.figure()\nplt.plot(histIndex, targets, 'b--', label='History')\nplt.plot(futureIndex, validate_targets, 'b:', label='Future')\nplt.plot(predIndex, predictions, 'r:', label='Prediction')\nplt.ylabel('Cases as proportion of Pop')\nplt.xlabel('Time')\nplt.legend(loc='upper left')\nplt.show()","sub_path":"baselineTest.py","file_name":"baselineTest.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"335775863","text":"import os\nimport urllib\nimport cgi\nimport jinja2\nimport webapp2\n\nfrom model import *\n\nfrom google.appengine.api import users\nfrom google.appengine.ext import ndb\n\nJINJA_ENVIRONMENT = jinja2.Environment(\n loader=jinja2.FileSystemLoader(os.path.dirname('templates/')),\n extensions=['jinja2.ext.autoescape'],\n autoescape=True)\n\nDEFAULT_BUG_LIST = ''\nDEFAULT_COMMENT_LIST = ''\n\ndef bug_key(bug=DEFAULT_BUG_LIST):\n return ndb.Key('Bug', bug)\n\ndef comment_key(comment=DEFAULT_COMMENT_LIST):\n return ndb.Key('Comment', comment) \n\ndef DefaultTemplateValues(uri):\n user = users.get_current_user()\n if user:\n url = users.create_logout_url(uri)\n url_linktext = 'Logout'\n else:\n url = users.create_login_url(uri)\n url_linktext = 'Login'\n\n return {\n 'user': user,\n 'url': url,\n 'url_linktext': url_linktext,\n 'author': Author,\n }\n\ndef GetSortKey(param):\n if param == 'date_old_new':\n return +Bug.date\n elif param == 'date_new_old':\n return -Bug.date\n elif param == 'name_a_z':\n return +Bug.summary\n elif param == 'name_z_a':\n return -Bug.summary\n elif param == 'active':\n return +Bug.status\n elif param == 'inactive':\n return -Bug.status\n else:\n return -Bug.date\n\nclass Bugs(webapp2.RequestHandler):\n\n def get(self):\n bug = self.request.get('bug_id', '')\n if bug:\n bugs_query = Bug.query(Bug.key == ndb.Key(urlsafe=bug))\n else:\n bugs_query = Bug.query().order(\n GetSortKey(self.request.get('sortBy', '')))\n bugs = bugs_query.fetch()\n\n template_values = DefaultTemplateValues(self.request.uri)\n template_values.update({\n 'bugs': bugs,\n 'bug': urllib.quote_plus(bug),\n 'bug_key': bug_key,\n })\n\n template = JINJA_ENVIRONMENT.get_template('post.html')\n self.response.write(template.render(template_values))\n\nclass Comments(webapp2.RequestHandler):\n\n def get(self):\n comment = self.request.get('comment_id', '')\n if comment:\n comments_query = Comment.query(Comment.key == ndb.Key(urlsafe=comment)).order(+Comment.date)\n else:\n comments_query = Comment.query().order(-Comment.date)\n\n comments = comments_query.fetch()\n\n template_values = DefaultTemplateValues(self.request.uri)\n template_values.update({\n 'comments': comments,\n 'comment': urllib.quote_plus(comment),\n 'comment_key': comment_key,\n })\n\n template = JINJA_ENVIRONMENT.get_template('feature.html')\n self.response.write(template.render(template_values))\n\nclass bug(webapp2.RequestHandler):\n\n def get(self):\n template = JINJA_ENVIRONMENT.get_template('newbug.html')\n self.response.write(template.render(DefaultTemplateValues(self.request.uri)))\n\n def post(self):\n bug = self.request.get('bug_id', None)\n\n if bug is None:\n bug = Bug()\n else:\n bug = ndb.Key(urlsafe=bug).get()\n\n if users.get_current_user():\n bug.author = Author(\n identity=users.get_current_user().user_id(),\n email=users.get_current_user().email())\n \n bug.summary = self.request.get('summary')\n bug.description = self.request.get('description')\n\n if self.request.get('status') == 'active':\n bugstatus = Bug(status=Status.ACTIVE)\n elif self.request.get('status') == 'inactive':\n bugstatus = Bug(status=Status.INACTIVE)\n\n bug.status = bugstatus.status\n bug.sortBy = self.request.get('sortBy')\n key = bug.put()\n self.redirect('/')\n\nclass comment(webapp2.RequestHandler):\n def post(self):\n feature = ndb.Key(urlsafe=self.request.get('feature_id', '')).get()\n comment = Comment()\n if users.get_current_user():\n comment.author = Author(\n identity=users.get_current_user().user_id(),\n email=users.get_current_user().email())\n \n comment.usercomment = self.request.get('usercomment')\n\n feature.comments.append(comment)\n feature.put()\n self.redirect('/feature?feature_id=' + self.request.get('feature_id'))\n\nclass Feature(webapp2.RequestHandler):\n def get(self):\n template = JINJA_ENVIRONMENT.get_template('feature.html')\n feature = ndb.Key(urlsafe=self.request.get('feature_id', '')).get()\n if feature is None:\n self.redirect('/')\n template_values = DefaultTemplateValues(self.request.uri)\n template_values['feature'] = feature\n template_values['feature_id'] = self.request.get('feature_id')\n\n self.response.write(template.render(template_values))\n\napp = webapp2.WSGIApplication([\n ('/', Bugs),\n ('/feature', Feature),\n ('/newbug', bug),\n ('/add', bug),\n ('/postcomment', comment),\n ('/newcomment', comment),\n], debug=True)","sub_path":"buggy.py","file_name":"buggy.py","file_ext":"py","file_size_in_byte":5016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"425499881","text":"\nimport matplotlib.pyplot as plt\nimport pandas as pd\ndata = pd.read_csv(\"C:/Users/jaymin/Documents/Character-Prediction-Using-Mobile-Sensors/DataAnalysis/train_data_analysis.csv\")\n#fig = plt.figure()\n#ax = fig.add_axes([0,0,1,1])\nwid = 0.5\nplt.bar(data['label'],data['avg'])\nplt.title(\"Average timestamp for every label\")\nplt.xlabel(\"Labels\")\nplt.ylabel(\"Timestamps\")\nplt.savefig(\"average_train.eps\",format='eps')\nplt.show()\n","sub_path":"DataAnalysis/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"339831918","text":"from newsie.models import Article\nimport numpy as np\nimport pandas as pd\nfrom sklearn.neighbors import NearestNeighbors\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.cluster import DBSCAN\nfrom utils.dummy_fun import dummy_fun\nfrom sklearn import metrics\nfrom newsie.publications.get_articles import categories\n\ndef average_silhouette():\n\n top_eps_values = []\n for index, category in enumerate(categories()):\n articles = Article.objects.filter(category__exact=category)\n\n #Creates a list of the pre-processed Article tokens\n texts = [art.tokens for art in articles]\n\n tfidf = TfidfVectorizer(\n use_idf=True,\n tokenizer=dummy_fun, #No need to pre-process,\n preprocessor=dummy_fun) # since it was done while webscraping\n \n tfidf_matrix = tfidf.fit_transform(texts)\n # tfidf_matrix = tfidf_matrix.todense()\n\n eps = .05\n top_s_score = 0\n top_eps_value = 0\n\n while eps <= 1:\n dbscan = DBSCAN(eps=eps, min_samples=2, metric='cosine')\n model = dbscan.fit(tfidf_matrix)\n labels = model.labels_\n if np.unique(labels).size >= 2:\n s_score = metrics.silhouette_score(tfidf_matrix, labels, metric=\"cosine\")\n if s_score > top_s_score:\n top_s_score = round(s_score, 3)\n top_eps_value = eps\n eps = round(eps + 0.05, 2)\n\n print(f\"Category: {category} | Top S_Score: {top_s_score} | Eps Value: {top_eps_value}\")\n top_eps_values.append(top_eps_value)\n top_s_score = 0\n top_eps_value = 0\n\n average_top_eps_value = round(np.mean(top_eps_values), 3)\n print(top_eps_values)\n print(f\"Average Top Eps Value: {average_top_eps_value}\")\n\n","sub_path":"newsie/scripts/average_silhouette.py","file_name":"average_silhouette.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"83242450","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nimport math as m\nimport random as ran\nfrom scipy.optimize import curve_fit\nfrom scipy.integrate import quad\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom decimal import Decimal\n#-----------------------------------------------\n# dataframe with the cross section points as in\n# \"Ultrahigh-Energy Neutrino Interactions\" Raj Gandhi\n#-----------------------------------------------\nncs={\n 'Energy (GeV)':[10**1,10**2,10**3,10**4,10**5,10**6,10**7,10**8,10**9,10**10,10**11,10**12],\n 'CrossSectionCC':[0.777*10**(-37),0.697*10**(-36),0.625*10**(-35),0.454*10**(-34),0.196*10**(-33),0.611*10**(-33),0.176*10**(-32),0.478*10**(-32),0.123*10**(-31),0.301*10**(-31),0.706*10**(-31),0.159*10**(-30)],\n 'minelasticityCC':[0.483,0.477,0.472, 0.426,0.332,0.273,0.250,0.237,0.225,0.216,0.208,0.205]}\n\nsimulatedncs={\n 'Energy (GeV)':[1.00*10,1.26*10,1.58*10,2.00*10,2.51*10,3.16*10,3.98*10,5.01*10,6.31*10,7.94*10,1*10**2,1.26*10**2,1.58*10**2,2.00*10**2,2.51*10**2,3.16*10**2,3.98*10**2,5.01*10**2,6.31*10**2,7.94*10**2,1*10**3,1.26*10**3,1.58*10**3,2.00*10**3,2.51*10**3,3.16*10**3,3.98*10**3,5.01*10**3,6.31*10**3,7.94*10**3,1*10**4,1.26*10**4,1.58*10**4,2.00*10**4,2.51*10**4,3.16*10**4,3.98*10**4,5.01*10**4,6.31*10**4,7.94*10**4,1*10**5,1.26*10**5,1.58*10**5,2.00*10**5,2.51*10**5,3.16*10**5,3.98*10**5,5.01*10**5,6.31*10**5,7.94*10**5,1*10**6,1.26*10**6,1.58*10**6,2.00*10**6,2.51*10**6,3.16*10**6,3.98*10**6,5.01*10**6,6.31*10**6,7.94*10**6,1*10**7],\n 'CrossSCC': [ 8.08*10**-38, 1*10**-37, 1.24*10**-37, 1.55*10**-37, 1.92*10**-37, 2.39*10**-37, 2.96*10**-37,3.69*10**-37,4.58*10**-37,5.71*10**-37,7.1*10**-37,8.85*10**-37,1.1*10**-36,1.38*10**-36,1.71*10**-36,2.14*10**-36,2.67*10**-36,3.32*10**-36,4.14*10**-36,5.15*10**-36,6.39*10**-36,7.93*10**-36,9.81*10**-36,1.21*10**-35,1.49*10**-35,1.83*10**-35,2.23*10**-35,2.71*10**-35,3.28*10**-35,3.95*10**-35,4.72*10**-35,5.62*10**-35,6.65*10**-35,7.83*10**-35,9.16*10**-35,1.07*10**-34,1.24*10**-34,1.43*10**-34,1.64*10**-34,1.88*10**-34,2.14*10**-34,2.44*10**-34,2.76*10**-34,3.13*10**-34,3.53*10**-34,3.97*10**-34,4.47*10**-34,5.01*10**-34,5.62*10**-34,6.29*10**-34,7.02*10**-34,7.84*10**-34,8.73*10**-34,9.72*10**-34,1.08*10**-33,1.2*10**-33,1.33*10**-33,1.47*10**-33,1.63*10**-33,1.8*10**-33,1.99*10**-33],\n 'CrossNC':[2.49*10**-38,3.09*10**-38, 3.84*10**-38, 4.78*10**-38, 5.93*10**-38, 7.37*10**-38, 9.17*10**-38, 1.14*10**-37, 1.42*10**-37, 1.77*10**-37, 2.2*10**-37, 2.74*10**-37, 3.42*10**-37, 4.27*10**-37, 5.33*10**-37, 6.65*10**-37, 8.3*10**-37, 1.04*10**-36, 1.29*10**-36, 1.61*10**-36, 2*10**-36, 2.49*10**-36, 3.09*10**-36, 3.83*10**-36, 4.73*10**-36, 5.83*10**-36, 7.16*10**-36, 8.75*10**-36, 1.07*10**-35, 1.29*10**-35, 1.56*10**-35, 1.87*10**-35, 2.23*10**-35, 2.64*10**-35, 3.11*10**-35, 3.65*10**-35, 4.27*10**-35, 4.96*10**-35, 5.74*10**-35, 6.61*10**-35, 7.59*10**-35, 8.68*10**-35, 9.89*10**-35, 1.12*10**-34, 1.28*10**-34, 1.44*10**-34, 1.63*10**-34, 1.83*10**-34, 2.06*10**-34, 2.32*10**-34, 2.6*10**-34, 2.91*10**-34, 3.25*10**-34, 3.62*10**-34, 4.04*10**-34, 4.5*10**-34, 5*10**-34, 5.56*10**-34, 6.16*10**-34, 6.83*10**-34, 7.56*10**-34],\n\n 'Total_CS':[]\n\n}\n\nfor a in range(len(simulatedncs['CrossSCC'])):\n simulatedncs['Total_CS'].append(simulatedncs['CrossSCC'][a]+simulatedncs['CrossNC'][a])\n\ndf = pd.DataFrame(data=ncs)\nsimulated = pd.DataFrame(data=simulatedncs)\n#print(simulated)\n#print(ncs['Energy (GeV)'][1])\n#-----------------------------------------------\n# Fit of the linear part till 10^12 eV\n#-----------------------------------------------\ndef fitfuncUND(x, a, b):\n\treturn a * x + b\n\n#popt, _ = curve_fit(fitfuncUND,df['Energy (GeV)'][:3],df['CrossSectionCC'][:3])\n#a,b=popt\n\nallm=[]\nallq=[]\nfor ele in range(len(ncs['minelasticityCC'])-1):\n params, _ =curve_fit(fitfuncUND,ncs['Energy (GeV)'][ele:ele+2],ncs['minelasticityCC'][ele:ele+2])\n allmb,allqb=params\n allm.append(allmb)\n allq.append(allqb)\n#print(\"allm\",allm)\n#print(\"allq\",allq)\n\ndef Bjorken(x):\n ss=[]\n if hasattr(x, \"__len__\"):\n for b in x:\n for a in range(len(ncs['minelasticityCC'])-1):\n if b>=ncs['Energy (GeV)'][a] and b=ncs['Energy (GeV)'][a] and x 1* 10**7:\n if interaction=='NC':\n cross_interaction=fitfuncOVE(constNC,indexNC,x)\n elif interaction=='CC':\n cross_interaction=fitfuncOVE(constCC,indexCC,x)\n elif interaction=='Total':\n cross_interaction=fitfuncOVE(constNC,indexNC,x)+fitfuncOVE(constCC,indexCC,x)\n else:\n print(\"No other known type of interactions\")\n return 1/(Na*cross_interaction)\n else:\n print(\"Energy too high > 10^21 eV or too low < 10 GeV\")\n return 0\n\ndef Lint(x,interaction):\n if hasattr(x, \"__len__\"):\n ss=[]\n for a in x:\n ss.append(buildingLint(a,interaction))\n return ss\n else:\n return buildingLint(x,interaction) \n\n\n\n#-------------------------------------------------------------\n# Earth density profile wrt x=r/EarthRadius\n#-------------------------------------------------------------\nEarthRadius=6371 #km\nradia=[1221.5,3480,5701,5771,5971,6151,6346.6,6356,6368,6371]\ndef buildingDensity(r):\n ratio=r/EarthRadius\n status=0\n if r< radia[0]:\n status=10\n return (13.0885-8.8381*ratio**2,status)\n elif r>radia[0] and r< radia[1]:\n status=9\n return (12.5815-1.2638*ratio-3.6426*ratio**2-5.5281*ratio**3,status)\n elif r> radia[1] and rradia[2] and rradia[3] and r radia[4] and r radia[5] and r< radia[6]:\n status=4\n return (2.691 + 0.6924 *ratio,status)\n elif r> radia[6] and r radia[7] and r< radia[8]:\n status=2\n return (2.6,status)\n elif r> radia[8] and r<=EarthRadius:\n status=1\n return (1.02,status)\n else:\n print (\"Radius out of limits\")\n return 0\n\ndef density_profile(r):\n \"\"\"\n call the buildingDensity function for r = scalar or list\n return the density value for the given r\n \"\"\"\n\n ss=[]\n if hasattr(r, \"__len__\"):\n for a in r:\n ss.append(buildingDensity(a)[0])\n return ss\n else:\n return buildingDensity(r)[0]\n\n\n\ndef int_lentgth_earth(theta):\n \"\"\"\n integral of rho x dl (g/cm^2)\n each integral calculated in angle x from cos-1(D/Ri) to cos-1(D/Ri+1)\n where Ri is the radius of the i-th concentric Earth shell\n for i = 0 Ri=0\n \"\"\"\n distance_from_center = EarthRadius*np.sin(np.radians(180-theta))\n #print(\"D\",distance_from_center)\n status=buildingDensity(distance_from_center)[1]\n #print(\"Numbers of traversed layers\",status)\n #print(\"radia\",radia[-status:])\n \n integral_extrema=[0]\n for rr in radia[-status:]:\n integral_extrema.append(np.arccos(distance_from_center/rr))\n #print(\"Extremis\",integral_extrema)\n final=[]\n for a in range(status):\n integrand = lambda x: 2*buildingDensity(distance_from_center/np.cos(x))[0] * distance_from_center*10**5/(np.cos(x)*np.cos(x))\n Integral=quad(integrand,integral_extrema[a],integral_extrema[a+1])\n final.append(Integral[0])\n #print(\"FINAL value of the integral contributions\",final)\n int_length=sum(final)\n #print(\"sum of contributions:\",int_length)\n return(int_length)\n\natm_sup_limit=455\ndef atmosphere(h):\n \"\"\"\n model of the density profile of the atmosphere\n h in km\n \"\"\"\n ss=[]\n if hasattr(h, \"__len__\"):\n for a in h:\n if a > EarthRadius+5 and a < EarthRadius+15: # h in km\n a-=(EarthRadius+5)\n ss.append(1.225 *10**-3 * m.exp(-a/9.192))\n elif a > EarthRadius+15 and a< EarthRadius+atm_sup_limit:\n a-=(EarthRadius+5)\n ss.append(1.944 *10**-3 * m.exp(-a/6.452))\n else:\n #print(\"Too high!!\")\n ss.append(0)\n return(ss)\n else:\n if h > EarthRadius+5 and h < EarthRadius+15: # h in km\n h-=(EarthRadius+5)\n return 1.225 *10**-3 * m.exp(-h/9.192)\n elif h > EarthRadius+15 and h< EarthRadius+atm_sup_limit:\n h-=(EarthRadius+5)\n return 1.944 *10**-3 * m.exp(-h/6.452)\n else:\n #print(\"Too high!!\")\n return 0\n\ndef int_length_atm(theta):\n \"\"\"\n integral of rho x dl (g/cm^2)\n each integral calculated in angle x from cos-1(D/Ri) to cos-1(D/Ri+1)\n where Ri is: \n EarthRadius+5 km\n EarthRadius+15 km\n EarthRadius+atm_sup_limit km\n \"\"\"\n distance_from_center = EarthRadius*np.sin(np.radians(180-theta))\n #print(\"D\",distance_from_center)\n integral_extrema=[]\n #added a +3.5 on first integral\n integral_extrema.append(np.arccos(distance_from_center/(EarthRadius+3.5)))\n integral_extrema.append(np.arccos(distance_from_center/(EarthRadius+15)))\n integral_extrema.append(np.arccos(distance_from_center/(EarthRadius+atm_sup_limit)))\n #print(\"Extremis\",integral_extrema)\n final=[]\n for a in range(2):\n integrand = lambda x: atmosphere(distance_from_center/np.cos(x)) * distance_from_center*10**5/(np.cos(x)*np.cos(x))\n Integral=quad(integrand,integral_extrema[a],integral_extrema[a+1])\n final.append(Integral[0])\n #print(\"FINAL values for ATMOSPHERE\",final)\n int_length=sum(final)\n #print(\"ATMOSPHERE sum of contributions:\",int_length)\n return(int_length)\n\n\ndef sea(h):\n \"\"\"\n to be deleted or implemented in case of a more sofisticated \n sea-water density profile\n By now assumed const = 1.040 g/cm^2\n \"\"\"\n ss=[]\n if hasattr(h, \"__len__\"):\n for a in h:\n if a > EarthRadius and a < EarthRadius+2: # h in km\n #a-=EarthRadius\n ss.append(1.040)\n elif a > EarthRadius+2 and a< EarthRadius+5:\n #a-=EarthRadius\n ss.append(1.040)\n else:\n ss.append(0)\n return(ss)\n else:\n if h > EarthRadius and h < EarthRadius+2: # h in cm\n # h-=EarthRadius\n return 1.040\n elif h > EarthRadius+2 and h< EarthRadius+5:\n #h-=EarthRadius*10**5\n return 1.040\n else:\n #print(\"Too high!!\")\n return 0\n \n\n#def sea_profile(theta):\n# \"\"\"\n# product of rho x l\n# with l = h/cos(theta)\n# Should be an integral if sea(h) implemented in a different way\n# \"\"\"\n# h=3.5*10**5\n# return 1.040*h/abs(np.cos(np.radians(theta)))\n\n#--------------------------------------------------\n# sea profile integrate to account for the Earth curvature\n#--------------------------------------------------\ndef sea_profile(theta):\n \"\"\"\n \"\"\"\n distance_from_center = EarthRadius*np.sin(np.radians(180-theta))\n integrand = lambda x: sea(distance_from_center/np.cos(x)) * distance_from_center*10**5/(np.cos(x)*np.cos(x))\n Integral=quad(integrand,np.arccos(distance_from_center/EarthRadius),np.arccos(distance_from_center/(EarthRadius+3.5)))\n return(Integral[0])\n \ndef total_slant(theta):\n ss=[]\n if hasattr(theta, \"__len__\"):\n for a in theta:\n if a < 90:\n ss.append(int_length_atm(a)+sea_profile(a))\n else:\n ss.append(int_length_atm(a)+sea_profile(a)+int_lentgth_earth(a))\n return(ss)\n else:\n if theta < 90:\n return int_length_atm(theta)+sea_profile(theta)\n else:\n return int_length_atm(theta)+sea_profile(theta)+int_lentgth_earth(theta)\n \n\n\n#def number_of_Lint(energy,theta):\n# final=np.zeros((len(energy),len(theta)))\n# encounter=0\n# for x in energy:\n# lint=Lint(x,'Total')\n# angcounter=0\n# for ang in theta:\n# final[encounter][angcounter]=total_slant(ang)/lint\n# angcounter+=1\n# encounter+=1\n# return final\n#------------------------------------------------------\n#improved performances\n#------------------------------------------------------\ndef number_of_Lint(energy,theta):\n status=0\n if hasattr(energy, \"__len__\") and hasattr(theta, \"__len__\"):\n final=np.zeros((len(energy),len(theta)))\n encounter=0\n lint=Lint(energy,'Total')\n total=total_slant(theta)\n for x in lint:\n angcounter=0\n for y in total:\n final[encounter][angcounter]=y/x\n angcounter+=1\n encounter+=1\n status=1\n return final,status\n elif hasattr(energy, \"__len__\") and np.isscalar(theta):\n final=np.zeros(len(energy))\n status=2\n #print(\"STATO\",status)\n encounter=0\n lint=Lint(energy,'Total')\n total=total_slant(theta)\n for x in lint:\n final[encounter]=total/x\n encounter+=1\n return final,status\n elif hasattr(theta, \"__len__\") and np.isscalar(energy):\n final=np.zeros(len(theta))\n status=3\n #print(\"STATO\",status)\n angcounter=0\n lint=Lint(energy,'Total')\n total=total_slant(theta)\n for y in total:\n final[angcounter]=y/lint\n angcounter+=1\n return final,status\n \n else:\n status=4\n #print(\"STATO\",status)\n return total_slant(theta)/Lint(energy,'Total'),status\n#------------------------------------------------------\n# neutrino survival probability\n#------------------------------------------------------\ndef Survival_probability_mean(energy,theta):\n Lint,status=number_of_Lint(energy,theta)\n return np.exp(-Lint)\n\ndef muon_range(energy):\n alpha=0.274 #GeV/m\n beta=3.49*10**-4 #1/m\n Ec=alpha/beta\n ss=[]\n rho=1 #g/cm^3 \n if hasattr(energy, \"__len__\"):\n for x in energy:\n E_muon=x*(1-Bjorken(x))\n if E_muon90:\n under.append(ang)\n else:\n over.append(ang)\n AeffOver=[]\n AeffUnder=[]\n reco_eff=0.01\n A_times_recoeff=A_geom*10**-4*reco_eff*90/len(over) #area in m^2 \n \n #working configuration\n #for ene in energy:\n #AeffOver.append(sum(final_prbability(ene,over)))\n # AeffOver.append(final_prbability(ene,over[1]))\n #AeffUnder.append(sum(final_prbability(ene,under)))\n # AeffUnder.append(final_prbability(ene,under[-1]))\n for ang in theta:\n ciccio1=[]\n ciccio2=[]\n if ang < 90:\n for ene in energy:\n ciccio1.append(A_times_recoeff*final_prbability(ene,ang))\n AeffOver.append(ciccio1)\n else:\n for ene in energy:\n ciccio2.append(A_times_recoeff*final_prbability(ene,ang))\n AeffUnder.append(ciccio2)\n #print(len(AeffOver))\n #AeffOver=np.array(AeffOver)#*A_times_recoeff\n #AeffUnder=np.array(AeffUnder)#*A_times_recoeff\n return (AeffOver,AeffUnder)\n \ndef nu_flux(energy):\n ss=[]\n if hasattr(energy, \"__len__\"):\n for ene in energy:\n ss.append(ene**-2*10**-8) #evts/GeV*s*cm^2\n \n return ss\n else:\n return 10**-8*energy**-2\n \n \ndef Numb_events(energy,theta):\n \"\"\"\n differetial number of events in energy and in theta\n \"\"\"\n reco_eff=0.01\n numb_Lint,status=number_of_Lint(energy,theta)\n factor=year*A_geom*2*np.pi*reco_eff\n proba=final_prbability(energy,theta)\n flux=nu_flux(energy)\n if status==1:\n binwidth=(energy[-1]-energy[0])/len(energy)\n # print(binwidth)\n events=np.zeros((len(energy),len(theta)))\n for ene in range(len(energy)):\n for ang in range(len(theta)):\n events[ene][ang]=proba[ene][ang]*flux[ene]*factor*binwidth\n return events\n elif status==2:\n binwidth=(energy[-1]-energy[0])/len(energy)\n events=[]\n for ene in range(len(energy)):\n events.append(proba[ene]*flux[ene]*factor*binwidth)\n return events\n \n elif status==3:\n events=[]\n binwidth=(theta[-1]-theta[0])/len(theta)\n for ang in range(len(theta)):\n events.append(proba[ang]*flux*factor*binwidth)\n return events\n elif status==4:\n return proba*flux*factor*np.sin(np.radians(theta))\n\n\ndef sum_of_events(energy,theta):\n #limit1=a\n #limit2=b\n #events=Numb_events(energy,theta)\n sums=[]\n for ang in theta:\n sums.append(sum(Numb_events(energy,ang)))\n return sums\n\ndef check(energy,theta):\n events=sum_of_events(energy,theta)\n selection=[]\n cumulative=[]\n binwidth=(theta[-1]-theta[0])/len(theta)\n for ang in range(len(theta)):\n if theta[ang]>90:\n selection.append(events[ang]*binwidth*abs(np.sin(np.radians(ang))))\n cumulative.append(sum(selection))\n else:\n cumulative.append(0)\n print(\"CUMULATIVE\",sum(cumulative))\n return cumulative\n \n#-------------------------------------------------------------\n# Plotting functions\n#-------------------------------------------------------------\n\nx_lint = np.logspace(1,11, 100)#np.linspace(10,0.99*10**12, 100000)\nx_lineO = np.logspace(6,12, 100)#x_lineO = np.linspace(10**6,10**12, 100)\ny_lineO=fitfuncOVE(constCC,indexCC,x_lineO)\ny_lineNC=fitfuncOVE(constNC,indexNC,x_lineO)\ny_line_total=[]\nfor a in range(len(y_lineO)):\n y_line_total.append(y_lineO[a]+y_lineNC[a])\n \nradius=np.linspace(0,EarthRadius,100)\nhatm=np.linspace(EarthRadius+5,EarthRadius+atm_sup_limit,100)\nhsea=np.linspace(EarthRadius+0.1,EarthRadius+4.9999,100)\nttheta=np.linspace(0.1,89.9,100)\nstheta=np.linspace(90.01,179.9,100)\ncc=[]\nff=[]\nfor aa in stheta:\n cc.append(int_lentgth_earth(aa)) \n ff.append(sea_profile(aa))\n #print(stheta)\ndd=[]\nfor bb in stheta:\n dd.append(int_length_atm(bb))\n\n#-------------------------------------------------------------\n#surface plot number generators\n#-------------------------------------------------------------\nNumber_of_points=50\n#x_energy = np.linspace(10,10**11, Number_of_points)\nx_energy = np.logspace(1,7, Number_of_points)\nzenithy=np.linspace(0,179.9,Number_of_points)\n#zenithy=np.logspace(0,2,Number_of_points)\n\n#-------------------------------------------------------------\n# Neutrino functions: Cross Section CC, Bjorken y, Interaction Length in (g/cm^2)\n#-------------------------------------------------------------\nf=plt.figure()\nax1=f.add_subplot(311)\ndf.plot(kind='scatter',x='Energy (GeV)',y='CrossSectionCC',color='green',ax=ax1, logx=True, logy=True)\nsimulated.plot(kind='scatter',x='Energy (GeV)',y='Total_CS',color='red',ax=ax1, logx=True, logy=True)\nsimulated.plot(kind='scatter',x='Energy (GeV)',y='CrossSCC',color='green',ax=ax1, logx=True, logy=True)\nsimulated.plot(kind='scatter',x='Energy (GeV)',y='CrossNC',color='blue',ax=ax1, logx=True, logy=True)\n#ax1.plot(x_line,y_line,'b--')\nax1.plot(x_lineO,y_lineO,'+',markersize=2, color='g')#'g--')\nax1.plot(x_lineO,y_lineNC,'+',markersize=2, color='b')#'b--')\nax1.plot(x_lineO,y_line_total,'+',markersize=2, color='r')\nax1.set_title('nu N CC Cross Section')\nax2=f.add_subplot(312)\ndf.plot(kind='scatter',x='Energy (GeV)',y='minelasticityCC',color='g',ax=ax2,logx=True,logy=True)\nax2.plot(x_lint,Bjorken(x_lint),'+',markersize=2, color='r')\nax2.set_title('Mean Bjorken y nu N CC')\nax3=f.add_subplot(313)\n#ax3.plot(x_line,Lint(x_line),'r--')\nax3.plot(x_lint,Lint(x_lint,'CC'),'+',markersize=2, color='g')#'g--')\nax3.plot(x_lint,Lint(x_lint,'Total'),'+',markersize=2, color='r')#'r--')\nax3.plot(x_lint,Lint(x_lint,'NC'),'+',markersize=2, color='b')#'b--')\nax3.set_yscale('log')\nax3.set_xscale('log')\nax3.set_ylabel('Lint (g/cm^2)')\nax3.set_xlabel('E_nu (GeV)')\nax3.set_title('Interaction Length')\nf.suptitle('Neutrino property functions')\n#-------------------------------------------------------------\n# Earth: 0) density profile vs radius; 4) slant depth (g/cm^2) vs angle\n#-------------------------------------------------------------\n\nf2=plt.figure()\nax=f2.add_subplot(121)\nax.plot(radius, density_profile(radius),'b-')\nax.set_ylabel('Density')\nax.set_xlabel('Earth radius (km)')\nax.set_title('Earth density profile')\nax4=f2.add_subplot(122)\n#ax4.plot(stheta,int_lentgth_earth(stheta),'b--')\nax4.plot(stheta,cc,'+',markersize=2, color='b')\nax4.set_title('slant depth')\nax4.set_ylabel('x rho (g/cm^2)')\nax4.set_xlabel('zenith angle (deg)')\nf2.suptitle('Earth')\n#-------------------------------------------------------------\n# Atmosphere: 5) density profile vs height ; 6) slanth depth (g/cm^2) vs angle\n#-------------------------------------------------------------\n\nf3=plt.figure()\nax5=f3.add_subplot(121)\nax5.plot(hatm, atmosphere(hatm),'+',markersize=2, color='g')\nax5.set_ylabel('Density')\nax5.set_xlabel('Atmoosphere height (km)')\nax5.set_yscale('log')\nax6=f3.add_subplot(122)\n#ax6.plot(stheta,int_length_atm(stheta),'b--')\nax6.plot(stheta,dd,'+',markersize=2, color='b')#'g--')\nax6.set_ylabel('x rho (g/cm^2)')\nax6.set_xlabel('zenith angle (deg)')\nax6.set_yscale('log')\nf3.suptitle('Atmosphere')\n#-------------------------------------------------------------\n# Sea: 7) density profile vs height (0 = sea bed, 3.5*10**5 sea level for ARCA;\n# 8) slanth depth (g/cm^2) vs angle\n#-------------------------------------------------------------\n\nf4=plt.figure()\nax7=f4.add_subplot(121)\nax7.plot(hsea, sea(hsea),'+',markersize=2, color='b')\nax7.set_ylabel('Sea Density')\nax7.set_xlabel('Sea height (km)')\nax8=f4.add_subplot(122)\n#ax6.plot(stheta,int_length_atm(stheta),'b--')\n#ax8.plot(ttheta,sea_profile((3.5+EarthRadius)*10**5,ttheta),'g--')\nax8.plot(stheta,ff,'g--')\n#ax8.plot(stheta,sea_profile(3.5+EarthRadius),'g--')\nax8.set_ylabel('x rho (g/cm^2)')\nax8.set_xlabel('zenith angle (deg)')\nax8.set_yscale('log')\nf4.suptitle('Sea')\n\n#-------------------------------------------------------------\n# TOTAL SLANT DEPTH vs ZENITH ANGLE\n#-------------------------------------------------------------\nf5=plt.figure()\nax9=f5.add_subplot(111)\nax9.plot(zenithy,total_slant(zenithy),'+',markersize=2, color='r')\n#ax9.plot(stheta,cc,'b--')\n#ax9.plot(stheta,dd,'g--')\n#ax9.plot(stheta,sea_profile(stheta),'g--')\nax9.set_ylabel('x rho (g/cm^2)')\nax9.set_xlabel('zenith angle (deg)')\nax9.set_yscale('log')\nf5.suptitle('TOTAL SLANT DEPTH vs ZENITH')\n\n\n\n#-------------------------------------------------------------\n# SURFACE PLOTS:\n# 10) Number on Lint; 11) survival probability; 12) survival at can level\n# 13) Interaction inside can; 14) 12*13= final probability\n#-------------------------------------------------------------\nfig = plt.figure()\nax10 = fig.add_subplot(121, projection='3d')\nax10.set_title('zenith energy # of Lint')\nX1=x_energy\nY1=zenithy\nZ1=number_of_Lint(X1,Y1)[0]\nX1, Y1 = np.meshgrid(X1, Y1)\nsurf = ax10.plot_surface(X1, Y1, Z1, cmap=cm.coolwarm,linewidth=0, antialiased=False)\nax10.set_xlabel('energy (GeV)')\nax10.set_ylabel('zenith angle (deg)')\n#ax10.colorbar(surf, shrink=0.5, aspect=5)\nax11 = fig.add_subplot(122, projection='3d')\nZ2=Survival_probability_mean(x_energy,zenithy)\nax11.set_xlabel('energy (GeV)')\nax11.set_ylabel('zenith angle (deg)')\nsurf1=ax11.plot_surface(X1, Y1, Z2, cmap=cm.coolwarm,linewidth=0, antialiased=False)\n#plt.imshow(number_of_Lint(x_lint,zenithy),origin='lower',interpolation='none')\n#fig.suptitle(\"distribution\")\nfig.colorbar(surf1, shrink=0.5, aspect=5)\n\nfigg= plt.figure()\naxmuon = figg.add_subplot(111)\naxmuon.set_title('muon range')\naxmuon.plot(x_energy,muon_range(x_energy),'+',markersize=2, color='r')\naxmuon.plot(x_energy,radius_can(x_energy),'+',markersize=2, color='g')\naxmuon.set_xlabel('energy (GeV)')\naxmuon.set_ylabel('Range (g/cm^2)')\naxmuon.set_xscale('log')\n\n\nfigmuon = plt.figure()\nax12 = figmuon.add_subplot(231, projection='3d')\nX2=x_energy\nY2=zenithy\nZ3=nu_survival_can_level(X2,Y2)\nZ4=nu_interaction_inside_can(X2,Y2)\nZ5=final_prbability(X2,Y2)\nX2, Y2 = np.meshgrid(X2, Y2)\nax12.set_xlabel('energy (GeV)')\nax12.set_ylabel('zenith angle (deg)')\nax12.set_title(\"survival at can level\")\nsurf2=ax12.plot_surface(X2, Y2, Z3, cmap=cm.coolwarm,linewidth=0, antialiased=False)\n\n\nax13 = figmuon.add_subplot(232, projection='3d')\nax13.set_xlabel('energy (GeV)')\nax13.set_ylabel('zenith angle (deg)')\nsurf3=ax13.plot_surface(X2, Y2, Z4, cmap=cm.coolwarm,linewidth=0, antialiased=False)\nax13.set_title(\"Interaction inside can\")\n#plt.imshow(number_of_Lint(x_lint,zenithy),origin='lower',interpolation='none')\nax14 = figmuon.add_subplot(233, projection='3d')\nax14.set_xlabel('energy (GeV)')\nax14.set_ylabel('zenith angle (deg)')\nax14.set_title(\"Final Probability\")\nsurf2=ax14.plot_surface(X2, Y2, Z5, cmap=cm.coolwarm,linewidth=0, antialiased=False)\n\n\n#print(\"_---------------______________------___DEBUG_______------_______---_--_-__-_-_-_--_-__\")\nE_fixed=10**7\nax15 = figmuon.add_subplot(234)\nax15.plot(zenithy,nu_survival_can_level(E_fixed,zenithy),'+',markersize=2)\n\nax16 = figmuon.add_subplot(235)\nax16.plot(zenithy,nu_interaction_inside_can(E_fixed,zenithy),'+',markersize=2)\n\nax17 = figmuon.add_subplot(236)\nax17.plot(zenithy,final_prbability(E_fixed,zenithy),'+',markersize=2)\n\n#TeVSky = np.logspace(3,6, Number_of_points)\n#PeVSky = np.logspace(6,9, Number_of_points)\n#EeVSky = np.logspace(9,11, Number_of_points)\n\n#TeVSky = np.linspace(10**3,10**6, Number_of_points)\n#PeVSky = np.linspace(10**6,10**9, Number_of_points)\n#EeVSky = np.linspace(10**9,10**11, Number_of_points)\n\nTeVSky = np.geomspace(10**3,10**6, Number_of_points)\nPeVSky = np.geomspace(10**6,10**9, Number_of_points)\nEeVSky = np.geomspace(10**9,10**11, Number_of_points)\n\nNevents=plt.figure()\nax18=Nevents.add_subplot(231,projection='3d')\nax18.set_title('Number of events')\nX3=x_energy\nY3=zenithy\nZ6=Numb_events(X3,Y3)\nX3, Y3 = np.meshgrid(X3, Y3)\nsurf3=ax18.plot_surface(X3, Y3, Z6, cmap=cm.coolwarm,linewidth=0, antialiased=False)\nax19=Nevents.add_subplot(232)\nax19.set_title(Decimal(str(E_fixed)))\nax19.plot(zenithy,Numb_events(E_fixed,zenithy),'+',markersize=2)\nax20=Nevents.add_subplot(233)\nax20.set_title('TeV Sky (1 TeV-1PeV)')\nax20.plot(zenithy,sum_of_events(TeVSky,zenithy),'+',markersize=2,color='r')\nax20_1=Nevents.add_subplot(234)\nax20_1.set_title('Cumulative 90-180 (1 TeV-1 PeV)')\nax20_1.plot(zenithy,check(TeVSky,zenithy),'+',markersize=2,color='r')\n\nax21=Nevents.add_subplot(235)\nax21.set_title('PeV Sky (1PeV-1EeV)')\nax21.plot(zenithy,sum_of_events(PeVSky,zenithy),'+',markersize=2,color='b')\nax22=Nevents.add_subplot(236)\nax22.set_title('EeV Sky (1EeV-$10^21$ eV)')\nax22.plot(zenithy,sum_of_events(EeVSky,zenithy),'+',markersize=2,color='g')\n\naeff=plt.figure()\naeff.suptitle('$A_{eff}$ TeV Sky')\nax23=aeff.add_subplot(121)\nOver,Under=A_eff(TeVSky,zenithy)\nax23.set_title('$A_{eff}$ Over')\nsumsOver=np.zeros(len(Over[0]))\nfor aefff in range(len(Over)):\n ax23.plot(TeVSky,Over[aefff],'+',markersize=2)#,color='g')\n sumsOver=sumsOver+np.array(Over[aefff])\nax23.plot(TeVSky,sumsOver,'g--')\nax23.set_xscale('log')\nax23.set_yscale('log')\n\nax24=aeff.add_subplot(122)\nax24.set_title('$A_{eff}$ Under')\nsumsUnder=np.zeros(len(Under[0]))\nfor ae in range(len(Under)):\n ax24.plot(TeVSky,Under[ae],'+',markersize=2)#,color='g')\n sumsUnder=sumsUnder+np.array(Under[ae])\nax24.plot(TeVSky,sumsUnder,'g--')\nax24.set_xscale('log')\nax24.set_yscale('log')\n\naeff1=plt.figure()\naeff1.suptitle('$A_{eff}$ PeV Sky')\nax25=aeff1.add_subplot(121)\nOver1,Under1=A_eff(PeVSky,zenithy)\nax25.set_title('$A_{eff}$ Over')\nsumsOver1=np.zeros(len(Over1[0]))\nfor aefff1 in range(len(Over1)):\n ax25.plot(PeVSky,Over1[aefff1],'+',markersize=2)#,color='g')\n sumsOver1=sumsOver1+np.array(Over1[aefff1])\nax25.plot(PeVSky,sumsOver1,'g--')\nax25.set_xscale('log')\nax25.set_yscale('log')\n\nax26=aeff1.add_subplot(122)\nax26.set_title('$A_{eff}$ Under')\nsumsUnder1=np.zeros(len(Under1[0]))\nfor ae1 in range(len(Under1)):\n ax26.plot(PeVSky,Under1[ae1],'+',markersize=2)#,color='g')\n sumsUnder1=sumsUnder1+np.array(Under1[ae1])\nax26.plot(PeVSky,sumsUnder1,'g--')\nax26.set_xscale('log')\nax26.set_yscale('log')\nax26.set_ylim([10**-1, 10**5])\n\naeff2=plt.figure()\naeff2.suptitle('$A_{eff}$ EeV Sky')\nax27=aeff2.add_subplot(121)\nOver2,Under2=A_eff(EeVSky,zenithy)\nax27.set_title('$A_{eff}$ Over')\nsumsOver2=np.zeros(len(Over2[0]))\nfor aefff2 in range(len(Over2)):\n ax27.plot(EeVSky,Over2[aefff2],'+',markersize=2)#,color='g')\n sumsOver2=sumsOver2+np.array(Over2[aefff2])\nax27.plot(EeVSky,sumsOver2,'g--')\nax27.set_xscale('log')\nax27.set_yscale('log')\n\nax28=aeff2.add_subplot(122)\nax28.set_title('$A_{eff}$ Under')\nsumsUnder2=np.zeros(len(Under2[0]))\nfor ae2 in range(len(Under2)):\n ax28.plot(EeVSky,Under2[ae2],'+',markersize=2)#,color='g')\n sumsUnder2=sumsUnder2+np.array(Under2[ae2])\nax28.plot(EeVSky,sumsUnder2,'g--')\nax28.set_xscale('log')\nax28.set_yscale('log')\nax28.set_ylim([10**-5, 10**4])\nplt.show()\n \n","sub_path":"ARCA_UP_SKY/Final.py","file_name":"Final.py","file_ext":"py","file_size_in_byte":41023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"302067155","text":"# Copyright 2017 Ruben Decrop\n\nimport datetime, urllib.request, sys, io\nfrom chessapi.models.ranking import Belplayer\n\ndef fetchplayerdbf():\n now = datetime.datetime.now()\n year = now.year\n month = (now.month - 1) // 3 * 3 + 1\n period = '{0:4d}{1:02d}'.format(year, month)\n print('period', period)\n url = 'http://www.frbe-kbsb.be/sites/manager/ELO/PLAYER_{0}.ZIP'.format(\n period)\n try:\n f = urllib.request.urlopen(url)\n except urllib.request.URLError:\n print('Cannot open url %s', url)\n return False\n fdata = f.read()\n f.close()\n return Belplayer.readzipfile(io.BytesIO(fdata), period)\n\n\nif __name__ == '__main__':\n print('fetching player.dbf')\n if fetchplayerdbf():\n print('success')\n\n\n","sub_path":"chessapi/scripts/fetchplayerdbf.py","file_name":"fetchplayerdbf.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"435967520","text":"def get_jaccard_sim( genres1 , genres2 ):\n len1 = len( genres1 )\n len2 = len( genres2 )\n # print( \"len1\" , len1 )\n # print( \"len2\" , len2 )\n if len1 == 1 and genres1[0] == 'Genre not found.':\n genres1 = []\n if len2 == 1 and genres2[0] == 'Genre not found.':\n genres2 = []\n len1 = len( genres1 )\n len2 = len( genres2 )\n if len1 == 0 and len2 == 0:\n return -2\n if len1 == 0 or len2 == 0:\n return -3\n num = 0\n den = len1 + len2\n for genre in genres1:\n if genre in genres2:\n num = num + 1\n den = den - 1\n # print( \"num\" , num )\n # print( \"den\" , den )\n return num / den","sub_path":"src/get_jaccard_sim.py","file_name":"get_jaccard_sim.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"49796200","text":"#!/usr/bin/env python\n# Lint as: python3\n\"\"\"Functions to run individual GRR components during self-contained testing.\"\"\"\n\nimport atexit\nimport os\nimport shutil\nimport signal\nimport subprocess\nimport sys\nimport tempfile\nimport threading\nimport time\n\nfrom typing import Dict, Iterable, List, Optional, Tuple, Union\n\nimport portpicker\n\nfrom grr_response_core.lib import package\nfrom grr_response_test.lib import api_helpers\n\nComponentOptions = Dict[str, Union[int, str]]\n\n\nclass Error(Exception):\n \"\"\"Module-specific base error class.\"\"\"\n\n\nclass ConfigInitializationError(Error):\n \"\"\"Raised when a self-contained config can't be written.\"\"\"\n\n\ndef _ComponentOptionsToArgs(options):\n if options is None:\n return []\n\n args = []\n for k, v in options.items():\n args.extend([\"-p\", \"%s=%s\" % (k, v)])\n return args\n\n\ndef _GetServerComponentArgs(config_path):\n \"\"\"Returns a set of command line arguments for server components.\n\n Args:\n config_path: Path to a config path generated by\n self_contained_config_writer.\n\n Returns:\n An iterable with command line arguments to use.\n \"\"\"\n\n primary_config_path = package.ResourcePath(\n \"grr-response-core\", \"install_data/etc/grr-server.yaml\")\n secondary_config_path = package.ResourcePath(\n \"grr-response-test\", \"grr_response_test/test_data/grr_test.yaml\")\n return [\n \"--config\",\n primary_config_path,\n \"--secondary_configs\",\n \",\".join([secondary_config_path, config_path]),\n \"-p\",\n \"Monitoring.http_port=%d\" % portpicker.pick_unused_port(),\n \"-p\",\n \"AdminUI.webauth_manager=NullWebAuthManager\",\n ]\n\n\ndef _GetRunEndToEndTestsArgs(\n client_id,\n server_config_path,\n tests = None,\n manual_tests = None):\n \"\"\"Returns arguments needed to configure run_end_to_end_tests process.\n\n Args:\n client_id: String with a client id pointing to an already running client.\n server_config_path: Path to the server configuration file.\n tests: (Optional) List of tests to run.\n manual_tests: (Optional) List of manual tests to not skip.\n\n Returns:\n An iterable with command line arguments.\n \"\"\"\n port = api_helpers.GetAdminUIPortFromConfig(server_config_path)\n\n api_endpoint = \"http://localhost:%d\" % port\n args = [\n \"--api_endpoint\",\n api_endpoint,\n \"--api_user\",\n \"admin\",\n \"--api_password\",\n \"admin\",\n \"--client_id\",\n client_id,\n \"--ignore_test_context\",\n \"True\",\n ]\n if tests is not None:\n args += [\"--whitelisted_tests\", \",\".join(tests)]\n if manual_tests is not None:\n args += [\"--manual_tests\", \",\".join(manual_tests)]\n\n return args\n\n\ndef _StartComponent(main_package, args):\n \"\"\"Starts a new process with a given component.\n\n This starts a Python interpreter with a \"-m\" argument followed by\n the main package name, thus effectively executing the main()\n function of a given package.\n\n Args:\n main_package: Main package path.\n args: An iterable with program arguments (not containing the program\n executable).\n\n Returns:\n Popen object corresponding to a started process.\n \"\"\"\n popen_args = [sys.executable, \"-m\", main_package] + args\n print(\"Starting %s component: %s\" % (main_package, \" \".join(popen_args)))\n process = subprocess.Popen(popen_args)\n print(\"Component %s pid: %d\" % (main_package, process.pid))\n\n def KillOnExit():\n if process.poll() is None:\n print(\"Killing %s.\" % main_package)\n process.kill()\n process.wait()\n\n atexit.register(KillOnExit)\n\n return process\n\n\ndef InitConfigs(mysql_database,\n mysql_username = None,\n mysql_password = None,\n logging_path = None,\n osquery_path = None):\n \"\"\"Initializes server and client config files.\"\"\"\n\n # Create 2 temporary files to contain server and client configuration files\n # that we're about to generate.\n #\n # TODO(user): migrate to TempFilePath as soon grr.test_lib is moved to\n # grr_response_test.\n fd, built_server_config_path = tempfile.mkstemp(\".yaml\")\n os.close(fd)\n print(\"Using temp server config path: %s\" % built_server_config_path)\n fd, built_client_config_path = tempfile.mkstemp(\".yaml\")\n os.close(fd)\n print(\"Using temp client config path: %s\" % built_client_config_path)\n\n def CleanUpConfigs():\n os.remove(built_server_config_path)\n os.remove(built_client_config_path)\n\n atexit.register(CleanUpConfigs)\n\n # Generate server and client configs.\n config_writer_flags = [\n \"--dest_server_config_path\",\n built_server_config_path,\n \"--dest_client_config_path\",\n built_client_config_path,\n \"--config_mysql_database\",\n mysql_database,\n ]\n\n if mysql_username is not None:\n config_writer_flags.extend([\"--config_mysql_username\", mysql_username])\n\n if mysql_password is not None:\n config_writer_flags.extend([\"--config_mysql_password\", mysql_password])\n\n if logging_path is not None:\n config_writer_flags.extend([\"--config_logging_path\", logging_path])\n\n if osquery_path is not None:\n config_writer_flags.extend([\"--config_osquery_path\", osquery_path])\n\n p = _StartComponent(\n \"grr_response_test.lib.self_contained_config_writer\",\n config_writer_flags)\n if p.wait() != 0:\n raise ConfigInitializationError(\"ConfigWriter execution failed: {}\".format(\n p.returncode))\n\n return (built_server_config_path, built_client_config_path)\n\n\ndef StartServerProcesses(\n server_config_path,\n component_options = None\n):\n\n def Args():\n return _GetServerComponentArgs(\n server_config_path) + _ComponentOptionsToArgs(component_options)\n\n return [\n _StartComponent(\n \"grr_response_server.gui.admin_ui\",\n Args()),\n _StartComponent(\n \"grr_response_server.bin.frontend\",\n Args()),\n _StartComponent(\n \"grr_response_server.bin.worker\",\n Args()),\n ]\n\n\ndef StartClientProcess(client_config_path,\n component_options = None,\n verbose = False):\n return _StartComponent(\n \"grr_response_client.client\",\n [\"--config\", client_config_path] + ([\"--verbose\"] if verbose else []) +\n _ComponentOptionsToArgs(component_options))\n\n\ndef RunEndToEndTests(client_id,\n server_config_path,\n tests = None,\n manual_tests = None):\n \"\"\"Runs end to end tests on a given client.\"\"\"\n p = _StartComponent(\n \"grr_response_test.run_end_to_end_tests\",\n _GetServerComponentArgs(server_config_path) + _GetRunEndToEndTestsArgs(\n client_id, server_config_path, tests=tests,\n manual_tests=manual_tests))\n if p.wait() != 0:\n raise RuntimeError(\"RunEndToEndTests execution failed.\")\n\n\ndef RunBuildTemplate(server_config_path,\n component_options = None,\n version_ini = None):\n \"\"\"Runs end to end tests on a given client.\"\"\"\n output_dir = tempfile.mkdtemp()\n\n def CleanUpTemplate():\n shutil.rmtree(output_dir)\n\n atexit.register(CleanUpTemplate)\n\n options = dict(component_options or {})\n if version_ini:\n fd, version_ini_path = tempfile.mkstemp(\".ini\")\n try:\n os.write(fd, version_ini.encode(\"ascii\"))\n finally:\n os.close(fd)\n\n options[\"ClientBuilder.version_ini_path\"] = version_ini_path\n\n p = _StartComponent(\n \"grr_response_client_builder.client_build\",\n _GetServerComponentArgs(server_config_path) +\n _ComponentOptionsToArgs(options) + [\"build\", \"--output\", output_dir])\n if p.wait() != 0:\n raise RuntimeError(\"RunBuildTemplate execution failed.\")\n\n return os.path.join(output_dir, os.listdir(output_dir)[0])\n\n\ndef RunRepackTemplate(\n server_config_path,\n template_path,\n component_options = None):\n \"\"\"Runs 'grr_client_builder repack' to repack a template.\"\"\"\n output_dir = tempfile.mkdtemp()\n\n def CleanUpInstaller():\n shutil.rmtree(output_dir)\n\n atexit.register(CleanUpInstaller)\n\n p = _StartComponent(\n \"grr_response_client_builder.client_build\",\n _GetServerComponentArgs(server_config_path) +\n _ComponentOptionsToArgs(component_options) +\n [\"repack\", \"--template\", template_path, \"--output_dir\", output_dir])\n if p.wait() != 0:\n raise RuntimeError(\"RunRepackTemplate execution failed.\")\n\n # Repacking may apparently generate more than one file. Just select the\n # biggest one: it's guaranteed to be the template.\n paths = [os.path.join(output_dir, fname) for fname in os.listdir(output_dir)]\n sizes = [os.path.getsize(p) for p in paths]\n _, biggest_path = max(zip(sizes, paths))\n\n return biggest_path\n\n\ndef RunUploadExe(server_config_path,\n exe_path,\n platform,\n component_options = None):\n \"\"\"Runs 'grr_config_upater upload_exe' to upload a binary to GRR.\"\"\"\n p = _StartComponent(\n \"grr_response_server.bin.config_updater\",\n _GetServerComponentArgs(server_config_path) +\n _ComponentOptionsToArgs(component_options) + [\n \"upload_exe\", \"--file\", exe_path, \"--platform\", platform,\n \"--upload_subdirectory\", \"test\"\n ])\n if p.wait() != 0:\n raise RuntimeError(\"RunUploadExe execution failed.\")\n\n return \"%s/test/%s\" % (platform, os.path.basename(exe_path))\n\n\n_PROCESS_CHECK_INTERVAL = 0.1\n\n\ndef _DieIfSubProcessDies(processes,\n already_dead_event):\n \"\"\"Synchronously waits for processes and dies if one dies.\"\"\"\n while True:\n for p in processes:\n if p.poll() not in [None, 0]:\n # Prevent a double kill. When the main process exits, it kills the\n # children. We don't want a child's death to cause a SIGTERM being\n # sent to a process that's already exiting.\n if already_dead_event.is_set():\n return\n\n # DieIfSubProcessDies runs in a background thread, raising an exception\n # will just kill the thread while what we want is to fail the whole\n # process.\n print(\"Subprocess %s died unexpectedly. Killing main process...\" %\n p.pid)\n for kp in processes:\n try:\n os.kill(kp.pid, signal.SIGTERM)\n except OSError:\n pass\n # sys.exit only exits a thread when called from a thread.\n # Killing self with SIGTERM to ensure the process runs necessary\n # cleanups before exiting.\n os.kill(os.getpid(), signal.SIGTERM)\n time.sleep(_PROCESS_CHECK_INTERVAL)\n\n\ndef DieIfSubProcessDies(\n processes):\n \"\"\"Kills the process if any of given processes dies.\n\n This function is supposed to run in a background thread and monitor provided\n processes to ensure they don't die silently.\n\n Args:\n processes: An iterable with multiprocessing.Process instances.\n\n Returns:\n Background thread started to monitor the processes.\n \"\"\"\n already_dead_event = threading.Event()\n t = threading.Thread(\n target=_DieIfSubProcessDies, args=(processes, already_dead_event))\n t.daemon = True\n t.start()\n\n def PreventDoubleDeath():\n already_dead_event.set()\n\n atexit.register(PreventDoubleDeath)\n\n return t\n","sub_path":"grr/test/grr_response_test/lib/self_contained_components.py","file_name":"self_contained_components.py","file_ext":"py","file_size_in_byte":11051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"289303594","text":"import sys\nimport traceback\n\nimport Qt.QtWidgets as QtWidgets\nimport Qt.QtCore as QtCore\nimport Qt.QtGui as QtGui\n\nfrom gazupublisher.views.MainWindow import MainWindow\nfrom gazupublisher.ui_data.color import main_color, text_color\nfrom gazupublisher.utils.error_window import ResizableMessageBox\nfrom gazupublisher.working_context import (\n set_working_context,\n get_working_context,\n is_maya_context,\n is_blender_context,\n)\nfrom qtazu.widgets.login import Login\n\n\n# Hack to allow to close the application with Ctrl+C\nimport signal\n\nsignal.signal(signal.SIGINT, signal.SIG_DFL)\n\n\ndef excepthook(exc_type, exc_value, exc_traceback):\n \"\"\"\n Handle unexpected errors by popping an error window and restarting the app.\n \"\"\"\n\n string_tb = traceback.format_exception(exc_type, exc_value, exc_traceback)\n from_gazupublisher = any(\n \"gazupublisher\" in tb_step for tb_step in string_tb\n )\n if not from_gazupublisher:\n sys.__excepthook__(exc_type, exc_value, exc_traceback)\n return\n\n header = \"\\n=== An error occured !=== \\nError message:\\n\"\n traceback_print = \"\".join(string_tb)\n\n message = \"%s%s\" % (header, traceback_print)\n if is_blender_context():\n from dccutils.dcc_blender import BlenderContext\n\n BlenderContext.software_print(message)\n else:\n print(message)\n app = QtWidgets.QApplication.instance()\n create_error_dialog(app.current_window, traceback_print)\n app.current_window.close()\n launch_main_app(app)\n\n\ndef create_error_dialog(parent, message):\n \"\"\"\n Create an error dialog window.\n \"\"\"\n error_dialog = ResizableMessageBox(parent)\n error_dialog.setWindowTitle(\"ERROR\")\n error_dialog.setModal(True)\n error_dialog.setText(\"An error has occurred\")\n error_dialog.setDetailedText(message)\n error_dialog.setStandardButtons(QtWidgets.QMessageBox.Cancel)\n error_dialog.show()\n error_dialog.raise_()\n error_dialog.activateWindow()\n\n\ndef launch_main_app(app):\n \"\"\"\n Launch the main application.\n \"\"\"\n window = create_main_window(app)\n window.show()\n\n\ndef on_emit(is_success, app, login_window):\n \"\"\"\n Activated on emit from the login window.\n \"\"\"\n if is_success:\n login_window.deleteLater()\n launch_main_app(app)\n\n\ndef gazu_login_window(app):\n \"\"\"\n Creates the login window.\n \"\"\"\n login_window = Login()\n login_window.logged_in.connect(\n lambda is_success: on_emit(is_success, app, login_window)\n )\n return login_window\n\n\ndef setup_dark_mode(app):\n \"\"\"\n Set up dark mode.\n \"\"\"\n palette = QtGui.QPalette()\n palette.setColor(QtGui.QPalette.Window, QtGui.QColor(main_color))\n palette.setColor(QtGui.QPalette.WindowText, QtGui.QColor(text_color))\n palette.setColor(QtGui.QPalette.Base, QtGui.QColor(main_color))\n palette.setColor(QtGui.QPalette.AlternateBase, QtGui.QColor(main_color))\n palette.setColor(QtGui.QPalette.ToolTipBase, QtGui.QColor(text_color))\n palette.setColor(QtGui.QPalette.ToolTipText, QtGui.QColor(text_color))\n palette.setColor(QtGui.QPalette.Text, QtGui.QColor(text_color))\n palette.setColor(QtGui.QPalette.Button, QtGui.QColor(main_color))\n palette.setColor(QtGui.QPalette.ButtonText, QtGui.QColor(text_color))\n palette.setColor(QtGui.QPalette.BrightText, QtCore.Qt.red)\n palette.setColor(QtGui.QPalette.Link, QtGui.QColor(42, 130, 218))\n palette.setColor(QtGui.QPalette.Highlight, QtGui.QColor(42, 130, 218))\n palette.setColor(QtGui.QPalette.HighlightedText, QtCore.Qt.black)\n palette.setColor(\n QtGui.QPalette.Disabled,\n QtGui.QPalette.WindowText,\n QtGui.QColor(text_color).darker(170),\n )\n palette.setColor(\n QtGui.QPalette.Disabled,\n QtGui.QPalette.ButtonText,\n QtGui.QColor(text_color).darker(170),\n )\n app.setPalette(palette)\n\n\ndef setup_style(app):\n \"\"\"\n Setup style. 'Fusion' is the wanted default style for this app.\n Maya already defines its own style.\n \"\"\"\n if \"Fusion\" in QtWidgets.QStyleFactory.keys() and not is_maya_context():\n app.setStyle(\"Fusion\")\n\n\ndef create_app():\n app = QtCore.QCoreApplication.instance()\n if app:\n try:\n import maya.cmds\n\n set_working_context(\"MAYA\")\n except:\n pass\n else:\n app = QtWidgets.QApplication(sys.argv)\n setup_style(app)\n setup_dark_mode(app)\n sys.excepthook = excepthook\n return app\n\n\ndef create_login_window(app):\n login_window = gazu_login_window(app)\n app.current_window = login_window\n return login_window\n\n\ndef create_main_window(app):\n main_window = MainWindow(app)\n app.current_window = main_window\n main_window.setObjectName(\"main_window\")\n main_window.setWindowTitle(\"Kitsu\")\n main_window.setStyleSheet(\n \"QMainWindow{background-color: %s;} \"\n \"QToolTip{color: %s; background-color: %s; border: 0px;}\"\n % (main_color, text_color, main_color)\n )\n return main_window\n\n\ndef main():\n try:\n app = create_app()\n login_window = create_login_window(app)\n login_window.show()\n sys.exit(app.exec_())\n\n except KeyboardInterrupt:\n sys.exit()\n\n\nif __name__ == \"__main__\":\n set_working_context(\"STANDALONE\")\n print(\"Working context : \" + get_working_context())\n main()\n","sub_path":"gazupublisher/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":5340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"398763002","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Nov 03 10:53:45 2018\r\n@author: Animesh Paul\r\nReferences:\r\n 1. https://docs.opencv.org/\r\n 2. https://www.stackoverflow.com/\r\n\"\"\"\r\nimport cv2 as cv\r\nimport numpy as np\r\nimport os\r\nfrom matplotlib import pyplot as plt\r\n\r\nUBIT = 'animeshp'\r\nnp.random.seed(sum([ord(c) for c in UBIT]))\r\n\r\nRESULT_DIR = \"./Results/Task3/\"\r\nif not os.path.exists(RESULT_DIR):\r\n os.makedirs(RESULT_DIR)\r\n\r\ndef save_img(filename, img):\r\n # Saves image with passed filename in the results folder\r\n if not os.path.exists(RESULT_DIR):\r\n os.makedirs(RESULT_DIR)\r\n filename = os.path.join(RESULT_DIR, filename)\r\n cv.imwrite(filename, img)\r\n\r\ndef compute_euc_dist(X, Mu):\r\n #X and Mu are two 1D Lists\r\n return(np.sqrt((X[0]- Mu[0]) ** 2 + (X[1] - Mu[1]) ** 2))\r\n \r\ndef assign(X, Mu):\r\n \"\"\" First Step is Computation of Euclidean Distance \"\"\"\r\n d_matrix = []\r\n index = []\r\n for i in range(0,len(X)):\r\n l = []\r\n for j in range(0,len(Mu)):\r\n d = compute_euc_dist(X[i], Mu[j])\r\n l.append(d)\r\n d_matrix.append(l)\r\n \r\n for i in range(0,len(d_matrix)):\r\n t = d_matrix[i].index(min(d_matrix[i]))\r\n index.append(t+1) # Class Vector\r\n return (index)\r\n\r\ndef plot_points(index, X, Mu, s):\r\n r_x = []\r\n r_y = []\r\n g_x = []\r\n g_y = []\r\n b_x = []\r\n b_y = []\r\n for i in range(0,len(index)):\r\n if index[i] == 1:\r\n r_x.append(X[i][0])\r\n r_y.append(X[i][1])\r\n if index[i] == 2:\r\n g_x.append(X[i][0])\r\n g_y.append(X[i][1])\r\n if index[i] == 3:\r\n b_x.append(X[i][0])\r\n b_y.append(X[i][1])\r\n \r\n plt.scatter(r_x, r_y, marker = '^', edgecolor = 'red', facecolor = 'white')\r\n plt.scatter(g_x, g_y, marker = '^', edgecolor = 'green', facecolor = 'white')\r\n plt.scatter(b_x, b_y, marker = '^', edgecolor = 'blue', facecolor = 'white')\r\n plt.scatter(Mu[0][0], Mu[0][1], marker = 'o', color = 'red')\r\n plt.scatter(Mu[1][0], Mu[1][1], marker = 'o', color = 'green')\r\n plt.scatter(Mu[2][0], Mu[2][1], marker = 'o', color = 'blue')\r\n \r\n for i in range(0,len(X)):\r\n plt.text(X[i][0], X[i][1] - 0.08, f'({X[i][0]}{X[i][1]})', fontsize = 4.5)\r\n \r\n for i in range(0,len(Mu)):\r\n plt.text(Mu[i][0], Mu[i][1] - 0.08, f'({Mu[i][0]}{Mu[i][1]})', fontsize = 4.5)\r\n \r\n plt.savefig(os.path.join(RESULT_DIR, 'task3_iter'+str(s)+'.jpg'))\r\n plt.gcf().clear()\r\n #print(\"Current Centroids are:= \" +str(Mu))\r\n \r\ndef recompute_mu(index, X, Mu):\r\n s1x = 0\r\n s1y = 0\r\n s2x = 0\r\n s2y = 0\r\n s3x = 0\r\n s3y = 0\r\n c1 = index.count(1)\r\n c2 = index.count(2)\r\n c3 = index.count(3)\r\n for i in range(0,len(index)):\r\n if index[i] == 1:\r\n s1x = s1x + X[i][0]\r\n s1y = s1y + X[i][1]\r\n if index[i] == 2:\r\n s2x = s2x + X[i][0]\r\n s2y = s2y + X[i][1]\r\n if index[i] == 3:\r\n s3x = s3x + X[i][0]\r\n s3y = s3y + X[i][1]\r\n \r\n s1x = s1x/c1\r\n s1y = s1y/c1\r\n s2x = s2x/c2\r\n s2y = s2y/c2\r\n s3x = s3x/c3\r\n s3y = s3y/c3\r\n \r\n Mu1 = [[s1x, s1y], [s2x, s2y], [s3x, s3y]]\r\n return (Mu1) \r\n\r\n#def plot_mu(Mu1):\r\n \r\n#Main Starts here\r\n\r\nX = [[5.9, 3.2], [4.6, 2.9], [6.2, 2.8], [4.7, 3.2], [5.5, 4.2], \r\n [5.0, 3.0], [4.9, 3.1], [6.7, 3.1], [5.1, 3.8], [6.0, 3.0]] #Set of Points to be clustered\r\n\r\nMu = [[6.2, 3.2], [6.6, 3.7], [6.5, 3.0]] #Initial Centroids, Last Term indicates class\r\n\r\ncolor_map = {1:'red', 2:'green', 3:'blue'} #Corresponding Colors of Class Labels\r\n\r\nj = 1\r\nfor i in range(0,2): \r\n index=assign(X, Mu)\r\n print(index)\r\n plot_points(index, X, Mu, j)\r\n j = j+1\r\n Mu = recompute_mu(index, X, Mu)\r\n plot_points(index, X, Mu, j)\r\n j = j+1","sub_path":"Task3_Kmeans.py","file_name":"Task3_Kmeans.py","file_ext":"py","file_size_in_byte":3863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"150066079","text":"import graphene\nfrom django.contrib.contenttypes.models import ContentType\nfrom crm.schema.mutation import SngyMutation\nfrom synergycrm.exceptions import SngyException\nfrom ..models import Comment\nfrom notice.models import Notification\nfrom users.models import User\n\n\nclass CreateComments(SngyMutation):\n\tresult = graphene.Boolean()\n\n\tclass Input:\n\t\tname = graphene.String(required=True)\n\t\tobject_id = graphene.Int(required=True)\n\t\tcomment = graphene.String(required=True)\n\t\ttargets = graphene.List(of_type=graphene.Int)\n\n\tdef mutate_and_get_payload(self, info, name, object_id, comment, targets):\n\t\tif not '.' in name:\n\t\t\traise SngyException('Неправильное имя')\n\t\tapp_label, model = name.lower().split('.')\n\t\tcontent_type = ContentType(app_label=app_label, model=model)\n\t\tcontent_object = content_type.get_object_for_this_type(id=object_id)\n\t\tComment.objects.create(content_object=content_object, user=info.context.user, comment=comment)\n\n\t\tusers_id = [u.id for u in User.objects.all()]\n\t\tif not targets:\n\t\t\ttargets = list(set([c.user_id for c in Comment.objects.filter(content_type__app_label=app_label,\n\t\t\t content_type__model=model, object_id=object_id)]))\n\t\t\tif info.context.user.id in targets:\n\t\t\t\ttargets.remove(info.context.user.id)\n\t\tfor t in targets:\n\t\t\tif t in users_id:\n\t\t\t\ttext = 'Комментарий: ' + comment\n\t\t\t\tNotification.objects.create(purpose_id=t, created=info.context.user, text=text)\n\n\t\treturn CreateComments(result=True)\n\n\nclass Mutation(graphene.ObjectType):\n\tcreate_comments = CreateComments.Field()\n\n","sub_path":"backend_v3/comments/schema/mutation.py","file_name":"mutation.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"542321799","text":"import numpy as np\n\n#Ones Counter\ndef Ones_Counter(GameBoard):\n\t#Ones Amount for Position(i,j)\n\tOAPOSij = [] \n\tfor p in range(0,len(Starting_Positions)):\n\t\ti = Starting_Positions[p][0]\n\t\tj = Starting_Positions[p][1]\n\t\tOAPOSij.append(np.sum(GameBoard[i][j:]) + np.sum(GameBoard.transpose()[j][i+1:]))\n\treturn(OAPOSij)\n\n#Permutations Generator\ndef CrossCombine(St_Pos_List):\n\t#Knot positions\t\n\tPos_Moves = [St_Pos_List]\n\tComb_Vec = [Pos_Moves]\n\tprint(\"CV: \",Comb_Vec)\n\t#Vertical\n\tfor i in range(St_Pos_List[0]+1, n):\n\t\tPos_Moves.append([i, St_Pos_List[1]])\n\t\tprint(\"PM: \",Pos_Moves)\n\t\t#Comb_Vec.extend([Pos_Moves])\n\t\t#print(\"CV: \",Comb_Vec)\n\t#Horizontal\n\tPos_Moves = [St_Pos_List]\n\tfor j in range(St_Pos_List[1]+1, n):\n\t\tPos_Moves.append([St_Pos_List[0],j])\n\t\tprint(\"PM: \",Pos_Moves)\n\t\t#Comb_Vec.extend([Pos_Moves])\n\t\t#print(\"CV: \",Comb_Vec)\n\t#Return Cross elements from Knot position\n\treturn(Pos_Moves)\n\t#return(Pos_Moves)\n\n#Algorithm Starting Positions\nStarting_Positions = []\n\n#GameBoard creation\nGameBoard = np.array([[1]*n]*n)\n\n#Algorithm Starting Positions Generator \nfor i in range(0,n):\n\tfor j in range(0,n):\n\t\tStarting_Positions.append([i,j])\n\n#All Possible Moves Amount for current GameBoard\nPMA = np.sum(Ones_Counter(GameBoard))\n\n","sub_path":"balls.py","file_name":"balls.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"61798828","text":"#from app.gui.write import write_dict\n#from app.gui.write import write_network\nimport subprocess\nimport networkx as nx\nimport json\nimport read\nimport write\n\npath = \"files/\"\ninfile = path\noutfile = path\nexecutable = \"./bin/all.out\"\n\n\n# 1. Get graph and write it\n# 2. Networkx to json\n# 3. Exec binary and algorithm\n# 4. Read result graph and display\n\n# 3. Exec algorithm\n#\n# ALGORITHMS\n# GRAPH\n#\n# 1: Graph operations\n# 2: Calculate if graph is bipartite & partitions\n# 3: Calculate euler path (Fleury's Algorithm)\n# 4: BFS expansion tree\n# 5: DFS expansion tree\n# 6: Kruskal minimun spanning forest\n# 7: Prim minimum spanning tree\n# \n# DIGRAPH \n#\n# 8: Shortest path (Dijkstra's algorithm)\n# 9: Shortest paths (Floyd-Warshall Algorithm)\n# \n# NETWORK\n#\n# 10: Maximun flow in a network (Ford-Fulkerson Algorithm)\n# 11: Primal algorithm\n# 12: Dual algorithm\n# 13: Simplex algorithm\n\n\ndef run_graph(g, algo):\n global infile\n global outfile\n\n infile = \"files/graph/input/g.json\"\n outfile = \"files/graph/output/g.json\"\n\n g.graph[\"weighted\"] = True\n g.graph[\"type\"] = \"graph\"\n #print(params)\n \n # All graph algorithms works same\n graph = write.write_dict(g)\n #print(graph)\n with open(infile, 'w') as out:\n json.dump(graph, out)\n\n bashCommand = f'{executable} {infile} {outfile} {algo}'\n print(f'executing {bashCommand}')\n\n process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)\n output, _ = process.communicate()\n print(output)\n\n gres = nx.MultiGraph()\n res, info, gres = read.read_graph(outfile,algo)\n print(\"RESULTS\")\n print(res)\n print(info)\n print(gres.nodes())\n print(gres.edges())\n return res, info, gres\n\n\n\ndef receive_graph(G):\n graph_data = nx.node_link_data(G)\n print(graph_data)\n\ndef run_digraph(d, algorithm, params):\n global infile\n global outfile\n\n infile = \"files/digraph/input/g.json\"\n outfile = \"files/digraph/output/g.json\"\n\n d.graph[\"weighted\"] = True\n d.graph[\"type\"] = \"digraph\"\n\n d_json = write.write_digraph(d)\n d_json[\"initial_tag\"] = params[0]\n print(\"param etros\")\n print(len(params))\n print(params)\n print(type(params))\n if algorithm == 8 and len(params) != 1:\n d_json[\"destination_tag\"] = params[1]\n print(d_json)\n\n with open(infile, 'w') as out:\n json.dump(d_json, out)\n\n bashCommand = f'{executable} {infile} {outfile} {algorithm}'\n print(f'executing {bashCommand}')\n\n process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)\n output, _ = process.communicate()\n print(output)\n\n #read result\n g_json = json.load(open(outfile))\n print(g_json)\n res, info, gres = read.read_digraph(outfile, algorithm, params)\n return res, info, gres\n\ndef run_network(n, algorithm, params):\n global infile\n global outfile\n\n infile = \"files/network/input/g.json\"\n outfile = \"files/network/output/g.json\"\n\n n.graph[\"weighted\"] = True\n n.graph[\"type\"]=\"network\"\n\n net = write.write_network(n)\n \n #ford fulkerson\n if len(params) != 0:\n net[\"target_flow\"] = params[0]\n \n print(net)\n\n with open(infile, 'w') as out:\n json.dump(net, out)\n\n bashCommand = f'{executable} {infile} {outfile} {algorithm}'\n print(f'executing {bashCommand}')\n\n process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)\n output, _ = process.communicate()\n print(output)\n\n #read result\n g_json = json.load(open(outfile))\n print(\"results read\")\n if len(params) != 0:\n g_json[\"target_flow\"] = params[0]\n print(g_json)\n res, info, gres = read.read_network(g_json, algorithm, params)\n print(\"from controller got results\")\n print(gres)\n print(res)\n print(info)\n return res, info, gres\n\n\n\n\n #return res\n \n\n\n \n #print(params)\n \n # All graph algorithms works same\n# graph = write.write_dict(g)\n #print(graph)\n# with open(infile, 'w') as out:\n# json.dump(graph, out)\n\n# bashCommand = f'{executable} {infile} {outfile} {algo}'\n# print(f'executing {bashCommand}')\n\n# process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)\n# output, _ = process.communicate()\n# print(output)\n\n #read result\n #g_json = json.load(open(outfile))\n #print(g_json)\n# gres = nx.MultiGraph()\n# return res, info, gres\n","sub_path":"app/gui/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":4402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"583503045","text":"#!/usr/bin/env python\n\n\"\"\"\n##########################################################################\n# * * * PySynth * * *\n# A very basic audio synthesizer in Python (www.python.org)\n#\n# Martin C. Doege, 2017-06-20 (mdoege@compuserve.com)\n##########################################################################\n# Based on a program by Tyler Eaves (tyler at tylereaves.com) found at\n# http://mail.python.org/pipermail/python-list/2000-August/041308.html\n##########################################################################\n\n# 'song' is a Python list (or tuple) in which the song is defined,\n# the format is [['note', value]]\n\n# Notes are 'a' through 'g' of course,\n# optionally with '#' or 'b' appended for sharps or flats.\n# Finally the octave number (defaults to octave 4 if not given).\n# An asterisk at the end makes the note a little louder (useful for the beat).\n# 'r' is a rest.\n\n# Note value is a number:\n# 1=Whole Note; 2=Half Note; 4=Quarter Note, etc.\n# Dotted notes can be written in two ways:\n# 1.33 = -2 = dotted half\n# 2.66 = -4 = dotted quarter\n# 5.33 = -8 = dotted eighth\n\"\"\"\n\nfrom __future__ import division\nfrom demosongs import *\nfrom mkfreq import getfreq\n\npitchhz, keynum = getfreq(pr = True)\n\n##########################################################################\n#### Main program starts below\n##########################################################################\n# Some parameters:\n\n# Beats (quarters) per minute\n# e.g. bpm = 95\n\n# Octave shift (neg. integer -> lower; pos. integer -> higher)\n# e.g. transpose = 0\n\n# Pause between notes as a fraction (0. = legato and e.g., 0.5 = staccato)\n# e.g. pause = 0.05\n\n# Volume boost for asterisk notes (1. = no boost)\n# e.g. boost = 1.2\n\n# Output file name\n#fn = 'pysynth_output.wav'\n##########################################################################\n\nimport wave, math, struct\nfrom mixfiles import mix_files\n\nfrom math import sin,cos\nfrom math import exp\nfrom math import pi\n\n\ndef make_wav(song,bpm=120,transpose=0,pause=.05,boost=1.1,repeat=0,fn=\"out.wav\", silent=False):\n\tf=wave.open(fn,'w')\n\n\tf.setnchannels(1)\n\tf.setsampwidth(2)\n\tf.setframerate(44100)\n\tf.setcomptype('NONE','Not Compressed')\n\n\tbpmfac = 120./bpm\n\n\tdef length(l):\n\t\treturn 88200./l*bpmfac\n\n\tdef waves2(hz,l):\n\t\ta=44100./hz\n\t\tb=float(l)/44100.*hz\n\t\treturn [a,round(b)]\n\n\tdef sixteenbit(x):\n\t\treturn struct.pack('h', round(32000*x))\n\n\tdef render2(a,b,vol,note):\n\t\tprint('a,b,vol,note:',a,b,vol,note)\n\t\tb2 = (1. - pause) * b\n\t\tl = waves2(a, b2)\n\t\tow = b''\n\t\tq = int(l[0] * l[1])\n\t\t# print('q',q)\n\n\t\thalfp = l[0] / 2.\n\t\tsp = 0\n\t\tfade = 1\n\n\t\tnotes = (\n\t\t\t# 'a', 'a#', 'b', 'c', 'c#', 'd', 'd#', 'e', 'f', 'f#', 'g', 'g#'\n\t\t\t# ('note',('frequencies'),('amplitude'),('phase'))\n\t\t\t('a',(886.658,1326.6,1772.5),(2150.2,171.1,35.6),(-80.525,-163.703,36.81)),\n\t\t\t('a#',(943.029,1886.2,2829.1),(2893.2,230.8,90),(170.928,-66.58,-123)),\n\n\t\t\t('b',(998.325,1995.5,2993.7),(1716.6,225.9,120.1),(-20.607,29.063,-41.767)),\n\n\t\t\t('c',(526.205,1051.5,1579.7,2103.2,2633.1),(1522.4,611.3,412.6,195.7,66.1),(-110.194,-122.091,-142,-160.32,-17.5336)),\n\t\t\t('c#',(558.039,1115.9,1674.5,2232.3,2786.4),(1086.9,438.5,243.4,69.7,54.7),(-101.194,-124.59,-39.76,175.142,149.439)),\n\n\t\t\t('d',(589.977,1176.9,1765.6,2360.1,2942.7),(809.6,646.93,177.55,104.92,56.93),(-86.14,60.59,49.29,50.76,-65.445)),\n\t\t\t('d#',(624.512,1248.8,1873.9,2494.2),(1108.1,467.8,219.7,85.6),(155.295,-141.48,169.528,23.577)),\n\n\t\t\t('e', (662.061,1324.3,1986.6), (1358.2,404.9,345.9),(-40.598,60.433,-5.727)),\n\n\t\t\t('f', (700.045,1399.5,2099), (2137.4,504.1,392.4),(16.463,144.473,54.86)),\n\t\t\t('f#', (747.028,1493.4,2239), (1876.7,482,216),(134.864,19.184,75.995)),\n\n\t\t\t('g', (786.977,1573.4,2360.2), (1649.2,228.8,184.2),(11.556,-561.7,-70.358)),\n\t\t\t('g#', (833.219,1666.3,2489.6), (1328.3,501.3,38.6),(131.78,91.116,120.36)),\n\n\t\t)\n\n\t\tproper_note_usued = False\n\n\t\tfor l in notes:\n\t\t\t# print('l',l)\n\t\t\t# l[0] is the note\n\t\t\tif(l[0] == note):\n\t\t\t\tprint('note',note)\n\t\t\t\tfrequencies_note = l[1]\n\t\t\t\tamplitudes_note = l[2]\n\t\t\t\tphases_note = l[3]\n\t\t\t\t# print('frequencies_note',frequencies_note)\n\t\t\t\t# print('amplitudes_note',amplitudes_note)\n\t\t\t\t# print('phases_note',phases_note)\n\t\t\t\t# number_harms = len(l[1])\n\t\t\t\t# for k in range(number_harms):\n\t\t\t\t# \tbreak\n\t\t\t\tif(len(l[1])!=len(l[2])):\n\t\t\t\t\t# something is wrong in spectrum\n\t\t\t\t\tprint(\"something is wrong in spectrum\")\n\t\t\t\t\texit()\n\t\t\t\telse:\n\t\t\t\t\tproper_note_usued = True\n\t\t\t\t\tprint(\"proper_note_usued = True\")\n\t\t\t\t\tfor x in range(q):\n\t\t\t\t\t\tfactor = 1 / b\n\t\t\t\t\t\t# sp = amplitudes_note[]\n\t\t\t\t\t\t# print('\"proper note\"')\n\t\t\t\t\t\t# ('note',('frequencies'),('amplitude'),('phase'))\n\t\t\t\t\t\t# for a,g,p in zip(amplitudes_note,frequencies_note,phases_note):\n\n\t\t\t\t\t\t# # todo:check this: https://www.audacity-forum.de/download/edgar/nyquist/nyquist-doc/manual/part5.html\n\t\t\t\t\t\t# for fr,am,ph in zip(frequencies_note,amplitudes_note,phases_note):\n\t\t\t\t\t\t# \t# print(\"fr,am,ph\",fr,am,ph)\n\t\t\t\t\t\t# \tsp = 0.01*am*sin( factor * fr * x *2*pi)\n\n\t\t\t\t\t\t# designed ('a', 2) to get 440Hz\n\t\t\t\t\t\tsp = sin( 2*pi*(a * x ) / b )\n\n\t\t\t\t\t\tow = ow + sixteenbit(.1 * vol * sp)\n\t\t\t\t\t\t# print('lol1')\n\t\t\t\t\tfill = max(int(ex_pos - curpos - q), 0)\n\t\t\t\t\tf.writeframesraw((ow) + (sixteenbit(0) * fill))\n\t\t\t\t\treturn q + fill\n\t\t# if(proper_note_usued ==False):\n\t\t# \tprint(\"if(proper_note_usued ==False):\")\n\t\t# \tfor x in range(q):\n\t\t# \t\t# print('lol3')\n\t\t# \t\t# factor = .0001\n\t\t# \t\tfactor = 1 / b * 2 * pi\n\t\t# \t\t# sp = amplitudes_note[]\n\t\t# \t\t# sp = .3 * sin(a * (1) * factor * x)\n\t\t# \t\t# sp = sp + (.3 / 4) * sin(a * (1 + 1) * factor * x)\n\t\t# \t\tsp=0\n\t\t# \t\t# sp = sp + .3*sin(a * (1 + 2) * factor * x)\n\t\t# \t\t# sp = sp + .1*sin(a * (1 + 3) * factor * x)\n\t\t# \t\t# sp = sp * (1 + .1* sin(0.001*x))\n #\n\t\t# \t\tow = ow + sixteenbit(.5 * vol * sp)\n\t\t# \tfill = max(int(ex_pos - curpos - q), 0)\n\t\t# \tf.writeframesraw((ow) + (sixteenbit(0) * fill))\n\n\t\treturn q + fill\n\n\t##########################################################################\n\t# Write to output file (in WAV format)\n\t##########################################################################\n\n\tif silent == False:\n\t\tprint(\"Writing to file\", fn)\n\tcurpos = 0\n\tex_pos = 0.\n\tfor rp in range(repeat+1):\n\t\tfor nn, x in enumerate(song):\n\t\t\tif not nn % 4 and silent == False:\n\t\t\t\tprint(\"[%u/%u]\\t\" % (nn+1,len(song)))\n\t\t\tif x[0]!='r':\n\t\t\t\tif x[0][-1] == '*':\n\t\t\t\t\tvol = boost\n\t\t\t\t\tnote = x[0][:-1]\n\t\t\t\telse:\n\t\t\t\t\tvol = 1.\n\t\t\t\t\tnote = x[0]\n\t\t\t\ttry:\n\t\t\t\t\tprint(\"note:\",note)\n\t\t\t\t\ta=pitchhz[note]\n\t\t\t\texcept:\n\n\t\t\t\t\ta=pitchhz[note + '4']\t# default to fourth octave\n\t\t\t\ta = a * 2**transpose\n\t\t\t\tif x[1] < 0:\n\t\t\t\t\tb=length(-2.*x[1]/3.)\n\t\t\t\telse:\n\t\t\t\t\tb=length(x[1])\n\t\t\t\tex_pos = ex_pos + b\n\t\t\t\tcurpos = curpos + render2(a,b,vol,note)\n\n\t\t\tif x[0]=='r':\n\t\t\t\tb=length(x[1])\n\t\t\t\tex_pos = ex_pos + b\n\t\t\t\tf.writeframesraw(sixteenbit(0)*int(b))\n\t\t\t\tcurpos = curpos + int(b)\n\n\tf.writeframes(b'')\n\tf.close()\n\tprint()\n\n##########################################################################\n# Synthesize demo songs\n##########################################################################\n\nif __name__ == '__main__':\n\tprint()\n\tprint(\"Creating Demo Songs... (this might take about a minute)\")\n\tprint()\n\n\t# LOL1\n\t# make_wav(lol1, fn = \"lol1.wav\")\n\n\t# # SONG 1\n\t# make_wav(song1, fn = \"pysynth_scale.wav\")\n #\n\t# # SONG 2\n\t# make_wav(song2, bpm = 95, boost = 1.2, fn = \"pysynth_anthem.wav\")\n\tmake_wav(song5, bpm = 120, boost = 1, fn = \"pysynth_anthem_.wav\")\n #\n\t# # SONG 3\n\t# make_wav(song3, bpm = 132/2, pause = 0., boost = 1.1, fn = \"pysynth_chopin.wav\")\n\n\t# SONG 4\n\t# right hand part\n\t# make_wav(song4_rh, bpm = 130, transpose = 1, pause = .1, boost = 1.15, repeat = 1, fn = \"pysynth_bach_rh.wav\")\n\t# left hand part\n\t# make_wav(song4_lh, bpm = 130, transpose = 1, pause = .1, boost = 1.15, repeat = 1, fn = \"pysynth_bach_lh.wav\")\n\t# mix both files together\n\t# mix_files(\"pysynth_bach_rh.wav\", \"pysynth_bach_lh.wav\", \"pysynth_bach.wav\")\n\n","sub_path":"pysynth_d_mod_single_sin_tone.py","file_name":"pysynth_d_mod_single_sin_tone.py","file_ext":"py","file_size_in_byte":7944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"209509574","text":"class Categorias:\n CategoriaModel = None\n CategoriaSquema = None\n def __init__(self,db,ma):\n class CategoriaModel(db.Model):\n __tablename__ = \"tbl_categorias\"\n\n categoria_id = db.Column(db.Integer, primary_key=True)\n nombre = db.Column(db.String(40), unique=True)\n productos = db.relationship('ProductosModel', backref='CategoriaModel')\n\n def __init__(self, nombre):\n self.nombre = nombre\n\n class CategoriaSquema(ma.Schema):\n class Meta:\n fields = ('categoria_id', 'nombre')\n\n self.CategoriaModel = CategoriaModel\n self.CategoriaSquema = CategoriaSquema","sub_path":"entidades/Categorias.py","file_name":"Categorias.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"11158918","text":"import cv2\nimport numpy as np\nimport face_recognition\nimport os\n\n# 설정\npath = 'ImageBasic'\nimages = []\nclassNames = []\nmyList = os.listdir(path)\n\n# 사진 디렉토리 내 이미지 경로 리스트 추출\nfor cl in myList:\n curImg = cv2.imread(f'{path}/{cl}')\n images.append(curImg)\n classNames.append(os.path.splitext(cl)[0])\nprint(classNames)\n\n\n# 각 사진별 인코딩 함수\ndef find_encodings(image_paths):\n encode_list = []\n\n for image_path in image_paths:\n inner_image = cv2.cvtColor(image_path, cv2.COLOR_BGR2RGB)\n encode = face_recognition.face_encodings(inner_image)[0]\n encode_list.append(encode)\n return encode_list\n\n\n# 인코딩 리스트 받기\nencodeListKnown = find_encodings(images)\nprint(f'Encoding Complete {len(encodeListKnown)}')\n\n# 캠 영상 받아서 처리\ncap = cv2.VideoCapture(0)\n\nwhile True:\n success, cap_img = cap.read()\n imgS = cv2.resize(cap_img, (0, 0), None, 0.25, 0.25)\n imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB)\n\n # 캠 얼굴 인코딩\n faceCurFrame = face_recognition.face_locations(imgS)\n encodesCurFrame = face_recognition.face_encodings(imgS, faceCurFrame)\n\n # 캠 얼굴과 메모리상 인코딩 데이터간의 비교\n for encodeFace, faceLoc in zip(encodesCurFrame, faceCurFrame):\n matches = face_recognition.compare_faces(encodeListKnown, encodeFace)\n faceDis = face_recognition.face_distance(encodeListKnown, encodeFace)\n\n matchIndex = np.argmin(faceDis)\n\n if matches[matchIndex]:\n name = classNames[matchIndex].upper()\n\n y1, x2, y2, x1 = faceLoc\n y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4\n cv2.rectangle(cap_img, (x1, y1), (x2, y2), (0, 255, 0), 2)\n cv2.rectangle(cap_img, (x1, y2 - 35), (x2, y2),\n (0, 255, 0), cv2.FILLED)\n cv2.putText(cap_img, name, (x1 + 6, y2 - 6),\n cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)\n cv2.imshow('cam', cap_img)\n cv2.waitKey(1)\n","sub_path":"modules/face_recognition/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"52249087","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[4]:\n\n\n# Action1:求2+4+6+8+...+100的求和,用Python该如何写\n\n# 求从0开始到N的所有偶数之和,定义函数SumEven(N)\n\ndef SumEven(N):\n sumeven = 0\n for i in range(0,N+1,2):\n sumeven = sumeven + i\n return sumeven\n\nN = 100\nprint(SumEven(N)) \n \n\n\n# In[ ]:\n\n\n\n\n","sub_path":"L1-1.py","file_name":"L1-1.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"359143590","text":"#!/srv/home/wconnell/anaconda3/envs/lightning\n\n\"\"\"\nAuthor: Will Connell\nDate Initialized: 2020-09-27\nEmail: connell@keiserlab.org\n\nScript to preprocess data.\n\"\"\" \n\n\n###########################################################################################################################################\n# # # # # # # # # # # # # # # # # # \n# IMPORT MODULES \n# # # # # # # # # # # # # # # # # # \n###########################################################################################################################################\n\n\n# I/O\nimport os\nimport sys\nimport argparse\nfrom pathlib import Path\nimport joblib\nimport pyarrow.feather as feather\n\n# Data handling\nimport numpy as np\nimport pandas as pd\nfrom sklearn import model_selection\n\n# Chem\nfrom rdkit import DataStructs\nfrom rdkit.Chem import MolFromSmiles\nfrom rdkit.Chem import AllChem\n\n# Transforms\nfrom sklearn.preprocessing import StandardScaler\n\n\n###########################################################################################################################################\n# # # # # # # # # # # # # # # # # # \n# PRIMARY FUNCTIONS \n# # # # # # # # # # # # # # # # # # \n###########################################################################################################################################\n\n\ndef smiles_to_bits(smiles, nBits):\n mols = [MolFromSmiles(s) for s in smiles]\n fps = [AllChem.GetMorganFingerprintAsBitVect(m,2,nBits=nBits) for m in mols]\n np_fps = []\n for fp in fps:\n arr = np.zeros((1,), dtype=np.int8)\n DataStructs.ConvertToNumpyArray(fp, arr)\n np_fps.append(arr)\n df = pd.DataFrame(np_fps)\n return df\n\n\ndef process(out_path):\n np.random.seed(2299)\n ## Read data\n # Paths\n out_path = Path(out_path)\n out_path.mkdir(parents=True, exist_ok=True)\n ds_path = Path(\"../../film-gex-data/drug_screens/\")\n cm_path = Path(\"../../film-gex-data/cellular_models/\")\n # CCLE\n meta_ccle = pd.read_csv(cm_path.joinpath(\"sample_info.csv\"))\n ccle = pd.read_csv(cm_path.joinpath(\"CCLE_expression.csv\"), index_col=0)\n # L1000 genes\n genes = pd.read_csv(cm_path.joinpath(\"GSE70138_Broad_LINCS_gene_info_2017-03-06.txt.gz\"), sep=\"\\t\", index_col=0)\n # CTRP\n cp_ctrp = pd.read_csv(ds_path.joinpath(\"CTRP/v20.meta.per_compound.txt\"), sep=\"\\t\", index_col=0)\n cl_ctrp = pd.read_csv(ds_path.joinpath(\"CTRP/v20.meta.per_cell_line.txt\"), sep=\"\\t\", index_col=0)\n exp_ctrp = pd.read_csv(ds_path.joinpath(\"CTRP/v20.meta.per_experiment.txt\"), sep=\"\\t\", index_col=0)\n ctrp = pd.read_csv(ds_path.joinpath(\"CTRP/v20.data.per_cpd_post_qc.txt\") ,sep='\\t', index_col=0)\n\n ## Merge data\n data = ctrp.join(exp_ctrp['master_ccl_id']).drop_duplicates()\n data = data.merge(cl_ctrp['ccl_name'], left_on='master_ccl_id', right_index=True)\n data = data.merge(cp_ctrp[['broad_cpd_id', 'cpd_smiles']], left_on='master_cpd_id', right_index=True)\n data = data.merge(meta_ccle[['stripped_cell_line_name', 'DepMap_ID']], left_on='ccl_name', right_on='stripped_cell_line_name')\n\n ## Generate Fingerprints\n nBits=512\n cpd_data = data[['broad_cpd_id', 'cpd_smiles']].drop_duplicates()\n bits = smiles_to_bits(cpd_data['cpd_smiles'], nBits=nBits)\n bits.index = cpd_data['broad_cpd_id']\n bits.columns =[\"FP_{}\".format(i) for i in range(len(bits.columns))]\n\n ## Subset L1000 gene features by Entrez ID\n genes_lm = genes[genes['pr_is_lm']==1]\n ccle_cols = np.array([[gene[0], gene[1].strip(\"()\")] for gene in ccle.columns.str.split(\" \")])\n ccle.columns = ccle_cols[:,1]\n ccle = ccle[genes_lm.index.astype(str)]\n\n ## Merge bits and GEX\n data = data.merge(bits, left_on=\"broad_cpd_id\", right_index=True)\n data = data.merge(ccle, left_on=\"DepMap_ID\", right_index=True)\n print(\"{} unique compounds and {} unique cell lines comprising {} data points\".format(data['broad_cpd_id'].nunique(),\n data['stripped_cell_line_name'].nunique(),\n data.shape[0]))\n \n ## Generate folds\n target = \"cpd_avg_pv\"\n group = \"stripped_cell_line_name\"\n n_splits = 5\n gene_cols = ccle.columns.to_numpy()\n fp_cols = bits.columns.to_numpy()\n \n data[\"fold\"] = -1\n data = data.sample(frac=1).reset_index(drop=True)\n gkf = model_selection.GroupKFold(n_splits=n_splits)\n for fold, (train_idx, val_idx) in enumerate(gkf.split(X=data, y=data[target].to_numpy(), groups=data[group].to_numpy())):\n print(len(train_idx), len(val_idx))\n data.loc[val_idx, 'fold'] = fold\n \n ## Generate transforms & write\n for fold in range(0, n_splits):\n train = data[data['fold'] != fold]\n val = data[data['fold'] == fold]\n # Transform\n scaler = StandardScaler()\n train.loc[:,gene_cols] = scaler.fit_transform(train.loc[:,gene_cols])\n val.loc[:,gene_cols] = scaler.transform(val.loc[:,gene_cols])\n # Write\n train.reset_index(drop=True).to_feather(out_path.joinpath(\"train_fold_{}.feather\".format(fold)))\n val.reset_index(drop=True).to_feather(out_path.joinpath(\"val_fold_{}.feather\".format(fold)))\n # Testing set\n train.sample(frac=0.05).reset_index(drop=True).to_feather(out_path.joinpath(\"sub_train_fold_{}.feather\".format(fold)))\n val.sample(frac=0.05).reset_index(drop=True).to_feather(out_path.joinpath(\"sub_val_fold_{}.feather\".format(fold)))\n \n ## Write out\n joblib.dump(gene_cols, out_path.joinpath(\"gene_cols.pkl\"))\n joblib.dump(fp_cols, out_path.joinpath(\"fp_cols.pkl\"))\n data.sample(frac=0.05).reset_index(drop=True).to_feather(out_path.joinpath(\"data_sub.feather\"))\n data.reset_index(drop=True).to_feather(out_path.joinpath(\"data.feather\"))\n \n return \"Complete\"\n\n\n###########################################################################################################################################\n# # # # # # # # # # # # # # # # # # \n# CLI \n# # # # # # # # # # # # # # # # # # \n###########################################################################################################################################\n\ndef main():\n \"\"\"Parse Arguments\"\"\"\n desc = \"Script for preprocessing data for reproducibility.\"\n parser = argparse.ArgumentParser(description=desc,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n # positional\n parser.add_argument(\"path\", type=str,\n help=\"Directory to write processed data.\")\n args = parser.parse_args()\n \n return process(args.path)\n\n\nif __name__ == \"__main__\": # pragma: no cover\n sys.exit(main()) ","sub_path":"project/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":7714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"67036499","text":"import signal\nimport os\nimport datetime\nfrom logging import getLogger, Formatter, FileHandler, StreamHandler, DEBUG\n\ntoday = datetime.date.today()\ntoday = today.strftime(\"%Y%m%d\")\n\npath_to_log = \"{0}/log/{1}.log\".format(os.path.dirname(__file__), today)\nfmt = \"%(asctime)s %(name)s %(lineno)d [%(levelname)s][%(funcName)s] %(message)s\"\nlog_fmt = Formatter(fmt)\n\ndef get_logger(module_name):\n logger = getLogger(module_name)\n handler = StreamHandler()\n handler.setLevel(\"INFO\")\n handler.setFormatter(log_fmt)\n logger.addHandler(handler)\n\n handler = FileHandler(path_to_log, 'a')\n handler.setLevel(DEBUG)\n handler.setFormatter(log_fmt)\n logger.setLevel(DEBUG)\n logger.addHandler(handler)\n\n return logger\n\ndef ctrlc_handler(signal, frame):\n print(\"\\nKeyboardInterrupt\")\n exit()\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"104902173","text":"import numpy as np\nfrom sklearn.metrics import confusion_matrix\nimport pandas as pd \nfrom keras.utils import np_utils\nfrom sklearn.preprocessing import LabelEncoder\nfrom keras.models import Sequential\nfrom sklearn.model_selection import train_test_split \nfrom keras.layers import Dense\nimport time\nfrom sklearn.metrics import confusion_matrix, classification_report\n\n\n\ndata_set= pd.read_csv('/content/drive/MyDrive/BTP/kddcup.data.csv') \nx= data_set.iloc[:, 0:41].values \ny= data_set.iloc[:, 41].values \nd = {}\n# Counting data poihnts of each class\nfor val in y:\n if val in d:\n d[val] = d[val]+1\n else:\n d[val] = 1\n\nprint(d)\n\nlabel_encoder_x1= LabelEncoder() \nlabel_encoder_x2= LabelEncoder() \nlabel_encoder_x3= LabelEncoder() \n \nx[:, 1]= label_encoder_x1.fit_transform(x[:, 1]) \nx[:, 2]= label_encoder_x2.fit_transform(x[:, 2]) \nx[:, 3]= label_encoder_x3.fit_transform(x[:, 3]) \n\nattack_class = {'normal.': 'Normal', 'back.': 'DOS', 'smurf.':'DOS', 'neptune.':'DOS', 'pod.': 'DOS', 'teardrop.':'DOS', 'land.': 'DOS',\n 'multihop.':'R2L', 'ftp_write.': 'R2L', 'guess_passwd.': 'R2L', 'imap.': 'R2L', 'phf.': 'R2L', 'spy.':'R2L', 'warezmaster.':'R2L', 'warezclient.':'R2L',\n 'rootkit.':'U2R', 'loadmodule.':'U2R', 'buffer_overflow.': 'U2R', 'perl.': 'U2R',\n 'portsweep.':'PROBE', 'satan.':'PROBE', 'ipsweep.': 'PROBE', 'nmap.':'PROBE'}\n\n \nfor i in range(len(y)):\n y[i] = attack_class[y[i]]\n\nencoder = LabelEncoder()\nencoder.fit(y)\nencoded_Y = encoder.transform(y)\ndummy_y = np_utils.to_categorical(encoded_Y)\n\nx_train, x_test, y_train, y_test= train_test_split(x, dummy_y, test_size= 0.30, random_state=0)\n\n\n\n\nmodel = Sequential()\nmodel.add(Dense(12, input_dim=41, activation='relu'))\nmodel.add(Dense(8, activation='relu'))\nmodel.add(Dense(8, activation='relu'))\nmodel.add(Dense(5, activation='softmax'))\n\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\ny_train = np.asarray(y_train).astype('float32')\nx_train = np.asarray(x_train).astype('float32')\nprint(y_train[:10])\ntime_start = time.time()\nmodel.fit(x_train, y_train, epochs=10, batch_size=10)\ntime_end = time.time()\nprint(\"Training time: \", time_end - time_start)\n\ny_test = np.asarray(y_test).astype('float32')\nx_test = np.asarray(x_test).astype('float32')\n\n_, accuracy = model.evaluate(x_test, y_test)\nprint(\"Accuracy: \", accuracy)\n\n\ntime_start = time.time()\ny_pred = model.predict(x_test)\ntime_end = time.time()\nprint(\"Testing time: \", time_end - time_start)\n\ny_pred = np.argmax(y_pred, axis=1)\ny_test = np.argmax(y_test, axis=1)\n\nprint(confusion_matrix(y_test, y_pred))\nprint(classification_report(y_test, y_pred))","sub_path":"Phase 2/Code/DL Models/5 Classes/dl_5_3HiddenLayer.py","file_name":"dl_5_3HiddenLayer.py","file_ext":"py","file_size_in_byte":2675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"359333906","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 31 22:57:29 2020\n\n@author: vismujum\n\"\"\"\n#import numpy as np\n\nimport pandas as pd\nimport numpy as np\nimport statsmodels.formula.api as sm\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn import tree\n\n#pip install pandas\n#pip install numpy\ndef vif_cal(input_data, dependent_col):\n x_vars=input_data.drop([dependent_col], axis=1)\n xvar_names=x_vars.columns\n for i in range(0,xvar_names.shape[0]):\n y1=x_vars[xvar_names[i]]\n x1=x_vars[xvar_names.drop(xvar_names[i])]\n rsq=sm.ols(formula=\"y1~x1\", data=x_vars).fit().rsquared\n vif=round(1/(1-rsq),2)\n print (xvar_names[i], \" VIF = \" , vif)\n\n\n\ndef mktDetails_pTest():\n # Read CSV File to capture Marketing Details\n df = pd.read_csv('C:\\codeRepository\\machine-learning\\Marketing_Details.csv')\n \n # Replace all rows that has missing values\n df.dropna(inplace = True)\n \n # Information on attributes\n df.info()\n\n # Number of Data Entries - Marketing details\n df.shape\n df.head()\n\n df.rename(columns={'Visits':'visits','Unique Visitors':'unique_visitors' ,'Leads':'leads','MQL':'mql','Pipeline Count':'pipeline_count','Opportunity Accounts':'opportunity_accounts','MC Subscriptions':'mc_subscriptions','MC Net Adds':'mc_net_adds'},inplace=True)\n\n # Lets identify Less impactful variables when we are identifying total subscription (mc_subscriptions) are received based for a given campaign \n # Visits and Unique visitirs are independent variable and rest all are dependent variables.\n\n # visits, unique_visitors,leads',mql , pipeline_count,opportunity_accounts,mc_subscriptions, mc_net_adds'\n # Impactful variables to determin MC Net Additions \n model_mcNetAdds = sm.ols(formula='mc_net_adds~visits+unique_visitors+leads+mql+pipeline_count+opportunity_accounts+mc_subscriptions' , data=df)\n fitted_mcNetAdds = model_mcNetAdds.fit()\n fitted_mcNetAdds.summary()\n \n model_mcNetAdds = sm.ols(formula='mc_net_adds~unique_visitors+leads+mql+pipeline_count+opportunity_accounts+mc_subscriptions' , data=df)\n fitted_mcNetAdds = model_mcNetAdds.fit()\n fitted_mcNetAdds.summary()\n\n # Apart from Visits attribute all other paraemters are required to predict no. of Net Addition in Subsctions\n\n\n # Impactful variables to determin MC Subscriptions \n model_mcSubs = sm.ols(formula='mc_subscriptions~visits+unique_visitors+leads+mql+pipeline_count+opportunity_accounts' , data=df)\n fitted_mcSubs = model_mcSubs.fit()\n fitted_mcSubs.summary()\n # All paraemters are required to predict No of Subsctions achived by Given Campaign\n\n # Impactful variables to determin Pipeline Count\n model_pipeLine = sm.ols(formula='pipeline_count~visits+unique_visitors+leads+mql+opportunity_accounts' , data=df)\n fitted_pipeLine = model_pipeLine.fit()\n fitted_pipeLine.summary()\n # Visits , Leads and MQL play an important role in identifying Pipeline count for a marketing campaign\n \n # Impactful variables to determin Opportunity Accounts\n model_opporAcc = sm.ols(formula='opportunity_accounts~visits+unique_visitors+leads+mql' , data=df)\n fitted_opporAcc = model_opporAcc.fit()\n fitted_opporAcc.summary()\n # All parameters are required to predict Number of opportunity accounts that are acived from Marketing campaign\n \n # Impactful variables to determin MQL\n model_mql = sm.ols(formula='mql~visits+unique_visitors+leads' , data=df)\n fitted_mql = model_mql.fit()\n fitted_mql.summary()\n # All parameters are required to predict Number of opportunity accounts that are acived from Marketing campaign\n\n # Impactful variables to determin Leads\n model_leads = sm.ols(formula='mql~visits+unique_visitors' , data=df)\n fitted_leads = model_leads.fit()\n fitted_leads.summary()\n\ndef mktDetails_decisionTree():\n # Read CSV File to capture Marketing Details\n df = pd.read_csv('C:\\codeRepository\\machine-learning\\Marketing_Details.csv')\n \n # Replace all rows that has missing values\n df.dropna(inplace = True)\n # Information on attributes\n df.info()\n # Number of Data Entries - Marketing details\n df.shape\n df.head()\n df.rename(columns={'Visits':'visits','Unique Visitors':'unique_visitors' ,'Leads':'leads','MQL':'mql','Pipeline Count':'pipeline_count','Opportunity Accounts':'opportunity_accounts','MC Subscriptions':'mc_subscriptions','MC Net Adds':'mc_net_adds'},inplace=True)\n\n features = list(df.columns[0:6])\n x = df[features]\n y = df['mc_net_adds']\n clf = tree.DecisionTreeClassifier(max_depth=3)\n clf.fit(x,y)\n from IPython.display import Image\n from sklearn.externals.six import StringIO\n from sklearn import tree\n import pydotplus\n #import graphviz\n\n dot_data = StringIO()\n tree.export_graphviz(clf,out_file=dot_data,feature_names=features , filled=True,rounded=True, impurity=False)\n graph = pydotplus.graph_from_dot_data(dot_data.getvalue())\n\n Image(graph.create_png())\n\ndef mktDetails_VIFTest():\n df = pd.read_csv('C:\\codeRepository\\machine-learning\\Marketing_Details.csv')\n # Replace all rows that has missing values\n df.dropna(inplace = True)\n # Information on attributes\n df.info()\n # Number of Data Entries - Marketing details\n df.shape\n df.head()\n df.rename(columns={'Visits':'visits','Unique Visitors':'unique_visitors' ,'Leads':'leads','MQL':'mql','Pipeline Count':'pipeline_count','Opportunity Accounts':'opportunity_accounts','MC Subscriptions':'mc_subscriptions','MC Net Adds':'mc_net_adds'},inplace=True)\n df1 = df.drop('visits')\n vif_cal(df1 , \"mc_net_adds\")\n\n\n \nif __name__ == \"__main__\":\n print(\"Executing as main program\")\n print(\"Value of __name__ is: \", __name__)\n mktDetails_pTest()\n\n","sub_path":"python-files/marketing_details.py","file_name":"marketing_details.py","file_ext":"py","file_size_in_byte":5792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"61453262","text":"#!/usr/bin/python\n# Copyright (c) 2017 Dell Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n#\n# THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT\n# LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS\n# FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.\n#\n# See the Apache Version 2.0 License for specific language governing\n# permissions and limitations under the License.\n\n\n\"\"\"Module for creation of the VxLAN Interface\"\"\"\nimport dn_base_ip_tool\nimport dn_base_br_tool\nimport ifindex_utils\nimport nas_os_if_utils as nas_if\nimport nas_vtep_config_obj as if_vtep_config\nimport copy\nimport cps_utils\nimport cps\n\nop_attr_name = 'dell-base-if-cmn/set-interface/input/operation'\n\nuse_linux_path = False\n\n''' Helper Methods '''\ndef _get_op_id(cps_obj):\n op_id_to_name_map = {1: 'create', 2: 'delete', 3: 'set'}\n op_id = None\n try:\n op_id = cps_obj.get_attr_data(op_attr_name)\n except ValueError:\n nas_if.log_err('No operation attribute in object')\n return None\n if not op_id in op_id_to_name_map:\n nas_if.log_err('Invalid operation type '+str(op_id))\n return None\n return op_id_to_name_map[op_id]\n\ndef __if_present(name):\n \"\"\"Method to check if the interface is present in linux\"\"\"\n if len(dn_base_ip_tool.get_if_details(name)) > 0:\n nas_if.log_info(\"Interface exists \" + str(name))\n return True\n nas_if.log_info(\"Interface doesn't exist \" + str(name))\n return False\n\ndef __create_vtep_if(vtep_name, vni, src_ip, addr_family):\n \"\"\"Method to create vtep interface in Linux\"\"\"\n if __if_present(vtep_name) is False and \\\n dn_base_ip_tool.create_vxlan_if(str(vtep_name), str(vni),\n str(src_ip), addr_family) is True:\n nas_if.log_info(\"Successfully created VTEP Interface \" + str(vtep_name))\n if_index = ifindex_utils.if_nametoindex(vtep_name)\n return True, if_index\n nas_if.log_err(\"Failed to create VTEP Interface \" + str(vtep_name))\n return False, None\n\ndef __delete_vtep_if(vtep_name):\n \"\"\"Method to delete vtep interface in Linux\"\"\"\n if __if_present(vtep_name) is True and \\\n dn_base_ip_tool.delete_if(vtep_name):\n nas_if.log_info(\"Successfully deleted VTEP Interface \" + str(vtep_name))\n return True\n nas_if.log_err(\"Failed to delete VTEP Interface \" + str(vtep_name))\n return False\n\ndef __add_remote_endpoints(vtep_name, remote_endpoints):\n \"\"\"Method to Add Remote Endpoints for the VxLAN in Linux\"\"\"\n rlist = {}\n for src_ip in remote_endpoints:\n remote_endpoint = remote_endpoints[src_ip]\n if dn_base_br_tool.add_learnt_mac_to_vtep_fdb(vtep_name, src_ip, \\\n remote_endpoint.addr_family, \\\n remote_endpoint.mac_addr) is False:\n nas_if.log_err(\"Failed to add remote endpoints \" + str(src_ip) + \" to VTEP Interface \" + str(vtep_name))\n return False, rlist\n rlist[src_ip] = remote_endpoints[src_ip]\n nas_if.log_info(\"Successfully added remote endpoint %s to Bridge Interface\" % (str(src_ip)))\n return True, rlist\n\ndef __remove_remote_endpoints(vtep_name, remote_endpoints):\n \"\"\"Method to Remove Remote Endpoints for the VxLAN in Linux\"\"\"\n rlist = {}\n for src_ip in remote_endpoints:\n remote_endpoint = remote_endpoints[src_ip]\n if dn_base_br_tool.del_learnt_mac_from_vtep_fdb(vtep_name, src_ip, \\\n remote_endpoint.addr_family, \\\n remote_endpoint.mac_addr) is False:\n nas_if.log_err(\"Failed to remove remote endpoints \" + str(src_ip) + \" to VTEP Interface \" + str(vtep_name))\n return False, rlist\n rlist[src_ip] = remote_endpoints[src_ip]\n nas_if.log_info(\"Successfully removed remote endpoint %s to Bridge Interface\" % (str(src_ip)))\n return True, rlist\n\n\n''' Create, Update and Delete '''\ndef update(cps_obj, params, cfg_obj):\n \"\"\"Method to set attributes for the VTEP in Linux\"\"\"\n _remote_endpoints = remote_endpoints = []\n member_op = if_vtep_config.get_member_op(cps_obj)\n ret, remote_endpoints = if_vtep_config.get_remote_endpoint_list(cps_obj)\n\n while True:\n if member_op == 'add':\n ret, _remote_endpoints = __add_remote_endpoints(cfg_obj.name, remote_endpoints)\n if ret is False:\n break\n else:\n ret, _remote_endpoints = __remove_remote_endpoints(cfg_obj.name, remote_endpoints)\n if ret is False:\n break\n return True\n\n nas_if.log_err(\"Update VTEP Failed, Rolling back\")\n if member_op == 'add':\n __remove_remote_endpoints(cfg_obj.name, _remote_endpoints)\n else:\n __add_remote_endpoints(cfg_obj.name, _remote_endpoints)\n return False\n\ndef create(cps_obj, params, cfg_obj):\n \"\"\"Method to create the VTEP in Linux\"\"\"\n _remote_endpoints = []\n while(True):\n ret, if_index = __create_vtep_if(cfg_obj.name, cfg_obj.vni, cfg_obj.ip, cfg_obj.addr_family)\n if ret is False:\n break\n ret, _remote_endpoints = __add_remote_endpoints(cfg_obj.name, cfg_obj.remote_endpoints)\n if ret is False:\n break\n return True\n\n nas_if.log_err(\"Create VTEP Failed, Rolling back\")\n __remove_remote_endpoints(cfg_obj.name, _remote_endpoints)\n __delete_vtep_if(cfg_obj.name)\n return False\n\ndef delete(cps_obj, params, cfg_obj):\n \"\"\"Method to delete the VTEP in Linux\"\"\"\n __remove_remote_endpoints(cfg_obj.name, cfg_obj.remote_endpoints)\n __delete_vtep_if(cfg_obj.name)\n return True\n\ndef _send_obj_to_base(cps_obj,op):\n nas_if.log_info('Sending vxlan object to base')\n in_obj = copy.deepcopy(cps_obj)\n in_obj.set_key(cps.key_from_name('target', 'dell-base-if-cmn/if/interfaces/interface'))\n obj = in_obj.get()\n if 'operation' in obj:\n del obj['operation']\n upd = (op, obj)\n _ret = cps_utils.CPSTransaction([upd]).commit()\n if not _ret:\n nas_if.log_err('BASE transaction for vxlan failed')\n return False\n return True\n\ndef handle_vtep_intf(cps_obj, params):\n \"\"\"Method to handle VTEP interface set, create or delete operations\"\"\"\n op = _get_op_id(cps_obj)\n if op is None:\n return False\n\n if not use_linux_path:\n return _send_obj_to_base(cps_obj,op)\n\n cfg_obj = if_vtep_config.create(cps_obj)\n if cfg_obj is None:\n return False\n\n if op == 'create' and create(cps_obj, params, cfg_obj) is True:\n return if_vtep_config.cache_add(cfg_obj.name, cfg_obj)\n if op == 'delete' and delete(cps_obj, params, cfg_obj) is True:\n return if_vtep_config.cache_del(cfg_obj.name)\n if op == 'set' and update(cps_obj, params, cfg_obj) is True:\n return if_vtep_config.cache_update(cfg_obj.name, cfg_obj)\n return False\n\n","sub_path":"scripts/lib/python/nas_if_vtep.py","file_name":"nas_if_vtep.py","file_ext":"py","file_size_in_byte":7231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"627232930","text":"# -*- coding: utf-8 -*-\n__copyright__ = \"Copyright (c) 2014-2017 Agora.io, Inc.\"\n\nimport os\nimport sys\n\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\n\nfrom src.AccessToken2 import *\n\n\ndef main():\n app_id = \"970CA35de60c44645bbae8a215061b33\"\n app_certificate = \"5CFd2fd1755d40ecb72977518be15d3b\"\n channel_name = \"7d72365eb983485397e3e3f9d460bdda\"\n uid = 2882341273\n account = \"2882341273\"\n chat_user_id = \"2882341273\"\n expiration_in_seconds = 3600\n\n rtc_service = ServiceRtc(channel_name, uid)\n rtc_service.add_privilege(ServiceRtc.kPrivilegeJoinChannel, expiration_in_seconds)\n\n rtm_service = ServiceRtm(account)\n rtm_service.add_privilege(ServiceRtm.kPrivilegeLogin, expiration_in_seconds)\n\n chat_service = ServiceChat(chat_user_id)\n chat_service.add_privilege(ServiceChat.kPrivilegeUser, expiration_in_seconds)\n\n token = AccessToken(app_id=app_id, app_certificate=app_certificate, expire=expiration_in_seconds)\n token.add_service(rtc_service)\n token.add_service(rtm_service)\n token.add_service(chat_service)\n\n print(\"Token for RTC, RTM and CHAT: {}\".format(token.build()))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"DynamicKey/AgoraDynamicKey/python/sample/AccessToken2Sample.py","file_name":"AccessToken2Sample.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"287575495","text":"import json\nimport requests\n\n\ndef main():\n delete_all_people()\n post_people()\n get_people()\n\n\ndef url_for(endpoint, url='localhost', port=5000):\n return f'http://{url}:{port}/{endpoint}/'\n\n\ndef delete_all_people():\n r = requests.delete(url_for('people'))\n print(f\"'people' deleted, server response: {r.status_code}\")\n\n\ndef post_people():\n data = [\n {'firstname': 'John', 'lastname': 'Doe'},\n {'firstname': 'Mike', 'lastname': 'Green'},\n ]\n\n r = requests.post(\n url_for('people'),\n json.dumps(data),\n headers={'Content-Type': 'application/json'}\n )\n print(f\"'people' posted, server response: {r.status_code}\")\n\n\ndef get_people():\n r = requests.get(url_for('people'))\n print(f\"'people' downloaded, server response: {r.status_code}\")\n\n if r.status_code == 200:\n people = r.json()['_items']\n print(f'{len(people)} people:')\n [print(f\"\\t{person['firstname']}, {person['_id']}\") for person in people]\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"my_code/clients/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"473930097","text":"#coding=utf-8\nimport requests\nimport threading\nimport re\nimport time\npage_s=input('请输入开始页码(1-92):')\npage_e=input('请输入结束页码(1-92):')\nwhile int(page_s)>int(page_e):#除了开始页码大于结束页码的输入都会被要求重新输入\n print('请重新输入页码')\n page_s = input('请输入开始页码(1-92):')\n page_e = input('请输入结束页码(1-92):')\n\ndef get_pic(page):\n\n url = 'http://jandan.net/ooxx/page-%s#comments' % page\n req=requests.get(url)\n try:\n txt=req.text\n id1 = re.findall(r'data-id=\"([0-9]*)\"', txt)\n id = list(set(id1)) # 去除重复\n data = [] #【1.id,2.图片连接,3.点赞数,4.反对数】\n for i in id:\n pic = re.findall(i+r'

    [\\s\\S]*?(.*)\\]\", txt)\n unlike = re.findall(r\"comment-unlike.*\" + i + \".*\\[(.*)\\]\", txt)\n data.append([i, pic[0][0], like[0], unlike[0]])\n except not req.ok:\n print(\"获取网页内容失败\")\n for each in data:\n try:\n html=requests.get('http://'+each[1],timeout=1)\n except not req.ok:\n print(\"获取图片内容失败\")\n with open(\"D:\\python study\\crossin\\Qimozuoye\\pic\\\\\"+each[0]+'赞'+each[2]+'反对'+each[3]+each[1][-4:],'wb') as f:\n f.write(html.content)\n print(each[0]+'下载完成')\n\nfor page in range(int(page_s),int(page_e)+1):\n #get_pic(page)\n t = threading.Thread(target=get_pic,args=(str(page),))\n t.start()\n","sub_path":"Qimozuoye/jiandan(beta).py","file_name":"jiandan(beta).py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"583436023","text":"import matplotlib.pyplot as plt\nfrom pylab import rcParams\nimport yfinance as yf\nimport datetime as dt\nimport warnings\nimport talib \nimport ta\n\nwarnings.filterwarnings(\"ignore\")\nyf.pdr_override()\n\n# input\nsymbol = str(input('Enter a ticker: '))\nnum_of_years = 1\nstart = dt.date.today() - dt.timedelta(days = int(365.25 * num_of_years))\nend = dt.date.today()\n\n# Read data \ndata = yf.download(symbol,start,end)\n\n# ## SMA and EMA\n#Simple Moving Average\ndata['SMA'] = talib.SMA(data['Adj Close'], timeperiod = 20)\n\n# Exponential Moving Average\ndata['EMA'] = talib.EMA(data['Adj Close'], timeperiod = 20)\n\n# Plot\nrcParams['figure.figsize'] = 15,10\ndata[['Adj Close','SMA','EMA']].plot(figsize=(15, 10))\nplt.xlabel('Dates')\nplt.ylabel('Close Price')\nplt.title(f'SMA vs. EMA for {symbol.upper()}')\nplt.show()\n\n\n# ## Bollinger Bands\n# Bollinger Bands\ndata['upper_band'], data['middle_band'], data['lower_band'] = talib.BBANDS(data['Adj Close'], timeperiod =20)\n\n# Plot\ndata[['Adj Close','upper_band','middle_band','lower_band']].plot(figsize=(15,10))\nplt.show()\n\n\n# ## MACD (Moving Average Convergence Divergence)\n# MACD\ndata['macd'], data['macdsignal'], data['macdhist'] = talib.MACD(data['Adj Close'], fastperiod=12, slowperiod=26, signalperiod=9)\ndata[['macd','macdsignal']].plot(figsize=(15,10))\nplt.xlabel('Dates')\nplt.ylabel('MACD')\nplt.title(f'Moving Average Convergence Divergence for {symbol.upper()}')\nplt.show()\n\n\n# ## RSI (Relative Strength Index)\n# RSI\ndata['RSI'] = talib.RSI(data['Adj Close'], timeperiod=14)\n# Plotting RSI\nfig,ax = plt.subplots(figsize=(15, 10))\nax.plot(data.index, data.RSI, label='RSI')\nax.fill_between(data.index, y1=30, y2=70, color = 'lightcoral', alpha=0.3)\nax.set_xlabel('Date')\nax.set_ylabel('RSI')\nax.set_title(f'Relative Strength Index for {symbol.upper()}')\nplt.show()\n\n\n# ## OBV (On Balance Volume)\n# OBV\ndata['OBV'] = talib.OBV(data['Adj Close'], data['Volume'])/10**6\n\nfig, (ax1, ax2) = plt.subplots(2)\nfig.suptitle(f'Close Price vs. On Balance Volume for {symbol.upper()}')\nax1.plot(data['Adj Close'])\nax1.set_ylabel('Close')\nax2.plot(data['OBV'])\nax2.set_ylabel('On Balance Volume (in millions)')\nplt.show()\n\n## CCI (Commodity Channel Index)\n# CCI\ncci = ta.trend.cci(data['High'], data['Low'], data['Close'], n=31, c=0.015)\nplt.subplots()\nrcParams['figure.figsize'] = 15,10\nplt.plot(cci)\nplt.axhline(y=0, color='r', linestyle='-')\nplt.xlabel('Dates')\nplt.ylabel('Commodity Channel Index')\nplt.title(f'Commodity Channel Index for {symbol.upper()}')\nplt.show()","sub_path":"Portfolio_Strategies/main_indicators_mult_graphs.py","file_name":"main_indicators_mult_graphs.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"56562137","text":"from django.shortcuts import render, redirect\nfrom myapp.item.models import Product\nfrom myapp.item.models import Ingredient\nfrom .forms import ProductQueryForm\nfrom .forms import ProductDetailForm\n\n# Create your views here.\ndef index(request):\n products = Product.objects.all()\n return render(request, 'index.html', {'products': products})\n\n\ndef show_ingredient(request):\n ingredients = Ingredient.objects.all()\n return render(request, 'ingredients.html', {'ingredients': ingredients})\n\n\n# 상품 목록 조회하기\ndef product_list(request):\n form = ProductQueryForm()\n\n if request.GET.get('skin_type') is not None:\n skin_type = request.GET.get('skin_type')\n # category = request.GET.get('category')\n page = request.GET.get('page')\n # exclude_in = request.GET.get('exclude_ingredient')\n # include_in = request.GET.get('include_ingredient')\n products, fitness = products_print(skin_type, 50, None, page, None, None)\n return render(request, 'product_list.html', {'form': form, 'products': products, 'fitness': fitness})\n\n return render(request, 'product_list.html', {'form': form})\n\n\n# 상품 상세 정보 조회하기\ndef product_detail(request, id):\n form = ProductDetailForm()\n\n product = Product.objects.get(id=id)\n base_url = \"https://grepp-programmers-challenges.s3.ap-northeast-2.amazonaws.com/2020-birdview/\"\n image_dir = \"image/\"\n thumbnail_dir = \"thumbnail/\"\n image_url = base_url + image_dir\n thumbnail_url = base_url + thumbnail_dir\n # 추천 상품 3개 보여주는 경우\n if request.GET.get('skin_type') is not None:\n skin_type = request.GET.get('skin_type')\n recommended, _ = products_print(skin_type, 3)\n return render(request, 'product_detail.html', {'product': product, 'image_url': image_url,\n 'thumbnail_url': thumbnail_url, 'recommended': recommended})\n\n return render(request, 'product_detail.html', {'form': form, 'product': product, 'image_url': image_url,\n 'thumbnail_url': thumbnail_url})\n\n\n# -------------inner function in product_list---------------\n# 보여질 50개의 제품\ndef products_print(skin_type, num_of_product=50, category=None, page=None, exclude_str=None, include_str=None):\n if page is None:\n page = 1\n else:\n page = int(page)\n\n products = set_products(category, exclude_str, include_str)\n id_score = {} # 제품 id에 현재 피부타임 점수를 key-value로 저장\n\n for product in products:\n score = 0\n ingredients = product.ingredients.split(',')\n for ingredient in ingredients:\n cur_ingre = Ingredient.objects.get(name=ingredient)\n if Ingredient.get_effect(cur_ingre, skin_type) == 'O':\n score += 1\n elif Ingredient.get_effect(cur_ingre, skin_type) == 'X':\n score -= 1\n id_score[product.id] = score\n\n\n # id_score을 score를 기준으로 정렬 후, 페이지에 맞는 요소들을 꺼내옴\n sorted_id_score = sorted(id_score.items(), reverse=True, key=lambda id_score:id_score[1])\n\n id_list = []\n ans_list = []\n for i in range(num_of_product*(page-1), num_of_product*page):\n if i < len(sorted_id_score):\n id_list.append(sorted_id_score[i][0])\n ans_list.append(Product.objects.filter(id=sorted_id_score[i][0]))\n\n return Product.objects.filter(id__in=id_list), ans_list\n\n\n# 상품 카테고리가 정해진 경우 해당 상품만 list로 반환\ndef set_products(category, exclude_str, include_str):\n products = []\n if category is None:\n products = Product.objects.all()\n else:\n products = Product.objects.filter(category=category)\n if exclude_str is not None:\n products = exclude_ingredient(products, exclude_str)\n if include_str is not None:\n products = include_ingredient(products, include_str)\n return products\n\n\n# 제외할 성분을 하나라도 갖는 경우 리스트에서 제외시킴\ndef exclude_ingredient(products, exclude_str):\n delete_list =[]\n exclude_list = exclude_str.split(',')\n for product in products:\n is_delete = False\n ingredients = product.ingredients.split(',')\n for ingredient in ingredients:\n if isdelete is True:\n break\n for exclude in exclude_lst:\n if ingredient == exclude:\n is_delete = True\n if isdelete is True:\n break\n if is_delete is True:\n delete_list.append(product.id)\n\n products = products.exclude(id__in=delete_list)\n\n return products\n\n\n# 포함할 성분을 하나라도 포함하지 않은 경우 리스트에서 제외시킴\ndef include_ingredient(products, include_str):\n delete_list = []\n include_list = include_str.split(',')\n for product in products:\n is_delete = False\n ingredients = product.ingredients.split(',')\n for ingredient in ingredients:\n is_include = False\n for include in include_list:\n if include == ingredient:\n is_include = True\n if is_include is True:\n break\n\n if is_include is False:\n is_delete = True\n if is_delete is True:\n delete_list.append(product.id)\n\n products = products.exclude(id__in=delete_list)\n return products\n\n\n# 재료명과 피부타입이 주어지면, 점수를 반환해줌\n# ingredient : Ingredient class\n# type : oily dry sensitive\ndef ingredient_effect(ingredient, skin_type):\n if ingredient.get_effect(skin_type) == 'O':\n return 1\n elif ingredient.get_effect(skin_type) == 'X':\n return -1\n else:\n return 0\n\n\n\n \n\n\n\n\n","sub_path":"django 리스팅/myapp/home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"605970222","text":"# -*- coding: utf-8 -*-\n\n# Copyright 2013 Mirantis, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nHandlers dealing with disks\n\"\"\"\n\nfrom ..manager import DisksFormatConvertor\nfrom ..validators.disks import NodeDisksValidator\nfrom nailgun.api.v1.handlers.base import BaseHandler\nfrom nailgun.api.v1.handlers.base import content\nfrom nailgun import objects\n\n\nclass NodeDisksHandler(BaseHandler):\n\n validator = NodeDisksValidator\n\n @content\n def GET(self, node_id):\n \"\"\":returns: JSONized node disks.\n\n :http: * 200 (OK)\n * 404 (node not found in db)\n \"\"\"\n from ..objects.volumes import VolumeObject\n\n node = self.get_object_or_404(objects.Node, node_id)\n node_volumes = VolumeObject.get_volumes(node)\n return DisksFormatConvertor.format_disks_to_simple(node_volumes)\n\n @content\n def PUT(self, node_id):\n \"\"\":returns: JSONized node disks.\n\n :http: * 200 (OK)\n * 400 (invalid disks data specified)\n * 404 (node not found in db)\n \"\"\"\n from ..objects.volumes import VolumeObject\n\n node = self.get_object_or_404(objects.Node, node_id)\n data = self.checked_data(\n self.validator.validate,\n node=node\n )\n\n if node.cluster:\n objects.Cluster.add_pending_changes(\n node.cluster,\n 'disks',\n node_id=node.id\n )\n\n volumes_data = DisksFormatConvertor.format_disks_to_full(node, data)\n VolumeObject.set_volumes(node, volumes_data)\n\n return DisksFormatConvertor.format_disks_to_simple(\n VolumeObject.get_volumes(node))\n\n\nclass NodeDefaultsDisksHandler(BaseHandler):\n\n @content\n def GET(self, node_id):\n \"\"\":returns: JSONized node disks.\n\n :http: * 200 (OK)\n * 404 (node or its attributes not found in db)\n \"\"\"\n node = self.get_object_or_404(objects.Node, node_id)\n if not node.attributes:\n raise self.http(404)\n\n volumes = DisksFormatConvertor.format_disks_to_simple(\n node.volume_manager.gen_volumes_info())\n\n return volumes\n\n\nclass NodeVolumesInformationHandler(BaseHandler):\n\n @content\n def GET(self, node_id):\n \"\"\":returns: JSONized volumes info for node.\n\n :http: * 200 (OK)\n * 404 (node not found in db)\n \"\"\"\n node = self.get_object_or_404(objects.Node, node_id)\n if node.cluster is None:\n raise self.http(404, 'Cannot calculate volumes info. '\n 'Please, add node to an environment.')\n volumes_info = DisksFormatConvertor.get_volumes_info(node)\n return volumes_info\n","sub_path":"nailgun/nailgun/extensions/volume_manager/handlers/disks.py","file_name":"disks.py","file_ext":"py","file_size_in_byte":3280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"529493131","text":"import Logger.Logger as log\n\nclass Joint:\n \n #a list of x and y coordinates for the polygon, each odd is x and even is y\n polygon = []\n \n #if shapename is not \"custom\", *arg contains arguments for preset shapes\n #otherwise it contains list of coordinates for a custom polygon\n def __init__(self, shapeName, *arg):\n \n if shapeName == \"custom\":\n \n cnt = len(arg)\n #zero or uneven number of coordinate arguments\n if cnt == 0 or cnt % 2 != 0:\n log.UnexpectedArgumentCountForShape(cnt)\n \n \n ","sub_path":"Joint.py","file_name":"Joint.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"203753027","text":"import time\nimport requests\nimport datetime\nfrom urllib.parse import urlencode\nimport json\nimport pandas as pd\nfrom lovelyrita.config import API_KEY\n\nAPI_URL = \"https://maps.googleapis.com/maps/api/geocode/\"\n\nclass Geocoder(object):\n def __init__(self, geocodes=None, api_url=API_URL, api_key=API_KEY):\n if geocodes is None:\n geocodes = pd.DataFrame(columns=('lat', 'lng', 'place_id', 'timestamp'))\n geocodes.index.name='address'\n self.geocodes = geocodes\n self.api_url = API_URL\n self.api_key = API_KEY\n\n def geocode(self, address):\n \"\"\"\n Pull data from Google Maps API\n\n Parameters\n ----------\n address : str\n \"\"\"\n # check if query has already been run\n try:\n g = self.geocodes.loc[address]\n return g['lat'], g['lng'], g['place_id']\n except KeyError:\n pass\n\n query = {'address': address,\n 'key': self.api_key}\n url = self.api_url + 'json?' + urlencode(query)\n response = requests.get(url)\n if response.status_code == 404:\n raise Exception(\"404 error for {}\".format(url))\n\n content = response.json()\n if content['status'] != 'OK':\n raise Exception(\"Status not OK for {}\".format(url))\n\n place_id = content['results'][0]['place_id']\n lat = content['results'][0]['geometry']['location']['lat']\n lng = content['results'][0]['geometry']['location']['lng']\n timestamp = str(datetime.datetime.now())\n\n new_geocode = pd.Series({'place_id': place_id,\n 'lat': lat, 'lng': lng,\n 'timestamp': timestamp},\n name=address)\n self.geocodes = self.geocodes.append(new_geocode)\n return lat, lng, place_id\n \n @classmethod\n def load(cls, geocode_path):\n return cls(load_geocodes(geocode_path))\n def save(self, geocode_path):\n save_geocodes(self.geocodes, geocode_path)\n \ndef save_addresses(addresses, path):\n with open(path, 'w') as f:\n f.write('\\n'.join(addresses))\n\ndef load_addresses(path):\n with open(path, 'r') as f:\n addresses = f.read().split('\\n')\n return addresses\n\ndef save_geocodes(geocodes, path):\n geocodes.to_hdf(path, 'geocodes')\n\ndef load_geocodes(path):\n return pd.read_hdf(path)\n","sub_path":"lovelyrita/geocode.py","file_name":"geocode.py","file_ext":"py","file_size_in_byte":2411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"125956850","text":"\"\"\"\nCode that goes along with the Airflow located at:\nhttp://airflow.readthedocs.org/en/latest/tutorial.html\n\"\"\"\nfrom airflow import DAG\nfrom airflow.operators.python_operator import PythonOperator\nfrom datetime import datetime, timedelta\nfrom airflow.models import Variable\nimport requests\nimport psycopg2\nfrom requests.auth import HTTPBasicAuth\nfrom star_count_helper.star_count_helper import star_count_helper\n\n \ndefault_args = {\n \"owner\": \"airflow\",\n \"depends_on_past\": False,\n \"start_date\": datetime(2021, 7, 16),\n \"schedule_interval\": None,\n \"email\": [\"airflow@airflow.com\"],\n \"email_on_failure\": False,\n \"email_on_retry\": False,\n \"retries\": 1,\n # 'queue': 'bash_queue',\n # 'pool': 'backfill',\n # 'priority_weight': 10,\n # 'end_date': datetime(2016, 1, 1),\n}\n\ndag = DAG(\"rohit\", default_args=default_args, schedule_interval=timedelta(1))\n\ngit_conf = {\n 'github_repo_name' : Variable.get(\"repo_name\"),\n 'username' : Variable.get(\"username\"),\n 'password' : Variable.get(\"password\")\n} \n#git_conf\n\ndb_conf = {\n 'db_name' : Variable.get(\"db_name\"),\n 'db_user' : Variable.get(\"db_user\"),\n 'db_password' : Variable.get(\"db_password\"),\n 'db_host' : Variable.get(\"db_host\"),\n 'db_port' : Variable.get(\"db_port\") \n}\n\n# execution starts here\ndef github_star_count():\n\n # API CALL\n r = star_count_helper.call_api(git_conf)\n #r = requests.get('https://api.github.com/repos/'+ github_repo_name, auth = HTTPBasicAuth(username, password)).json()\n #r = requests.get('https://api.github.com/repos/'+ github_repo_name).json()\n print(\"stargazers_count: \",r[\"stargazers_count\"])\n print(\"watchers_count: \",r[\"watchers_count\"])\n print(\"forks: \",r[\"forks\"])\n star_count = int(r[\"stargazers_count\"])\n\n # Ingest data to DB \n star_count_helper.insert_data(db_conf, git_conf.get('github_repo_name'), star_count)\n\n return (str,200)\n\n\nt1 = PythonOperator(\n task_id='GithubStarCount',\n python_callable= github_star_count,\n #op_kwargs = {\"x\" : \"Apache Airflow\"},\n dag=dag,\n)\n","sub_path":"dags/rohit.py","file_name":"rohit.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"392365957","text":"\nimport logging\nimport numpy as np\nimport torch\n\nfrom . import network as networks\nfrom .game import import_game\nfrom .search_tree import SearchTree\n\n\ndef create_network(network_type, board_size, num_blocks, base_chans):\n Net = getattr(networks, network_type)\n return Net(board_size=board_size,\n num_blocks=num_blocks,\n base_chans=base_chans)\n\n\nclass Policy:\n def __init__(self, config):\n \"\"\"Construct new policy\"\"\"\n self.gamelib = import_game(config['game'])\n self.device = torch.device(config['device'])\n if self.device.type == 'cuda':\n # enable cudnn auto-tuner\n torch.backends.cudnn.benchmark = True\n\n def initialize(self, config):\n \"\"\"Initialize policy for training\"\"\"\n self.net = create_network(config['network'],\n config['board_size'],\n config['num_blocks'],\n config['base_chans'])\n self.net.to(self.device)\n # don't train anything by default\n self.net.eval()\n # network params\n self.network_type = config['network']\n self.board_size = config['board_size']\n self.num_blocks = config['num_blocks']\n self.base_chans = config['base_chans']\n # search params\n self.simulations = config['simulations']\n self.search_batch_size = config['search_batch_size']\n self.exploration_coef = config['exploration_coef']\n self.exploration_depth = config['exploration_depth']\n self.exploration_noise_alpha = config['exploration_noise_alpha']\n self.exploration_noise_scale = config['exploration_noise_scale']\n self.exploration_temperature = config['exploration_temperature']\n\n @property\n def net(self):\n try:\n return self._net\n except AttributeError:\n raise RuntimeError('Policy must be initialized or loaded before use')\n\n @net.setter\n def net(self, net):\n self._net = net\n\n def reset(self, game):\n \"\"\"Start new game\n :returns: Initial node\n \"\"\"\n self.tree = SearchTree(self.gamelib,\n self.net,\n self.device,\n self.simulations,\n self.search_batch_size,\n self.exploration_coef,\n self.exploration_noise_alpha)\n self.tree.reset(game)\n return self.tree.root\n\n def load_state_dict(self, state):\n \"\"\"Load model state\n \"\"\"\n # load network architecture and params\n self.network_type = state['network_type']\n self.board_size = state['board_size']\n self.num_blocks = state['num_blocks']\n self.base_chans = state['base_chans']\n self.net = create_network(self.network_type,\n self.board_size,\n self.num_blocks,\n self.base_chans)\n self.net.load_state_dict(state['net'])\n self.net.to(self.device)\n\n # load search params\n self.simulations = state['simulations']\n self.search_batch_size = state['search_batch_size']\n self.exploration_coef = state['exploration_coef']\n self.exploration_depth = state['exploration_depth']\n self.exploration_noise_alpha = state['exploration_noise_alpha']\n self.exploration_noise_scale = state['exploration_noise_scale']\n self.exploration_temperature = state['exploration_temperature']\n\n def state_dict(self):\n \"\"\"Return model state\n \"\"\"\n return {\n 'net': self.net.state_dict(),\n 'network_type': self.network_type,\n 'board_size': self.board_size,\n 'num_blocks': self.num_blocks,\n 'base_chans': self.base_chans,\n 'simulations': self.simulations,\n 'search_batch_size': self.search_batch_size,\n 'exploration_coef': self.exploration_coef,\n 'exploration_depth': self.exploration_depth,\n 'exploration_noise_alpha': self.exploration_noise_alpha,\n 'exploration_noise_scale': self.exploration_noise_scale,\n 'exploration_temperature': self.exploration_temperature,\n }\n\n def choose_action(self, game, node, depth,\n temperature=None,\n noise_scale=None):\n \"\"\"Choose next move.\n can raise SearchTreeFull\n :param game: Current game state\n :returns: action - action id,\n node - child node following action,\n probs - 1d array of action probabilities\n \"\"\"\n assert not game.result()\n moves = game.legal_moves()\n if temperature is None:\n temperature = self.exploration_temperature\n if noise_scale is None:\n noise_scale = self.exploration_noise_scale\n if depth >= self.exploration_depth:\n temperature = 0.\n probs, metrics = self.tree.search(game, node, temperature, noise_scale)\n action = np.argmax(np.random.multinomial(1, probs))\n node = self.tree.get_child(node, action, moves)\n assert node\n return action, node, probs, metrics\n\n def make_action(self, game, node, action, moves):\n \"\"\"Update search tree with opponent action.\n can raise SearchTreeFull\n \"\"\"\n node = self.tree.move(game, node, action, moves)\n return node\n\n def tree_stats(self):\n return self.tree.stats()\n\n @classmethod\n def load(cls, config, path):\n \"\"\"Create policy and load weights from checkpoint\n Paths can be local filenames or s3://... URL's (please install\n smart_open library for S3 support).\n Loads tensors according to config['device']\n :param path: Either local or S3 path of policy file\n \"\"\"\n policy = cls(config)\n location = policy.device.type\n if location == 'cuda':\n location += f':{policy.device.index or 0}'\n if path.startswith('s3://'):\n # smart_open is optional dependency\n import smart_open\n with smart_open.smart_open(path) as f:\n state = torch.load(f, map_location=location)\n else:\n state = torch.load(path, map_location=location)\n policy.load_state_dict(state['policy'])\n policy.net.eval()\n return policy\n","sub_path":"azalea/policy.py","file_name":"policy.py","file_ext":"py","file_size_in_byte":6499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"202398515","text":"import random\n\nn = int(input(\"list length = \"))\na = int(input(\"min = \"))\nb = int(input(\"max = \"))\narr = []\narr2 = []\n\nfor i in range(n):\n arr.append(random.randint(a, b))\n\nprint(\"X = \"+str(arr))\n\nfor i in arr:\n if i > 0:\n arr2.append(i)\n arr2.append(0)\n else:\n arr2.append(i)\n\nprint(\"Y = \"+str(arr2))\n","sub_path":"hometask_8/+bonus/314.py","file_name":"314.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"410781000","text":"import requests\nimport json\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom datetime import date\nimport talib\nimport mpl_finance as mpf\nimport seaborn as sns\nimport numpy as np\nimport datetime\nfrom dateutil.relativedelta import relativedelta\nimport csv\nimport time\nplt.rcParams['font.family']='SimHei' # 顯示中文('SimHei' for MacOS)\nfrom sklearn import preprocessing\n\nglobal df1\n\n\ndef RSI(n, index):\n global df1\n mean_up=0\n mean_down=0\n data=df1.loc[index-(n-1):index+1,'漲跌價差']\n for i in data :\n if float(i)>0:\n mean_up+=float(i)\n else:\n mean_down-=float(i)\n mean_up/=n\n mean_down/=n\n if mean_down == 0 :\n return np.nan\n else :\n rs=mean_up/mean_down\n rsi=100*rs/(1+rs)\n return rsi\n\ndef KD(n, index, K_before, D_before):\n global df1\n Mtoday=float(df1.at[index,'收盤價'])\n data=df1.loc[index-(n-1):index+1,'收盤價']\n Max=float(max(data))\n Min=float(min(data))\n RSV=(Mtoday-Min)/(Max-Min) *100\n K=K_before*0.6667+RSV*0.3333\n D=D_before*0.6667+K*0.3333\n return (K, D)\n \ndef BIAS(n, index):\n global df1\n Mtoday=float(df1.at[index,'收盤價'])\n data=np.asarray(df1.loc[index-(n-1):index+1,'收盤價'].astype(float))\n Mean=np.mean(data)\n ans=100*(Mtoday-Mean)/Mean\n return ans\ndef WMR(n, index):\n global df1\n Mtoday=float(df1.at[index,'收盤價'])\n H=np.asarray(df1.loc[index-(n-1):index+1,'最高價'].astype(float))\n L=np.asarray(df1.loc[index-(n-1):index+1,'最低價'].astype(float))\n Hn=np.max(H)\n Ln=np.min(L)\n ans=100*(Hn-Mtoday)/(Hn-Ln)\n return ans\n\ndef EMA(index, N):\n global df1\n S='EMA_'+str(N)\n ans=((float(df1.at[index,'收盤價'])*2)+(N-1)*(float(df1.at[index-1,S])))/(N+1)\n return ans\n\ndef MACD(index, N, dif):\n global df1\n ans=((dif*2)+(N-1)*(float(df1.at[index-1,'MACD'])))/(N+1)\n return ans\n'''\nPSY = 有上漲的天數( N日內 ) / N * 100\n上漲天數係指週期天數( N日 )內,股價上漲的天數和由於其一定在 0 ~ 100之間移動\n故研判PSY的數值當線路介於 20 ~ 80之間移動時為盤整狀態;\n當數值低於10時則可能出現反彈機會,應注意買點的出現;\n數值若高於90以上時,則可能短線過熱,市場心理過於超買,極可能出現回檔的現象。\nPSY的應用\n1. 一般心理線介於25%~75%是合理變動範圍。 \n2. 超過75%或低於25%,就有買超或賣超現象,股價回跌或回升機會增加,此時可準備賣出或買進。\n在大多頭或大空頭市場初期,可將超買、超賣點調整至83%、17%值到行情尾聲,再調回70%、25%。\n3. 當行情出現低於10%或高於90%時;是真正的超賣和超買現象,\n行情反轉的機會相對提高,此時為賣出和買進時機\n'''\ndef psy(index, N):\n global df1\n riseday=0\n for i in range(index-N,index):\n isrise=(float(df1.at[i,'漲跌價差']))\n if (isrise>0):\n riseday+=1\n ans=riseday/N*100\n return ans\n'''\nMTM=C-Cn\n其中:C為當日收市價,Cn為N日前收市價,N為設定參數,一般選設10日,亦可在6日至14日之間選擇。\n(1)一般情況下,MTM由上向下跌破中心線時為賣出時機,相反,MTM由下向上突破中心線時為買進時機。\n(2)因選設10日移動平均線情況下,當MTM在中心線以上,由上向下跌穿平均為賣出訊號,反之,當MTM在中心線以下,由下向上突破平均線為買入訊號。\n(3)股價在上漲行情中創新高點,而MTM未能配合上升,出現背馳現象,意味上漲動力減弱,此時應關註行情,慎防股價反轉下跌。\n(4)股價在下跌行情中走出新低點,而MTM未能配合下降,出現背馳,該情況意味下跌動力減弱,此時應註意逢低承接。\n(5)若股價與MTM在低位同步上升,顯示短期將有反彈行情;若股價與MTM在高位同步下降,則顯示短期可能出現股價回落。\n'''\ndef MTM(index, N):\n global df1\n C=(float(df1.at[index,'收盤價']))\n Cn=(float(df1.at[index-N,'收盤價']))\n return C - Cn\n \n\ndef SAR(index, n_day, AF,SAR_col_name):\n global df1\n\n if index < n_day: # for init\n return 0\n flut_cumu = sum(df1.loc[index-n_day:index-1,'漲跌價差'])\n \n # 算區間極值\n if flut_cumu >= 0: # 上漲\n extrema = float(max(df1.loc[index-n_day:index-1, \"最高價\"]))\n else: # 下跌\n extrema = float(min(df1.loc[index-n_day:index-1, \"最低價\"]))\n \n # 更新 AF值\n if index > n_day+1:\n # 上次是上漲且上漲創新高 或 上次是下跌且下跌創新低\n if (SAR.last_up_down == 0 and flut_cumu < 0 and SAR.last_extrema > extrema) or (SAR.last_up_down == 1 and flut_cumu >= 0 and SAR.last_extrema < extrema):\n AF = 0.2 if AF>=0.2 else AF+0.02 \n \n # 保存漲跌資訊到下一次\n if flut_cumu >= 0: # 上漲\n SAR.last_up_down = 1\n else: # 下跌\n SAR.last_up_down= 0\n \n # 計算 SAR\n if index == n_day: # for init\n SAR.last_extrema = extrema\n return extrema\n else:\n last_SAR = float(df1.loc[index-1, SAR_col_name])\n return last_SAR+AF*(extrema - last_SAR)\n'''\n一. 先計算股票價位的變動值;分別以DM+ 或 DM- 來代表其上漲或下跌的趨向變動值DM:\n\n   DM+ = 本日最高價 - 一日前最高價 ( 上漲的趨向變動值 )\n   DM- = 本日最低價 - 一日前最低價 ( 下跌的趨向變動值 )\n\n二. 無論其DM+ 或DM- 接取其絕對值較大之數值為當日之趨向變動值。由此原則可得此趨向之變動值在於求取每日價格波動幅度之增減的真正幅度。\n\n三. 找出TR,該變動值需比較下列三種差價的『絕對值』後,取其中最大者為本日之TR。\n\n   A = 今日最高價 - 今日最低價\n   B = 今日最高價 - 一日前收盤價\n   C = 今日最低價 - 一日前收盤價\n \n\n四. 計算DI:\n\n   +DI = (DM+) 14日平均 / (TR) 14日平均 *100\n   -DI = (DM-) 14日平均 / (TR) 14日平均 *100\n   求出其14日移動平均值\n   第一日:採用+DI及-DI的14日移動平均值\n   第二日:開始以平滑移動方式修正:\n   本日的(+DI)十日平均 = 一日前(DI+)值 * 13/14 + 本日(+DI) * 1/14\n   本日的(-DI)十日平均 = 一日前(DI-)值 * 13/14 + 本日(-DI) * 1/14\n\n五. ADX計算方式:\n   ADX= [(+DI)- (-DI)] / [(+DI)+(-DI)] *100\n   求出ADX其10日移動平均值\n   第一日:直接採用ADX的14日移動平均值\n   第二日:開始以平滑移動方式修正:\n   ADX= (一日前的ADX * 13/14) + (本日的ADX * 1/14)\n'''\n\ndef DM(index):\n global df1\n if index==0:\n return (0,0)\n DMP = float(df1.at[index, \"最高價\"]) - float(df1.at[index-1, \"最高價\"])\n DMN = float(df1.at[index, \"最低價\"]) - float(df1.at[index-1, \"最低價\"])\n return (DMP, DMN)\n\ndef TR(index):\n global df1\n if index==0:\n return 0\n A = abs(float(df1.at[index, \"最高價\"]) - float(df1.at[index, \"最低價\"]))\n B = abs(float(df1.at[index, \"最高價\"]) - float(df1.at[index-1, \"收盤價\"]))\n C = abs(float(df1.at[index, \"最低價\"]) - float(df1.at[index-1, \"收盤價\"]))\n \n return max([A, B, C])\n\ndef DI(index, n_day):\n global df1\n if index < n_day:\n return (0, 0)\n elif index == n_day:\n PDI = float(sum(df1.loc[index-n_day:index-1, \"DM+(DMI)\"]))/float(sum(df1.loc[index-n_day:index-1, \"TR(DMI)\"]))*100\n NDI = float(sum(df1.loc[index-n_day:index-1, \"DM-(DMI)\"]))/float(sum(df1.loc[index-n_day:index-1, \"TR(DMI)\"]))*100\n \n return (PDI, NDI)\n else:\n PDI = float(sum(df1.loc[index-n_day:index-1, \"DM+(DMI)\"]))/float(sum(df1.loc[index-n_day:index-1, \"TR(DMI)\"]))*100\n NDI = float(sum(df1.loc[index-n_day:index-1, \"DM-(DMI)\"]))/float(sum(df1.loc[index-n_day:index-1, \"TR(DMI)\"]))*100\n \n return (float(df1.loc[index-1, \"+DI(DMI)\"])*(1-1/n_day) + PDI/n_day, float(df1.loc[index-1, \"-DI(DMI)\"])*(1-1/n_day) + NDI/n_day)\n \n \ndef ADX(index, n_day):\n global df1\n # ADX= [(+DI)- (-DI)] / [(+DI)+(-DI)] *100\n \n if index < n_day:\n return 0\n elif index == n_day:\n PDI = float(df1.loc[index, \"+DI(DMI)\"])\n NDI = float(df1.loc[index, \"-DI(DMI)\"])\n ADX = (PDI - NDI) / (PDI + NDI) * 100\n return ADX\n else:\n PDI = float(df1.loc[index, \"+DI(DMI)\"])\n NDI = float(df1.loc[index, \"-DI(DMI)\"])\n ADX = float(df1.loc[index-1, \"ADX(DMI)\"])*(1-1/n_day) + ((PDI - NDI)/(PDI + NDI)*100)/n_day\n \n return ADX\n'''\n1. 先求出昨日行情的CDP值(亦稱均價)\n CDP = (最高價 + 最低價 + 2*收盤價) /4\n \n2. 再分別計算昨天行情得最高值(AH)、近高值(NH)、近低值(NL)及最低值(AL)\n AH = CDP + (最高價 - 最低價)\n NH = 2*CDP - 最低價\n NL = 2*CDP - 最高價\n AL = CDP - (最高價 - 最低價\n \n3. 以最高值(AH)附近開盤應追價買進\n 盤中高於近高值(NH)時可以賣出\n 盤中低於近低值(NL)時可��買進\n 以最低值(AL)附近開盤應追價賣出\n CDP為當天軋平的超短線操作法,務必當天沖銷(利用融資融卷)軋平。若當天盤中無法達到所設定理想的買賣價位時,亦應以當日的收盤價軋平 \n\n'''\n\ndef CDP(index):\n global df1\n ans = (float(df1.at[index-1,'最高價']) + float(df1.at[index-1,'最低價']) + (float(df1.at[index-1,'收盤價'])*2)) / 4\n return ans\n\ndef KDX(index):\n global df1\n ky1 = float(df1.at[index-1,'K'])\n ky2 = float(df1.at[index,'K'])\n dy1 = float(df1.at[index-1,'D'])\n dy2 = float(df1.at[index,'D'])\n \n k1 = ky2 - ky1\n b1 = ky1 - k1\n k2 = dy2 - dy1\n b2 = dy1 - k2\n \n x = (b2 - b1) / (k1 - k2)\n y = (k1*x) + b1\n return y\n \ndef stock_index_generator(df_in,stockcode):\n global df1\n df1 = df_in\n \n for index, row in df1.iteritems():\n indexNames = df1[df1[index] == '--'].index\n df1 = df1.drop(indexNames)\n df1 = df1.reset_index(drop=True)\n df1.sort_index(inplace=True)\n #RSI_6\n N_day=6\n rsi=RSI(N_day,N_day-1)\n df1.loc[N_day-1,'RSI_6']=rsi\n for i in range(N_day,len(df1)):\n rsi=RSI(N_day,i)\n df1.loc[i,'RSI_6']=rsi\n #RSI_12\n N_day=12\n rsi=RSI(N_day,N_day-1)\n df1.loc[N_day-1,'RSI_12']=rsi\n for i in range(N_day,len(df1)):\n rsi=RSI(N_day,i)\n df1.loc[i,'RSI_12']=rsi\n\n for i in range(len(df1)-1):\n dif=float(df1.loc[i+1,'最高價'])-float(df1.loc[i,'最高價'])\n if dif > 0:\n df1.loc[i,'Ans']=1\n else:\n df1.loc[i,'Ans']=-1\n #KD_5\n N_day=5\n K,D=KD(N_day,N_day-1,50,50)\n df1.loc[N_day-1,'K']=K\n df1.loc[N_day-1,'D']=D\n for i in range(N_day,len(df1)):\n K,D=KD(N_day,i,K,D)\n df1.loc[i,'K']=K\n df1.loc[i,'D']=D\n for i in range(12,len(df1)):\n Yesterday=df1.loc[i-1,'RSI_12']-df1.loc[i-1,'RSI_6']\n Today =df1.loc[i,'RSI_12']-df1.loc[i,'RSI_6']\n Product = Yesterday*Today\n if Product < 0 or (abs(Product-0)<0.0001) :\n if Yesterday > 0:\n df1.loc[i,'RSI_DIF']=1\n else :\n df1.loc[i,'RSI_DIF']=-1\n else :\n df1.loc[i,'RSI_DIF']=0\n #BIAS\n\n N_day=6\n bias=BIAS(N_day,N_day-1)\n df1.loc[N_day-1,'BIAS']=bias\n for i in range(N_day,len(df1)):\n bias=BIAS(N_day,i)\n df1.loc[i,'BIAS']=bias\n #WMR\n\n N_day=6\n wmr=WMR(N_day,N_day-1)\n df1.loc[N_day-1,'WMR']=wmr\n for i in range(N_day,len(df1)):\n wmr=WMR(N_day,i)\n df1.loc[i,'WMR']=wmr\n #MACD\n\n df1.loc[0,'EMA_12']=float(df1.at[0,'收盤價'])\n df1.loc[0,'EMA_26']=float(df1.at[0,'收盤價'])\n df1.loc[0,'MACD']=0\n for i in range(1,len(df1)):\n A=EMA(i,12)\n B=EMA(i,26)\n dif=A-B\n macd=MACD(i,14,dif)\n df1.loc[i,'EMA_12']=A\n df1.loc[i,'EMA_26']=B\n df1.loc[i,'MACD']=macd\n #psy心理線\n \n #psy_6\n for i in range(0,6):\n df1.loc[i,'psy_6']=0\n for i in range(6,len(df1)):\n df1.loc[i,'psy_6']=psy(i,6)\n #MTM動量指標\n \n #MTM_6\n for i in range(0,6):\n df1.loc[i,'MTM_6']=0\n for i in range(6,len(df1)):\n df1.loc[i,'MTM_6']=MTM(i,6)\n # SAR 停損點轉向操作系統\n '''\n inti:\n 上升波段:SAR 設定於近期n日中最高價\n 下跌波段:SAR 設定於近期n日中最低價\n\n SAR:\n 當天SAR=前一天SAR+AF*(區間極值–前一天SAR)\n \n AF:\n 則是SAR分析指標的特有產物,叫作加速因子,起始值為0.02,\n 當趨勢正在走上漲(下跌)波段的時候,只要最高(低)價再創新高(低),AF就增加0.02,而最高限制為0.2。\n \n 區間極值:\n 上漲的波段當中,取最高價當作區間極值;相反的,在下跌波段當中,則取最低價當作區間極值。\n '''\n\n AF = 0.02\n n_day=6\n SAR_col_name = 'SAR_%d' % n_day\n\n\n for i in range(0,len(df1)):\n df1.loc[i, SAR_col_name] = SAR(i,n_day,AF,SAR_col_name)\n\n # DMI 趨向指標\n \n\n n_day = 14\n\n\n for i in range(0,len(df1)):\n (df1.loc[i, \"DM+(DMI)\"], df1.loc[i, \"DM-(DMI)\"]) = DM(i)\n df1.loc[i, \"TR(DMI)\"] = TR(i)\n (df1.loc[i, \"+DI(DMI)\"], df1.loc[i, \"-DI(DMI)\"]) = DI(i, n_day)\n df1.loc[i, \"ADX(DMI)\"] = ADX(i, n_day)\n\n #CDP逆勢操作系統\n\n\n df1.loc[0,'CDP']=np.nan\n df1.loc[0,'AH']=np.nan\n df1.loc[0,'NH']=np.nan\n df1.loc[0,'NL']=np.nan\n df1.loc[0,'AL']=np.nan\n\n for i in range(1,len(df1)):\n cdp = CDP(i)\n df1.loc[i,'CDP'] = cdp\n ah = float(df1.at[i,'CDP']) + ( float(df1.at[i-1,'最高價']) - float(df1.at[i-1,'最低價']) )\n nh = ( float(df1.at[i,'CDP']) * 2 ) - float(df1.at[i-1,'最低價'])\n nl = ( float(df1.at[i,'CDP']) * 2 ) - float(df1.at[i-1,'最高價'])\n al = float(df1.at[i,'CDP']) - ( float(df1.at[i-1,'最高價']) - float(df1.at[i-1,'最低價']) )\n\n df1.loc[i,'AH'] = ah\n df1.loc[i,'NH'] = nh\n df1.loc[i,'NL'] = nl\n df1.loc[i,'AL'] = al\n \n st = float(df1.at[i,'開盤價'])\n \n if st >= ah :\n df1.loc[i,'Trend'] = 6\n elif st >= nh :\n df1.loc[i,'Trend'] = 5\n elif st >= cdp :\n df1.loc[i,'Trend'] = 4\n elif st >= nl :\n df1.loc[i,'Trend'] = 3\n elif st >= al :\n df1.loc[i,'Trend'] = 2\n else :\n df1.loc[i,'Trend'] = 1\n \n '''\n 6 = 大漲\n 5 = 漲\n 4 = 偏漲\n 3 = 偏跌\n 2 = 跌\n 1 = 大跌\n '''\n \n N_day=5\n\n for i in range(N_day,len(df1)):\n Yesterday=df1.loc[i-1,'D']-df1.loc[i-1,'K']\n Today =df1.loc[i,'D']-df1.loc[i,'K']\n Product = Yesterday*Today\n\n if Product < 0 or (abs(Product-0)<0.0001) :\n if Yesterday > 0:\n a=1\n else :\n a=-1\n else :\n a=0 \n df1=df1.fillna(0)\n df1=df1.drop(range(14))\n df1=df1.reset_index(drop=True)\n\n df1.to_json('./stock_data_index/' + stockcode + '_index.json')\n return df1\n\n#Normalize\ndef Normalize_pd(df1):\n df2=df1[['RSI_6','RSI_12','K','D','BIAS','WMR','EMA_12','EMA_26','MACD','psy_6','MTM_6','SAR_6','DM+(DMI)','DM-(DMI)','TR(DMI)','+DI(DMI)','-DI(DMI)','ADX(DMI)','Trend']].copy()\n\n def min_max(inputCol,df2):\n arr=np.array( [float(i) for i in df2[inputCol]])\n arr = np.reshape(arr, (-1,1))\n min_max_scaler=preprocessing.MinMaxScaler()\n a=min_max_scaler.fit_transform(arr) \n min_maxdf[inputCol]=np.reshape(a*255, (-1)).tolist()\n\n min_maxdf = pd.DataFrame()\n for i in ['RSI_6','RSI_12','K','D','BIAS','WMR','EMA_12','EMA_26','MACD','psy_6','MTM_6','SAR_6','DM+(DMI)','DM-(DMI)','TR(DMI)','+DI(DMI)','-DI(DMI)','ADX(DMI)','Trend']:\n min_max(i,df2)\n return min_maxdf\n\ndef Normalize_pd_V2(new_idx):\n\n def min_max2(inputCol,new_idx):\n arr=np.array( [float(i) for i in new_idx[inputCol]])\n arr = np.reshape(arr, (-1,1))\n min_max_scaler=preprocessing.MinMaxScaler()\n a=min_max_scaler.fit_transform(arr) \n min_maxdf2[inputCol]=np.reshape(a*255, (-1)).tolist()\n min_maxdf2 = pd.DataFrame()\n for i in ['RSI','KD','BIAS','WMR','MACD','PSY','SAR','CDP','+DI(DMI)','-DI(DMI)','ADX(DMI)']:\n min_max2(i,new_idx)\n return min_maxdf2\n\n\ndef stock_index_generator_V2(df_in,stockcode):\n df2=df_in[['RSI_6','RSI_12','K','D','BIAS','WMR','EMA_12','EMA_26','MACD','psy_6','MTM_6','SAR_6','DM+(DMI)','DM-(DMI)','TR(DMI)','+DI(DMI)','-DI(DMI)','ADX(DMI)','Trend']].copy()\n new_idx=pd.DataFrame()\n #rsi\n rsi6=np.array([float(i) for i in df2['RSI_6']])\n rsi12=np.array([float(i) for i in df2['RSI_12']])\n rst=np.array(0)\n for i in range(1,rsi6.size):\n tmp=0\n if(rsi6[i]>90):\n tmp=-1\n elif(rsi6[i]>80):\n tmp=-0.5\n elif(rsi6[i]<10):\n tmp=1\n elif(rsi6[i]<20):\n tmp=0.5\n dif=rsi6[i]-rsi12[i]\n mul=(rsi6[i-1]-rsi12[i-1])*dif\n if (abs(mul-0) < 0.0000001) or (mul < 0):\n if (dif > 0) or ((abs(dif-0) < 0.0000001) and rsi6[i-1] < rsi12[i-1]):\n tmp=tmp+2\n else:\n tmp=tmp-2\n rst=np.append(rst,tmp)\n new_idx['RSI']=np.reshape(rst, (-1)).tolist()\n #KD\n k=np.array([float(i) for i in df2['K']])\n d=np.array([float(i) for i in df2['D']])\n rst=np.array(0)\n for i in range(1,k.size):\n dif=k[i]-d[i]\n mul=dif*(k[i-1]*d[i-1])\n tmp=0\n if (abs(mul-0) < 0.0000001) or (mul < 0):\n if (dif > 0) or ((abs(dif-0) < 0.0000001) and k[i-1] < d[i-1]):\n tmp=1\n else:\n tmp=-1\n w=0\n if k[i]>80 or k[i]<20 :\n w=2\n elif k[i]>70 or k[i]<30 :\n w=1\n rst=np.append(rst,w*tmp)\n new_idx['KD']=np.reshape(rst, (-1)).tolist()\n #BIAS\n bias=np.array([float(i) for i in df2['BIAS']])\n if(bias[0]<-4.5):\n rst=np.array(2)\n elif(bias[0]<-3):\n rst=np.array(1)\n elif(bias[0]>5):\n rst=np.array(-2)\n elif(bias[0]>3.5):\n rst=np.array(-1)\n else:\n rst=np.array(0)\n for i in range(1,bias.size):\n if(bias[i]<-4.5):\n rst=np.append(rst,2)\n elif(bias[i]<-3):\n rst=np.append(rst,1)\n elif(bias[i]>5):\n rst=np.append(rst,-2)\n elif(bias[i]>3.5):\n rst=np.append(rst,-1)\n else:\n rst=np.append(rst,0)\n new_idx['BIAS']=np.reshape(rst, (-1)).tolist()\n #WMR\n wr=np.array([float(i) for i in df2['WMR']])\n if(wr[0]<=20):\n rst=np.array(-2)\n elif(wr[0]<35):\n rst=np.array(-1)\n elif(wr[0]<65):\n rst=np.array(0)\n elif(wr[0]<80):\n rst=np.array(1)\n else:\n rst=np.array(2)\n for i in range(1,wr.size):\n if(wr[i]<=20):\n rst=np.append(rst,-2)\n elif(wr[i]<35):\n rst=np.append(rst,-1)\n elif(wr[i]<65):\n rst=np.append(rst,0)\n elif(wr[i]<80):\n rst=np.append(rst,1)\n else:\n rst=np.append(rst,2)\n new_idx['WMR']=np.reshape(rst, (-1)).tolist()\n #MACD\n macd=np.array([float(i) for i in df2['MACD']])\n dif=np.array([float(i) for i in df2['EMA_12']])-np.array([float(i) for i in df2['EMA_26']])\n if macd[0]>0 and dif[0]>0:\n rst=np.array(2)\n elif dif[0]>0:\n rst=np.array(1)\n elif macd[0]>0:\n rst=np.array(-1)\n else:\n rst=np.array(-2)\n for i in range(1,macd.size):\n if macd[i]>0 and dif[i]>0:\n rst=np.append(rst,2)\n elif dif[i]>0:\n rst=np.append(rst,1)\n elif macd[i]>0:\n rst=np.append(rst,-1)\n else:\n rst=np.append(rst,-2)\n new_idx['MACD']=np.reshape(rst, (-1)).tolist()\n #PSY\n new_idx['PSY']=df2['psy_6'].copy()\n #SAR\n sar=np.array([float(i) for i in df2['SAR_6']])\n dif=k-sar\n rst=np.array(0)\n for i in range(1,k.size):\n mul=dif[i]*dif[i-1]\n tmp=0\n if (abs(mul-0) < 0.0000001) or (mul < 0):\n if (dif[i] > 0) or ((abs(dif[i]-0) < 0.0000001) and dif[i-1]<0):\n tmp=1\n else:\n tmp=-1\n rst=np.append(rst,tmp)\n new_idx['SAR']=np.reshape(rst, (-1)).tolist()\n #CDP\n new_idx['CDP']=df2['Trend'].copy()\n #DMI\n l=['+DI(DMI)','-DI(DMI)','ADX(DMI)']\n for i in l:\n new_idx[i]=df2[i].copy()\n pd.set_option('display.max_rows', 1000)\n pd.set_option('display.max_columns', 1000)\n new_idx.to_json('./stock_data_index_V2/' + stockcode + '_index_V2.json')\n\n return new_idx\n\n\n\nif __name__ == \"__main__\":\n stockcode='0050'\n PATH_input_json = './stock_data/'+stockcode+'.json'\n df=stock_index_generator(pd.read_json(PATH_input_json),stockcode)\n print(df)\n min_maxdf=Normalize_pd(df)\n print(min_maxdf)\n\n df_v2 = stock_index_generator_V2(df,stockcode)\n print(df_v2)\n min_maxdfV2 = Normalize_pd_V2(df_v2)\n print(min_maxdfV2)\n\n pass\n\n\n","sub_path":"Model/lstm_w/index_generate.py","file_name":"index_generate.py","file_ext":"py","file_size_in_byte":21368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"544504190","text":"# 5번_B735042_김대겸\r\n\r\n# main()함수 선언.\r\ndef main():\r\n inputString = input(\"정수 리스트 입력: \")\r\n # inputString을 list1으로 변환한다\r\n list1 = list(map(int, inputString.split()))\r\n print(\"평균=\", getMean(list1))\r\n print(\"표준 편차\", getDeviation(list1))\r\n\r\n# getMean()함수 선언.(평균과 구하고 그 값을 반환하는 함수)\r\ndef getMean(lst):\r\n lst_total = 0\r\n for i in lst:\r\n lst_total += i\r\n lst_average = (lst_total / len(lst))\r\n return lst_average\r\n\r\n# getDeviation()함수 선언.(표준편차를 구하고 그 값을 반환하는 함수)\r\ndef getDeviation(lst): \r\n ave = getMean(lst)\r\n cha_total = 0\r\n for i in lst:\r\n cha_total += ((i - ave)**2)\r\n devi = ((cha_total / (len(lst)))**(1/2))\r\n return devi\r\n\r\n# main()함수 호출.\r\nmain()\r\n","sub_path":"김대겸 (5).py","file_name":"김대겸 (5).py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"612878436","text":"import cv2\r\nimport numpy as np\r\n\r\ndef main():\r\n \r\n windowname=\"live video\"\r\n \r\n cv2.namedWindow(windowname)\r\n \r\n cap=cv2.VideoCapture(0)\r\n \r\n if cap.isOpened():\r\n ret, frame=cap.read()\r\n else:\r\n ret = False\r\n \r\n while ret:\r\n \r\n ret, frame=cap.read()\r\n \r\n hsv=cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)\r\n \r\n low = np.array([100,50,50])\r\n high= np.array([140,255,255])\r\n \r\n image_mask=cv2.inRange(hsv, low, high)\r\n \r\n output=cv2.bitwise_and(frame,frame,mask=image_mask)\r\n cv2.imshow(windowname,output)\r\n \r\n if cv2.waitKey(1)== 27:\r\n break\r\n \r\n print(image_mask) \r\n cv2.destroyWindow(windowname)\r\n cap.release()\r\n\r\nif __name__==\"__main__\":\r\n main() ","sub_path":"color.py","file_name":"color.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"492278814","text":"#!/usr/bin/env python\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom astropy.io import fits\nfrom .get_ephem import get_ephemerides, naif_lookup\nfrom nirc2_reduce.image import Image\nfrom nirc2_reduce.phot import nearest_stand_filt\nfrom datetime import datetime, timedelta\nimport warnings\nfrom skimage import feature\nfrom image_registration.chi2_shifts import chi2_shift\nfrom image_registration.fft_tools.shift import shiftnd, shift2d\nfrom scipy.interpolate import interp2d, RectBivariateSpline, NearestNDInterpolator, griddata\n#from .fit_gaussian import fitgaussian\nfrom astropy.modeling import models, fitting\nfrom scipy.ndimage.measurements import center_of_mass\nfrom scipy.ndimage.interpolation import zoom\n\n#from mpl_toolkits import basemap\nimport pyproj\n\n\ndef lat_lon(x,y,ob_lon,ob_lat,pixscale_km,np_ang,req,rpol):\n '''Find latitude and longitude on planet given x,y pixel locations and\n planet equatorial and polar radius'''\n np_ang = -np_ang\n x1 = pixscale_km*(np.cos(np.radians(np_ang))*x - np.sin(np.radians(np_ang))*y)\n y1 = pixscale_km*(np.sin(np.radians(np_ang))*x + np.cos(np.radians(np_ang))*y)\n olrad = np.radians(ob_lat)\n \n #set up quadratic equation for ellipsoid\n r2 = (req/rpol)**2\n a = 1 + r2*(np.tan(olrad))**2 #second order\n b = 2*y1*r2*np.sin(olrad) / (np.cos(olrad)**2) #first order\n c = x1**2 + r2*y1**2 / (np.cos(olrad))**2 - req**2 #constant\n\n radical = b**2 - 4*a*c\n #will equal nan outside planet since radical < 0\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\") #suppresses error for taking sqrt nan\n x3s1=(-b+np.sqrt(radical))/(2*a)\n x3s2=(-b-np.sqrt(radical))/(2*a)\n z3s1=(y1+x3s1*np.sin(olrad))/np.cos(olrad)\n z3s2=(y1+x3s2*np.sin(olrad))/np.cos(olrad)\n odotr1=x3s1*np.cos(olrad)+z3s1*np.sin(olrad)\n odotr2=x3s2*np.cos(olrad)+z3s2*np.sin(olrad)\n #the two solutions are front and rear intersections with planet\n #only want front intersection\n \n #tricky way of putting all the positive solutions into one array\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\") #suppresses error for taking < nan\n odotr2[odotr2 < 0] = np.nan\n x3s2[odotr2 < 0] = np.nan\n z3s2[odotr2 < 0] = np.nan\n odotr1[odotr1 < 0] = odotr2[odotr1 < 0]\n x3s1[odotr1 < 0] = x3s2[odotr1 < 0]\n z3s1[odotr1 < 0] = z3s2[odotr1 < 0]\n \n odotr,x3,z3 = odotr1,x3s1,z3s1\n y3 = x1\n r = np.sqrt(x3**2 + y3**2 + z3**2)\n \n #lon_w = np.degrees(np.arctan(y3/x3)) + ob_lon\n lon_w = np.degrees(np.arctan2(x3,y3)-np.pi/2) + ob_lon \n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\") #suppresses error for taking < nan\n lon_w[lon_w < 0] += 360\n lon_w = lon_w%360\n lat_c = np.degrees(np.arcsin(z3/r))\n lat_g = np.degrees(np.arctan(r2*np.tan(np.radians(lat_c))))\n #plt.imshow(lon_w, origin = 'lower left')\n #plt.show()\n return lat_g, lat_c, lon_w\n\ndef surface_normal(lat_g, lon_w, ob_lon):\n '''Returns the normal vector to the surface of the planet.\n Take dot product with sub-obs or sub-sun vector to find cosine of emission angle'''\n nx = np.cos(np.radians(lat_g))*np.cos(np.radians(lon_w-ob_lon))\n ny = np.cos(np.radians(lat_g))*np.sin(np.radians(lon_w-ob_lon))\n nz = np.sin(np.radians(lat_g))\n return np.asarray([nx,ny,nz])\n\ndef emission_angle(ob_lat, surf_n):\n '''Return the cosine of the emission angle of surface wrt observer'''\n ob = np.asarray([np.cos(np.radians(ob_lat)),0,np.sin(np.radians(ob_lat))])\n return np.dot(surf_n.T, ob).T\n \n#def sun_angle(ob_lon, ob_lat, sun_lon, sun_lat):\n# return\n \ndef get_filt_info(filt):\n '''Helper to I/F. Will find flux of sun in given filter'''\n with open('/Users/emolter/Python/nirc2_reduce/filter_passbands/sun_fluxes.txt','r') as f:\n f.readline() #header\n for line in f:\n l = line.split(',')\n fl = l[0].strip(', \\n')\n if fl == filt:\n wl = float(l[1].strip(', \\n'))\n sun_mag = float(l[2].strip(', \\n'))\n return wl, sun_mag\n \ndef find_airmass(observatory, time, object):\n '''Use the power of astropy to retrieve airmass of standard\n star automatically... obvs not done yet'''\n return\n \ndef airmass_correction(air_t, air_c, filt):\n '''Helper to I/F. Computes correction factor to photometry based on airmass.\n Multiply \n air_t is airmass of science target.\n air_c is airmass of calibrator.\n filt options are j, h, k, l, m. Use nearest one for narrowband filters'''\n cdict = {'j': 0.102,\n 'h': 0.059,\n 'k': 0.088,\n 'l': 0.093,\n 'm': 0.220} #from https://www2.keck.hawaii.edu/realpublic/inst/nirc/exts.html\n if filt == None:\n return 1.0\n tau = cdict[filt]\n factor = np.exp(tau*air_t)/np.exp(tau*air_c)\n return factor\n\nclass CoordGrid:\n \n def __init__(self, infile, lead_string = None, req = 24764, rpol = 24341, scope = 'keck'):\n '''Pull ephemeris data, calculate lat and lon. Pixscale in arcsec, req and rpol in km'''\n \n self.im = Image(infile)\n self.req = req\n self.rpol = rpol\n scope = str.lower(scope)\n\n if scope == 'keck':\n pixscale = 0.009942\n elif scope == 'lick':\n pixscale = 0.033\n elif scope == 'alma':\n pixscale = np.abs(self.im.header['CDELT1']) * 3600 #deg to arcsec\n elif scope == 'hst':\n pixscale = np.abs(self.im.header['PIXSCAL'])\n else:\n pixscale = 0.0\n self.pixscale_arcsec = pixscale\n if scope == 'vla' or scope == 'alma':\n self.data = self.im.data[0,0,:,:]\n else:\n self.data = self.im.data\n \n #pull and reformat header info\n if not scope == 'hst_wfc3':\n targ = self.im.header['OBJECT'].split('_')[0]\n targ = targ.split(' ')[0]\n self.target = targ\n else:\n targ = 'Neptune'\n self.target = 'Neptune'\n if scope == 'vla' or scope == 'alma':\n date = self.im.header['DATE-OBS']\n expstart = date.split('T')[1]\n date = date.split('T')[0]\n elif scope == 'hst':\n date = self.im.header['DATE-OBS']\n expstart = self.im.header['TIME-OBS']\n elif scope == 'keck':\n expstart = self.im.header['EXPSTART']\n date = self.im.header['DATE-OBS']\n imsize_x = self.data.shape[0]\n imsize_y = self.data.shape[1]\n if scope == 'lick':\n tstart = datetime.strptime(self.im.header['DATE-BEG'][:-7],'%Y-%m-%dT%H:%M')\n else:\n tstart = datetime.strptime(date+' '+expstart[:5],'%Y-%m-%d %H:%M')\n tend = tstart + timedelta(minutes=1)\n tstart = datetime.strftime(tstart, '%Y-%m-%d %H:%M')\n tend = datetime.strftime(tend, '%Y-%m-%d %H:%M')\n self.date_time = tstart\n \n #pull ephemeris data\n naif = naif_lookup(targ)\n if scope == 'keck':\n obscode = 568\n elif scope == 'vla':\n obscode = -5\n elif scope == 'lick':\n obscode = 662\n elif scope == 'alma':\n obscode = -7\n elif scope == 'hst_wfc3' or scope == 'hst_opal' or scope == 'hst_wfc2':\n obscode = '500@-48'\n else:\n obscode = input('Enter Horizons observatory code: ')\n \n ## check ephem inputs\n #print(naif) \n #print(obscode)\n #print(tstart)\n #print(tend)\n \n ephem = get_ephemerides(naif, obscode, tstart, tend, '1 minutes')[0][0] #just the row for start time\n ephem = [val.strip(' ') for val in ephem]\n time = ephem[0]\n ra, dec = ephem[3], ephem[4]\n dra, ddec = float(ephem[5]), float(ephem[6])\n if not scope == 'hst_wfc3':\n az, el = float(ephem[7]), float(ephem[8])\n self.airmass, extinction = float(ephem[9]), float(ephem[10])\n apmag, sbrt = float(ephem[11]), float(ephem[12])\n self.ang_diam = float(ephem[15])\n self.ob_lon, self.ob_lat = float(ephem[16]), float(ephem[17])\n self.sun_lon, self.sun_lat = float(ephem[18]), float(ephem[19])\n #self.sun_ang = sun_angle(ob_lon, ob_lat, sun_lon, sun_lat)\n self.np_ang, self.np_dist = float(ephem[20]), float(ephem[21])\n self.sun_dist = float(ephem[22])*1.496e8 #from AU to km\n self.dist = float(ephem[24])*1.496e8 #from AU to km \n \n self.pixscale_km = self.dist*np.radians(pixscale/3600)\n avg_circumference = 2*np.pi*((req + rpol)/2.0)\n self.deg_per_px = self.pixscale_km * (1/avg_circumference) * 360 #approximate conversion between degrees and pixels at sub-observer point\n \n if lead_string != None:\n #if you already did the edge detection and centering and are loading centered image\n self.centered = self.im.data\n self.lat_g = Image(lead_string+'_latg.fits').data\n self.lon_w = Image(lead_string+'_lonw.fits').data\n self.model_planet = np.nan_to_num(self.lat_g * 0.0 + 1.0)\n try:\n self.err_x = Image(lead_string+'_errx.fits').data\n self.err_y = Image(lead_string+'_erry.fits').data\n except:\n pass\n try:\n self.projected = Image(lead_string+'_proj.fits').data\n except:\n pass\n try:\n self.mu = Image(lead_string+'_mu.fits').data\n except:\n self.surf_n = surface_normal(self.lat_g, self.lon_w, self.ob_lon)\n self.mu = emission_angle(self.ob_lat, self.surf_n)\n try:\n self.mu_projected = Image(lead_string+'_mu_proj.fits').data\n except:\n pass\n \n else:\n xcen, ycen = int(imsize_x/2), int(imsize_y/2) #pixels at center of planet\n xx = np.arange(imsize_x) - xcen\n yy = np.arange(imsize_y) - ycen\n x,y = np.meshgrid(xx,yy)\n self.lat_g, self.lat_c, self.lon_w = lat_lon(x,y,self.ob_lon,self.ob_lat,self.pixscale_km,self.np_ang,req,rpol)\n self.surf_n = surface_normal(self.lat_g, self.lon_w, self.ob_lon)\n self.mu = emission_angle(self.ob_lat, self.surf_n)\n\n def ioverf(self, filt, flux_per, stand_airmass):\n '''Compute I/F ratio given an image in cts s-1 and a conversion between\n cts s-1 and erg s-1 cm-2 um-1 sr-1'''\n wl, sun_flux_earth = get_filt_info(filt)\n sun_flux = sun_flux_earth * (1/np.pi)*(1.496e8/self.sun_dist)**2 #factor of pi because F = pi*B\n sr_per_px = np.radians(self.pixscale_arcsec/3600)**2\n sun_flux_density = sun_flux * sr_per_px # from erg s-1 cm-2 um-1 sr-1 to erg s-1 cm-2 um-1 px-1\n print('Sun flux density ', sun_flux_density)\n \n #photometry correction\n airmass_filt = nearest_stand_filt[filt]\n air_corr = airmass_correction(self.airmass, stand_airmass, airmass_filt)\n print('Airmass correction ',air_corr)\n self.data = self.data * flux_per * air_corr / sun_flux_density\n if hasattr(self, 'centered'):\n self.centered = self.centered * flux_per * air_corr / sun_flux_density\n \n #def minnaert(self, k):\n # '''Applies Minnaert correction to remove effects of limb darkening\n # k is an empirically determined constant between 0 and 1, 0.7 for Io'''\n # self.data = self.data * self.sun_ang**k * self.mu**(k - 1)\n # if hasattr(self, 'centered'):\n # self.centered = self.centered * mu0**k * self.mu**(k - 1)\n \n def write_photonly(self, outstr):\n '''If you want to just run ioverf and then write'''\n hdulist_out = self.im.hdulist\n #centered data\n hdulist_out[0].header['OBJECT'] = self.target+'_calibrated'\n hdulist_out[0].data = self.data\n hdulist_out[0].writeto(outstr, overwrite=True)\n\n def edge_detect(self, low_thresh = 0.01, high_thresh = 0.05, sigma = 5, plot = True):\n '''Uses skimage canny algorithm to find edges of planet, correlates\n that with edges of model, '''\n \n self.model_planet = np.nan_to_num(self.lat_g * 0.0 + 1.0)\n edges = feature.canny(self.data/np.max(self.data), sigma=sigma, low_threshold = low_thresh, high_threshold = high_thresh)\n model_edges = feature.canny(self.model_planet, sigma=sigma, low_threshold = low_thresh, high_threshold = high_thresh)\n \n [dx,dy,dxerr,dyerr] = chi2_shift(model_edges,edges)\n self.x_shift = -dx #need if we want to shift another filter the same amount\n self.y_shift = -dy\n print('Pixel shift X, Y = ', self.x_shift, self.y_shift)\n \n #error in position on surface is approximately equal to projected error times emission angle - in reality there is some asymmetry that would be important if error bars are large\n #These are lat/lon error in the x-hat and y-hat directions; their magnitude is correct for lat-lon space but their direction is not\n self.err_x = dxerr/(self.deg_per_px*self.mu)\n self.err_y = dyerr/(self.deg_per_px*self.mu)\n print(' Lat/Lon error at sub-obs point in x-hat direction = '+str(dxerr/self.deg_per_px))\n print(' Lat/Lon error at sub-obs point in y-hat direction = '+str(dyerr/self.deg_per_px)) \n \n self.centered = shift2d(self.data,-1*dx,-1*dy)\n self.edges = shift2d(edges,-1*dx,-1*dy)\n\n if plot:\n fig, (ax0, ax1, ax2) = plt.subplots(1, 3, figsize=(10, 5))\n \n ax0.imshow(self.data, origin = 'lower left')\n ax0.set_title('Image')\n \n ax1.imshow(edges, origin = 'lower left')\n ax1.set_title('Canny filter, $\\sigma=$%d'%sigma)\n \n ax2.imshow(self.edges, origin = 'lower left', alpha = 0.5)\n ax2.imshow(model_edges, origin = 'lower left', alpha = 0.5)\n ax2.set_title('Overlay model and data')\n \n plt.show()\n \n \n def edge_detect_error(self, niter, perturb_l, perturb_dist, low_thresh = 0.002, dist = 0.02, sigma = 5, doplot = True):\n '''Perturbs parameters of Canny algorithm to produce a variety of \n edge detection solutions. Finds most probable one, and takes \n standard deviation of those to produce an error\n perturb_l, perturb_dist Factor by which low_thresh and distance between low and high threshold are changed. must be >= 1\n sigmavals List of sigma values to use. Usually some subset of [3,5,7]\n niter Number of iterations for each low, high threshold value'''\n \n #set up the model planet\n self.model_planet = np.nan_to_num(self.lat_g * 0.0 + 1.0)\n model_edges = feature.canny(self.model_planet, sigma=sigma, low_threshold = low_thresh, high_threshold = low_thresh + dist)\n\n if doplot:\n inp = False\n while not inp:\n \n #set up arrays of values\n l_vals = np.arange(low_thresh/perturb_l, low_thresh*perturb_l, (low_thresh*perturb_l - low_thresh/perturb_l)/niter)\n dist_vals = np.arange(dist/perturb_dist, dist*perturb_dist, (dist*perturb_dist - dist/perturb_dist)/niter)\n \n #check that lowest, middle, and highest params give you what is expected\n l_bounds = [l_vals[0], low_thresh, l_vals[-1]]\n d_bounds = [dist_vals[0], dist, dist_vals[-1]]\n fig, axes = plt.subplots(3, 3, figsize=(8, 12), sharex = True, sharey = True)\n \n for i in range(3):\n #do the edges \n l = l_bounds[i]\n d = d_bounds[i]\n edges = feature.canny(self.data/np.max(self.data), sigma=sigma, low_threshold = l, high_threshold = l + d)\n [dx,dy,dxerr,dyerr] = chi2_shift(model_edges,edges)\n shift_edges = shift2d(edges,-1*dx,-1*dy)\n \n #plot things\n axarr = axes[i]\n axarr[0].imshow(self.data, origin = 'lower left')\n axarr[1].imshow(edges, origin = 'lower left')\n axarr[2].imshow(shift_edges, origin = 'lower left', alpha = 0.5)\n axarr[2].imshow(model_edges, origin = 'lower left', alpha = 0.5) \n \n #cosmetics\n if i == 0:\n axarr[0].set_title('Image')\n axarr[1].set_title('Edges, $\\sigma=$%d'%sigma)\n axarr[2].set_title('Overlay model and data')\n \n for ax in axarr:\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n ax.set_ylim([0, edges.shape[1]])\n ax.set_xlim([0, edges.shape[0]])\n \n axarr[0].set_ylabel('l = '+str(l)[:6]+', d = '+str(d)[:6])\n \n plt.subplots_adjust(wspace = 0, hspace = 0)\n plt.show() \n \n yn = input('Are you okay with these? (y/n): ')\n if yn.lower().strip() == 'y' or yn.lower().strip() == 'yes':\n inp = True\n else:\n low_thresh = float(input('New value of low_thresh: '))\n dist = float(input('New value of dist: '))\n perturb_l = float(input('New value of perturb_l: '))\n perturb_dist = float(input('New value of perturb_dist: '))\n else:\n l_vals = np.arange(low_thresh/perturb_l, low_thresh*perturb_l, (low_thresh*perturb_l - low_thresh/perturb_l)/niter)\n dist_vals = np.arange(dist/perturb_dist, dist*perturb_dist, (dist*perturb_dist - dist/perturb_dist)/niter)\n \n #now iterate over the parameter space and determine x,y for each\n dx_vals, dy_vals = [], []\n dxerr_vals , dyerr_vals = [], []\n for lt in l_vals:\n for d in dist_vals:\n ht = lt + d\n edges = feature.canny(self.data/np.max(self.data), sigma=sigma, low_threshold = lt, high_threshold = ht)\n [dx,dy,dxerr,dyerr] = chi2_shift(model_edges,edges)\n dx_vals.append(dx)\n dy_vals.append(dy)\n dxerr_vals.append(dxerr)\n dyerr_vals.append(dyerr)\n #print(d, dx, dy)\n plotevery = False\n if plotevery:\n fig, (ax0, ax1, ax2) = plt.subplots(1, 3, figsize=(10, 5))\n \n ax0.imshow(self.data, origin = 'lower left')\n ax0.set_title('Image')\n \n ax1.imshow(edges, origin = 'lower left')\n ax1.set_title('Canny filter, $\\sigma=$%d'%sigma)\n \n ax2.imshow(shift2d(edges,-1*dx,-1*dy), origin = 'lower left', alpha = 0.5)\n ax2.imshow(model_edges, origin = 'lower left', alpha = 0.5)\n ax2.set_title('Overlay model and data') \n \n plt.show() \n dx_vals = np.asarray(dx_vals)\n dy_vals = np.asarray(dy_vals)\n dxerr_vals = np.asarray(dxerr_vals)\n dyerr_vals = np.asarray(dyerr_vals)\n print('Best X, Y = ', np.mean(dx_vals), np.mean(dy_vals))\n print('Sigma X, Y = ', np.std(dx_vals), np.std(dy_vals))\n print('Typical shift error X, Y = ', np.mean(dxerr_vals), np.mean(dyerr_vals))\n print('Spread in shift error X, Y = ', np.std(dxerr_vals), np.std(dyerr_vals))\n print('Total error X, Y = ', np.sqrt(np.std(dx_vals)**2 + np.mean(dxerr_vals)**2), np.sqrt(np.std(dy_vals)**2 + np.mean(dyerr_vals)**2))\n \n if doplot:\n #histogram of the samples\n fig, (ax0, ax1) = plt.subplots(2,1, figsize = (6,8))\n \n ax0.hist(dx_vals, bins = niter)\n ax1.hist(dy_vals, bins = niter)\n \n ax0.set_xlabel('Shift in X')\n ax0.set_ylabel('Number')\n ax1.set_xlabel('Shift in Y')\n ax1.set_ylabel('Number')\n plt.show()\n \n \n def manual_shift(self,dx,dy):\n self.centered = shift2d(self.data,dx,dy)\n \n def plot_latlon(self):\n '''Make pretty plot of lat_g and lon_w overlaid on planet'''\n fig, (ax0, ax1) = plt.subplots(1,2, figsize = (12,6))\n \n #little circle around planet - now does not depend on self.edges existing\n planetedge = np.copy(self.lat_g)\n nans = np.isnan(planetedge)\n planetedge[np.invert(nans)] = 100\n planetedge[nans] = 0\n \n #latitudes\n ax0.imshow(self.centered, origin = 'lower left')\n levels_lat = np.arange(-90,105,15)\n label_levels_lat = np.arange(-90,60,30)\n ctr_lat = ax0.contour(self.lat_g, levels_lat, colors='white', linewidths=2)\n ax0.clabel(ctr_lat, label_levels_lat, inline=1, inline_spacing = 2, fontsize=16, fmt='%d')\n ax0.contour(planetedge, colors = 'white', linewidths = 1)\n #ax0.set_title('Latitudes', fontsize = 18)\n ax0.get_xaxis().set_ticks([])\n ax0.axes.get_yaxis().set_ticks([])\n \n #longitudes\n ax1.imshow(self.centered, origin = 'lower left')\n #hack here to avoid discontinuity in contours - split longs in half\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\") #suppresses error for taking < nan\n lon_w1 = np.copy(self.lon_w)\n lon_w1[lon_w1 >= 180] = np.nan\n lon_w2 = np.copy(self.lon_w)\n lon_w2[lon_w2 < 180] = np.nan\n \n levels_lon = range(0,360,30)\n levels_lon_hack = [1] + list(levels_lon[1:]) #make contour at zero actually 1 - otherwise won't plot it since it's at the edge\n ctr_lon1 = ax1.contour(lon_w1, levels_lon_hack, colors='white', linewidths=2)\n ctr_lon2 = ax1.contour(lon_w2, levels_lon_hack, colors='white', linewidths=2)\n \n fmt = {}\n vals = np.arange(0,360,30)\n for l, v in zip(levels_lon_hack, vals):\n fmt[l] = str(int(v)) #make it so the labels say the right things despite hack\n ax1.clabel(ctr_lon1, levels_lon_hack, fmt = fmt, inline=1, inline_spacing = 2, fontsize=16)\n ax1.clabel(ctr_lon2, levels_lon_hack, fmt = fmt, inline=1, inline_spacing = 2, fontsize=16)\n ax1.contour(planetedge, colors = 'white', linewidths = 1)\n #ax1.set_title('Longitudes', fontsize = 18)\n ax1.get_xaxis().set_ticks([])\n ax1.axes.get_yaxis().set_ticks([]) \n \n plt.tight_layout()\n plt.savefig('lat_lon_overlay.png')\n plt.show()\n \n def write(self, lead_string):\n '''Tertiary data products'''\n hdulist_out = self.im.hdulist\n #centered data\n hdulist_out[0].header['OBJECT'] = self.target+'_CENTERED'\n hdulist_out[0].data = self.centered\n hdulist_out[0].writeto(lead_string + '_centered.fits', overwrite=True)\n #latitudes\n hdulist_out[0].header['OBJECT'] = self.target+'_LATITUDES'\n hdulist_out[0].data = self.lat_g\n hdulist_out[0].writeto(lead_string + '_latg.fits', overwrite=True)\n #longitudes\n hdulist_out[0].header['OBJECT'] = self.target+'_LONGITUDES'\n hdulist_out[0].data = self.lon_w\n hdulist_out[0].writeto(lead_string + '_lonw.fits', overwrite=True)\n #errors only exist if edge_detect was run. if manual shift, just ignore\n try:\n #error in x*mu\n hdulist_out[0].header['OBJECT'] = self.target+'_XERR'\n hdulist_out[0].data = self.err_x\n hdulist_out[0].writeto(lead_string + '_errx.fits', overwrite=True)\n #error in y*mu\n hdulist_out[0].header['OBJECT'] = self.target+'_YERR'\n hdulist_out[0].data = self.err_y\n hdulist_out[0].writeto(lead_string + '_erry.fits', overwrite=True)\n except:\n pass\n\n def bootstrap_func(self, order = 2):\n '''Takes a navigated image, plots flux as function of emission angle,\n fits (to nth order) to the minimum flux vs emission angle curve.\n returns the fit coefficients to IoverF(mu)'''\n \n onplanet = np.copy(self.centered)\n onplanet *= self.model_planet\n \n vals = onplanet.flatten()\n mus = self.mu.flatten()\n \n vals_2 = vals[vals > 0] #remove zeros on outside of image\n mus_2 = mus[vals > 0]\n \n np.savetxt('flux_vs_mu.txt', np.asarray([mus_2, vals_2]))\n \n '''It looks like the minimum value at each emission angle follows a fairly\n regular distribution. Try to make a function fit the bottom of it.'''\n bins = np.arange(0,1.01,0.01)\n x = np.digitize(mus_2, bins)\n mins = [np.min(vals_2[np.where(x == i)]) if len(vals_2[np.where(x == i)]) > 0 else 0.0 for i in range(bins.shape[0])]\n mins = np.asarray(mins)\n bins = bins[np.where(mins > 0)]\n mins = mins[np.where(mins > 0)]\n \n z = np.polyfit(bins,mins, order)\n func = np.poly1d(z)\n \n plt.semilogy(mus_2, vals_2, linestyle = '', marker = '.', color = 'k', markersize = 1)\n plt.semilogy(bins, func(bins), color = 'r')\n #plt.semilogy(bins, z[0]*bins**2 + z[1]*bins*1.1 + z[2])\n plt.xlabel(r'Emission angle $\\mu$')\n plt.ylabel('I/F')\n plt.show()\n \n print('Polynomial parameters ... + A2*x**2 + A1*x + A2 = ',z)\n return z\n \n def locate_feature(self, outfile=None):\n plt.imshow(self.centered, origin = 'lower left')\n plt.show()\n print('Define a box around the feature you want to track. Note x,y are reversed in image due to weird Python indexing!')\n pix_l = input('Enter lower left pixel x,y separated by a comma: ')\n pix_u = input('Enter upper right pixel x,y separated by a comma: ')\n \n p0x, p0y = int(pix_l.split(',')[0].strip(', \\n')),int(pix_l.split(',')[1].strip(', \\n'))\n p1x, p1y = int(pix_u.split(',')[0].strip(', \\n')),int(pix_u.split(',')[1].strip(', \\n'))\n region = self.centered[p0x:p1x,p0y:p1y] \n\n #Brightest spot in feature\n maxloc = np.where(self.centered == np.max(region))\n maxlat, maxlon = self.lat_g[maxloc], self.lon_w[maxloc]\n \n #Gaussian fit\n A0 = np.sum(region)\n x0, y0 = (p1x - p0x)/2, (p1y - p0y)/2\n x_std0, y_std0 = region.shape[0]/2, region.shape[1]/2\n theta0 = 0.0\n g_init = models.Gaussian2D(A0, x0, y0, x_std0, y_std0, theta0)\n xx, yy = np.mgrid[:region.shape[0], :region.shape[1]]\n fit_g = fitting.LevMarLSQFitter()\n g = fit_g(g_init, xx, yy, region)\n \n xfg, yfg = g.x_mean + p0x, g.y_mean + p0y\n latfg, lonfg = self.lat_g[int(round(xfg)),int(round(yfg))], self.lon_w[int(round(xfg)), int(round(yfg))]\n \n ''' #estimate lat and lon errors\n frac = 0.5 #can probably constrain the center much more, but depends on morphology of storm over time\n fracmax = np.where(g_overlay/np.max(g_overlay) > frac)\n inlat, inlon = self.lat_g[fracmax], self.lon_w[fracmax]\n minlat, maxlat = np.min(inlat), np.max(inlat)\n minlon, maxlon = np.min(inlon), np.max(inlon) #wrapping issues still present!\n \n lat_errl, lat_erru = np.abs(latf - minlat), np.abs(maxlat - latf) \n lon_wrrl, lon_wrru = np.abs(lonf - minlon), np.abs(maxlon - lonf)'''\n\n #Contour method after Martin, de Pater, Marcus 2012\n def ctr_region(rgn, frac):\n rgn = np.copy(rgn)\n rgn[rgn < frac*np.max(rgn)] = 0.0\n rgn[rgn > 0.0] = 1.0\n xf, yf = center_of_mass(rgn)\n return xf, yf\n \n def interp_latlon_atpt(xd,yd):\n x, y = int(round(xd)), int(round(yd))\n xcoords, ycoords = np.arange(x-3, x+4), np.arange(y-3, y+4)\n latgrid = self.lat_g[x-3:x+4,y-3:y+4]\n longrid = self.lon_w[x-3:x+4,y-3:y+4]\n #RectBivariateSpline and interp2d both fail if lat/lon grid has NaNs, i.e. if near edge of planet\n if np.any(np.isnan(latgrid[2:5,2:5])):\n #Check to see if you are way too close\n print(' WARNING! DANGER! ERROR! HELP! OMG!')\n print(' Trying to find pixel locations very near edge of planet')\n print(' Lat-lon errors are probably wrong!!')\n latgrid[np.isnan(latgrid)] = 0.0\n longrid[np.isnan(longrid)] = 0.0\n interpf_lat = RectBivariateSpline(xcoords, ycoords, latgrid)\n interpf_lon = RectBivariateSpline(xcoords, ycoords, longrid)\n return interpf_lat.ev(xd, yd), interpf_lon.ev(xd, yd)\n #interpf_lat = interp2d(xcoords, ycoords, latgrid, kind = 'cubic')\n #interpf_lon = interp2d(xcoords, ycoords, longrid, kind = 'cubic')\n #return interpf_lat(xd, yd), interpf_lon(xd, yd)\n \n def ctr_fit(rgn, frac):\n (px, py) = ctr_region(rgn, frac)\n xfc, yfc = px + p0x, py + p0y\n #latfc, lonfc = self.lat_g[int(round(xfc)),int(round(yfc))], self.lon_w[int(round(xfc)), int(round(yfc))] #old way - fails if error is <~ 1 pixel\n latfc, lonfc = interp_latlon_atpt(xfc, yfc)\n return xfc, yfc, latfc, lonfc\n \n poslist = [] \n for val in np.arange(0.68, 0.96, 0.01):\n xfc, yfc, latfc, lonfc = ctr_fit(region, val)\n poslist.append([xfc, yfc, latfc, lonfc])\n poslist = np.asarray(poslist)\n medposlist = np.median(poslist, axis = 0)\n meanposlist = np.mean(poslist, axis = 0)\n minposlist = np.min(poslist, axis = 0)\n maxposlist = np.max(poslist, axis = 0)\n sigmaposlist = np.std(poslist, axis = 0) \n ## there will be longitude wrapping issues here later - will need to fix at some point\n\n print('Error in X,Y,lat,lon', sigmaposlist)\n print('Best X,Y,lat,lon (contour method)', medposlist)\n \n #write to file\n if outfile != None:\n print('Writing detailed outputs to file.')\n rows = ['# ','X_pixel', 'Y_pixel', 'Latitude', 'Longitude']\n columns = ['Brightest', 'Contour_Median','Contour_Mean','Contour_Sigma','Contour_Min','Contour_Max','Gaussian_Center','Gaussian_Sigma','Edge_Detect_Err']\n with open(outfile, 'w') as f:\n f.write('#Finding center of extended feature with a few techniques.\\n')\n f.write('#Note that edge detection error in lat, lon is actually edge detection lat/lon err in x-hat, y-hat\\n')\n f.write(' '.join(rows)+'\\n')\n f.write(columns[0]+' '+str(maxloc[0])+' '+str(maxloc[1])+' '+str(maxlat[0])+' '+str(maxlon[0])+'\\n')\n f.write(columns[1]+' '+str(medposlist[0])+' '+str(medposlist[1])+' '+str(medposlist[2])+' '+str(medposlist[3])+'\\n')\n f.write(columns[2]+' '+str(meanposlist[0])+' '+str(meanposlist[1])+' '+str(meanposlist[2])+' '+str(meanposlist[3])+'\\n')\n f.write(columns[3]+' '+str(sigmaposlist[0])+' '+str(sigmaposlist[1])+' '+str(sigmaposlist[2])+' '+str(sigmaposlist[3])+'\\n')\n f.write(columns[4]+' '+str(minposlist[0])+' '+str(minposlist[1])+' '+str(minposlist[2])+' '+str(minposlist[3])+'\\n')\n f.write(columns[5]+' '+str(maxposlist[0])+' '+str(maxposlist[1])+' '+str(maxposlist[2])+' '+str(maxposlist[3])+'\\n')\n f.write(columns[6]+' '+str(xfg)+' '+str(yfg)+' '+str(latfg)+' '+str(lonfg)+'\\n')\n f.write(columns[7]+' '+str(g.x_stddev + 0)+' '+str(g.y_stddev + 0)+' '+str(-999)+' '+str(-999)+'\\n')\n f.write(columns[8]+' '+str(-999)+' '+str(-999)+' '+str(self.err_x[int(round(medposlist[0])),int(round(medposlist[1]))])+' '+str(self.err_y[int(round(medposlist[0])),int(round(medposlist[1]))])+'\\n')\n \n #replace Gaussian onto grid we had before for plotting\n eval_g = g(xx, yy)\n g_overlay = np.zeros(self.centered.shape)\n g_overlay[p0x:p1x,p0y:p1y] = eval_g\n #plot things up \n fig, (ax0) = plt.subplots(1,1, figsize = (8,5))\n ax0.imshow(region, origin = 'lower left')\n levels = [0.68, 0.815, 0.95]\n cs = ax0.contour(region/np.max(region), levels, colors = 'white')\n cs_g = ax0.contour(eval_g/np.max(eval_g), [0.68], colors = 'red')\n plt.show() \n \n \n def project(self, outstem = 'h', pixsz = None, interp = 'cubic'):\n '''Project the data onto a flat x-y grid.\n pixsz is in arcsec. if pixsz = None, translates the pixel scale\n of the image to a distance at the sub-observer point.\n interp asks whether to regrid using a nearest neighbor, linear, or cubic'''\n \n #determine the number of pixels in resampled image\n if pixsz == None:\n pixsz = self.pixscale_arcsec\n npix_per_degree = (1/self.deg_per_px) * (self.pixscale_arcsec / pixsz) # (old pixel / degree lat) * (arcsec / old pixel) / (arcsec / new pixel) = new pixel / degree lat\n npix = int(npix_per_degree * 180) + 1 #(new pixel / degree lat) * (degree lat / planet) = new pixel / planet\n print('New image will be %d by %d pixels'%(2*npix + 1, npix))\n print('Pixel scale %f km = %f pixels per degree'%(self.pixscale_km, npix_per_degree))\n \n #create new lon-lat grid\n extra_wrap_dist = 180\n newlon, newlat = np.arange(-extra_wrap_dist,360 + extra_wrap_dist, 1/npix_per_degree), np.arange(-90,90, 1/npix_per_degree)\n gridlon, gridlat = np.meshgrid(newlon, newlat)\n nans = np.isnan(self.lon_w.flatten())\n def input_helper(arr, nans):\n '''removing large region of NaNs speeds things up significantly'''\n return arr.flatten()[np.logical_not(nans)]\n inlon, inlat, indat = input_helper(self.lon_w, nans), input_helper(self.lat_g, nans), input_helper(self.centered, nans)\n\n #fix wrapping by adding dummy copies of small lons at > 360 lon\n inlon_near0 = inlon[inlon < extra_wrap_dist]\n inlon_near0 += 360\n inlon_near360 = inlon[inlon > 360 - extra_wrap_dist]\n inlon_near360 -= 360\n inlon_n = np.concatenate((inlon_near360, inlon, inlon_near0))\n inlat_n = np.concatenate((inlat[inlon > 360 - extra_wrap_dist], inlat, inlat[inlon < extra_wrap_dist]))\n indat_n = np.concatenate((indat[inlon > 360 - extra_wrap_dist], indat, indat[inlon < extra_wrap_dist]))\n\n #do the regridding\n datsort = griddata((inlon_n, inlat_n), indat_n, (gridlon, gridlat), method = interp)\n \n #trim extra data we got from wrapping\n wrap_i_l = len(gridlon[0][gridlon[0] < 0]) - 1\n wrap_i_u = len(gridlon[0][gridlon[0] >= 360])\n datsort = datsort[:,wrap_i_l:-wrap_i_u]\n gridlon = gridlon[:,wrap_i_l:-wrap_i_u]\n gridlat = gridlat[:,wrap_i_l:-wrap_i_u]\n \n # make far side of planet into NaNs\n snorm = surface_normal(gridlat, gridlon, self.ob_lon)\n #emang = emission_angle(self.ob_lat, snorm).T\n emang = emission_angle(self.ob_lat, snorm)\n farside = np.where(emang < 0.0)\n datsort[farside] = np.nan\n self.projected = datsort\n self.mu_projected = emang\n \n #write data to fits file \n hdulist_out = self.im.hdulist\n ## projected data\n hdulist_out[0].header['OBJECT'] = self.target+'_projected'\n hdulist_out[0].data = datsort\n hdulist_out[0].writeto(outstem + '_proj.fits', overwrite=True)\n ## emission angles\n hdulist_out[0].header['OBJECT'] = self.target+'_mu_proj'\n hdulist_out[0].data = emang\n hdulist_out[0].writeto(outstem + '_mu_proj.fits', overwrite=True)\n print('Writing files %s'%outstem + '_proj.fits and %s'%outstem + '_mu_proj.fits')\n \n def plot_projected(self, outfname, ctrlon = 180, lat_limits = [-90, 90], lon_limits = [0, 360], cbarlabel = 'I/F'):\n '''Once projection has been run, plot it using this function''' \n \n #apply center longitude to everything\n npix = self.projected.shape[1]\n npix_per_degree = 1.0 / self.deg_per_px\n print(npix_per_degree)\n offset = (ctrlon + 180)%360\n offsetpix = np.round(offset*npix_per_degree)\n uoffsetpix = npix - offsetpix\n newim = np.copy(self.projected)\n lefthalf = self.projected[:,:offsetpix]\n righthalf = self.projected[:,offsetpix:]\n newim[:,uoffsetpix:] = lefthalf #switch left and right halves\n newim[:,:uoffsetpix] = righthalf\n \n #extent = [ctrlon - 180, ctrlon + 180, -90, 90]\n extent = [ctrlon + 180, ctrlon - 180, -90, 90]\n parallels = np.arange(lat_limits[0],lat_limits[1] + 30, 30.)\n #meridians = np.arange(lon_limits[0],lon_limits[1] + 60, 60.)\n meridians = np.arange(lon_limits[1], lon_limits[0] - 60, -60.)\n \n #plot it\n fs = 14 #fontsize for plots\n fig, ax0 = plt.subplots(1,1, figsize = (10,7))\n \n cim = ax0.imshow(np.fliplr(newim), origin = 'lower left', cmap = 'gray', extent = extent)\n for loc in parallels:\n ax0.axhline(loc, color = 'cyan', linestyle = ':')\n for loc in meridians:\n ax0.axvline(loc, color = 'cyan', linestyle = ':')\n\n ax0.set_xlabel('Longitude (W)', fontsize = fs)\n ax0.set_ylabel('Latitude', fontsize = fs)\n ax0.set_ylim(lat_limits)\n ax0.set_xlim(lon_limits[::-1])\n ax0.set_title(self.date_time, fontsize = fs + 2)\n ax0.tick_params(which = 'both', labelsize = fs - 2)\n \n #plot the colorbar\n divider = make_axes_locatable(ax0)\n cax = divider.append_axes('right', size='5%', pad=0.05)\n cbar = fig.colorbar(cim, cax = cax, orientation = 'vertical')\n cbar.set_label(cbarlabel, fontsize = fs)\n cax.tick_params(which = 'both', labelsize = fs - 2)\n \n plt.savefig(outfname, bbox = None)\n plt.show()\n \n def feature_size_projected(self):\n '''Find a feature, tell how big it is in lat-lon space'''\n \n if not hasattr(self, 'projected'):\n print('Must run on projected data. Run coords.project() first. Returning')\n return\n \n plt.imshow(self.projected, origin = 'lower left')\n plt.show()\n print('Define a box around the feature you want to track. Note x,y are reversed in image due to weird Python indexing!')\n pix_l = input('Enter lower left pixel x,y separated by a comma: ')\n pix_u = input('Enter upper right pixel x,y separated by a comma: ')\n \n p0x, p0y = int(pix_l.split(',')[0].strip(', \\n')),int(pix_l.split(',')[1].strip(', \\n'))\n p1x, p1y = int(pix_u.split(',')[0].strip(', \\n')),int(pix_u.split(',')[1].strip(', \\n'))\n region = self.projected[p0x:p1x,p0y:p1y]\n \n def build_contour(rgn, frac):\n rgn = np.copy(rgn)\n rgn[rgn < frac*np.max(rgn)] = 0.0\n rgn[rgn > 0.0] = 1.0\n return rgn\n \n level = 0.5\n fwhm_2d = build_contour(region, level)\n \n # find the longest rays in the x and y direction across the amorphous fwhm region\n collapse_x = np.sum(fwhm_2d, axis = 1)\n collapse_y = np.sum(fwhm_2d, axis = 0)\n fwhm_x, wherefwhm_x = np.max(collapse_x), np.argmax(collapse_x)\n fwhm_y, wherefwhm_y = np.max(collapse_y), np.argmax(collapse_y)\n \n # convert to lat-lon\n deg_lat, deg_lon = fwhm_x * self.deg_per_px, fwhm_y * self.deg_per_px\n km_lat, km_lon = fwhm_x * self.pixscale_km, fwhm_y * self.pixscale_km\n print('%f degrees lat, %f degrees lon'%(deg_lat, deg_lon))\n print('%f km in zonal direction, %f km in meridional direction'%(km_lat, km_lon))\n \n # for plotting, find min point and max point for each of these rays\n ray_x = np.where(fwhm_2d[wherefwhm_x, :] == 1)[0]\n ray_y = np.where(fwhm_2d[:, wherefwhm_y] == 1)[0]\n \n plt.imshow(region, origin = 'lower left', cmap = 'gray')\n plt.contour(fwhm_2d, levels = [level], colors = ['red'])\n plt.plot(ray_x, np.full(ray_x.shape, wherefwhm_x), color = 'r', lw = 2)\n plt.plot(np.full(ray_y.shape, wherefwhm_y), ray_y, color = 'r', lw = 2)\n plt.title('%s'%self.date_time[:-6])\n plt.savefig('storm_size.png')\n plt.show()\n \n \n \n def help(self):\n \n helpstr = '''\n Contains tasks for image navigation, image projection, calculating I/F, and\n other things that require Horizons ephemeris data to compute\n \n Functions (see DOCUMENTATION.py for use):\n ioverf(self, filt, flux_per, stand_airmass)\n write_photonly(self, outstr)\n edge_detect(self, low_thresh = 0.01, high_thresh = 0.05, sigma = 5, plot = True)\n edge_detect_error(self, niter, perturb_l, perturb_dist, low_thresh = 0.002, dist = 0.02, sigma = 5, doplot = True)\n manual_shift(self,dx,dy)\n plot_latlon(self)\n write(self, lead_string)\n bootstrap_func(self, order = 2)\n locate_feature(self, outfile=None)\n project(self, outstem = 'h', pixsz = None, interp = 'cubic')\n plot_projected(self, outfname, ctrlon = 180, lat_limits = [-90, 90], lon_limits = [0, 360], cbarlabel = 'I/F')\n \n Attributes:\n im: image object for infile\n req: equatorial radius\n rpol: polar radius\n data: the image data\n pixscale_arcsec: pixel scale of image in arcsec\n target: name of planet\n date_time: datetime object for start time\n airmass:\n ang_diam:\n ob_lon: sub observer longitude\n ob_lat: sub observer latitude\n sun_lon: sub solar longitude\n sun_lat: sub solar latitude\n np_ang: north pole position angle (CCW, or east, wrt celestial north)\n np_dist: angular dist of np from sub observer point\n sun_dist: distance from target to sun\n dist: distance from target to observer \n pixscale_km: pixel scale of image in km\n deg_per_px: lat/lon degrees on planet per pixel at sub obs point\n lat_g: grid of planetographic latitudes on planet\n lat_c: grid of planetocentric latitudes on planet\n lon_w: grid of west longitudes on planet (west for IAU standard, as output by Horizons)\n err_x: lat/lon error from navigation in x direction, in px\n err_y: lat/lon error from navigation in y direction, in px\n centered: centered data after edge detection\n model_planet: ellipse with planet's projected shape based on ephemeris\n projected: image on regular lat/lon grid after projection\n mu: grid of emission angles on planet\n surf_n: grid of normal vectors to the surface of planet\n x_shift: pixel shift in x direction from edge detect\n y_shift: pixel shift in x direction from edge detect\n edges: map of edges found by edge detect\n '''\n print(helpstr)\n \n \n \n \n \n ''' \n def change_projection(self):\n not written yet but would use basemap, or Charles Goullaud replacement, to reproject arbitrarily\n \n ''' \n ","sub_path":"coordgrid.py","file_name":"coordgrid.py","file_ext":"py","file_size_in_byte":44351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"252174803","text":"import sys\nimport json\nimport re\nimport os\n\ncompanion_data_dir = sys.argv[1]\noutdir = sys.argv[2]\nhyphen_re = re.compile(r'[–—−]')\nfor filename in os.listdir(companion_data_dir):\n mrp_companion = {}\n with open(companion_data_dir+filename) as infile:\n for line in infile:\n if line.startswith('#'):\n id = line[1:].strip()\n mrp_companion[id] = {'tokenization':[], 'spans':{}}\n elif not line.startswith('\\n'):\n line = line.split()\n token = line[1]\n token = re.sub(r'[–—−]', '-', token).lower()\n if \"’\" in token:\n token = token.replace(\"’\", \"'\")\n #if \"”\" in token:\n # token = token.replace(\"”\", '\"')\n #if \"“\" in token:\n # token = token.replace(\"“\", '\"')\n if \"…\" in token:\n token = token.replace(\"…\", \"...\")\n #if '-' in token:\n # token = token.replace('-', '—')\n mrp_companion[id]['tokenization'].append(token)\n span = line[-1][11:]\n index = line[0]\n mrp_companion[id]['spans'][span] = int(index) -1\n json.dump(mrp_companion, open(outdir+ filename[:-7]+'.json', 'w', encoding='utf8'), ensure_ascii=False)\n","sub_path":"ucca/get_companion_tokenization.py","file_name":"get_companion_tokenization.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"500675045","text":"#OOPR-Assgn-10\r\n\r\nclass CallDetail:\r\n def __init__(self,phoneno,called_no,duration,call_type):\r\n self.__phoneno=phoneno\r\n self.__called_no=called_no\r\n self.__duration=duration\r\n self.__call_type=call_type \r\n \r\n \r\nclass Util:\r\n def __init__(self):\r\n self.list_of_call_objects=None\r\n\r\n def parse_customer(self,list_of_call_string):\r\n self.list_of_call_objects=[]\r\n b=[]\r\n for i in list_of_call_string:\r\n b.append(i.split(','))\r\n a=b\r\n for i in range(0,len(a)):\r\n self.list_of_call_objects.append(CallDetail(a[i][0],a[i][1],a[i][2],a[i][3]))\r\n return self.list_of_call_objects\r\ncall='9990000001,9330000001,23,STD'\r\ncall2='9990000001,9330000002,54,Local'\r\ncall3='9990000001,9330000003,6,ISD'\r\n\r\nlist_of_call_string=[call,call2,call3]\r\nUtil().parse_customer(list_of_call_string)\r\n\r\n","sub_path":"OOPS/day2/Assignment10.py","file_name":"Assignment10.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"64247508","text":"from flask import Flask, redirect, url_for, render_template, jsonify, request\nimport os\n\napp = Flask(__name__, static_url_path=\"/static\")\n\n@app.route(\"/\", methods=[\"GET\"])\ndef blank():\n return redirect(\"/whoops/\")\n\n@app.route(\"//\", methods=[\"GET\"])\ndef main(location):\n pages = [\"home\", \"upcoming_events\", \"current_members\", \"contact_us\"]\n if location not in pages:\n location = \"whoops\"\n cocntents = \"\"\n realpath = os.path.dirname(os.path.realpath(__file__))+\"/templates/\"\n with open(realpath+location+\".html\", \"r\") as fin:\n contents = fin.read()\n pretty = {\n \"home\": \"Home\",\n \"upcoming_events\": \"Upcoming Events\",\n \"current_members\": \"Current Members\",\n \"contact_us\": \"Contact Us\",\n \"whoops\": \"Whoops\"\n }\n return render_template(\"index.html\", url=location, page=pretty[location], html=contents)\n\n@app.route(\"/load_page/\", methods=[\"GET\"])\ndef load_page():\n print(\"here\")\n return jsonify(url=request.args[\"goal\"], page=request.args[\"goal\"], html=\"

    WORKED

    \")\n\nif __name__ == \"__main__\":\n app.run(debug=True, threaded=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"237495494","text":"# coding:utf-8\n\nfrom flask import Blueprint, request, jsonify\n\nfrom ..service import locationService\nfrom ..results import multi_location_result\nfrom ..helpers import crossdomain\n\nbp = Blueprint('location_user', __name__, url_prefix=\"/locations\")\n\n\n@bp.route(\"/search_by_geo\", methods=[\"GET\"])\n@crossdomain(origin=\"*\")\ndef search_article_by_geo():\n poi_longitude = float(request.args.get(\"longitude\")) if request.args.get(\"longitude\") else None\n poi_latitude = float(request.args.get(\"latitude\")) if request.args.get(\"latitude\") else None\n poi_distance = float(request.args.get(\"distance\")) if request.args.get(\"distance\") else None\n location_id_list = locationService. \\\n location_id_by_geo(poi_longitude=poi_longitude, poi_latitude=poi_latitude, poi_distance=poi_distance)\n\n location_list = multi_location_result(location_id_list)\n return jsonify(data=dict(locations=location_list, success=True))","sub_path":"program/frontend/location_user.py","file_name":"location_user.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"375700840","text":"from minesweeper import Board\nimport curses\n\n_UP = \"up\"\n_DOWN = \"down\"\n_RIGHT = \"right\"\n_LEFT = \"left\"\n\nclass MineBoardKey(Board):\n def __init__(self, width, height, mines):\n Board.__init__(self, width, height, mines)\n curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLACK)\n curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_WHITE)\n self.colormap = {'n':curses.color_pair(1), 'h':curses.color_pair(2)}\n self.marker = [0,0]\n\n def move_marker(self, direction):\n \"\"\" move marker over board \"\"\"\n if direction == _UP and self.marker[1]+1 < self.height:\n self.marker[1] += 1\n elif direction == _DOWN and self.marker[1] > 0:\n self.marker[1] += -1\n elif direction == _LEFT and self.marker[0] > 0:\n self.marker[0] += -1\n elif direction == _RIGHT and self.marker[0]+1 < self.width:\n self.marker[0] += 1\n \n def keypress(self, c):\n \"\"\" deals with keypresses \"\"\"\n if c == ord('q'):\n return None\n elif c == 259:\n self.move_marker(_DOWN)\n elif c == 258:\n self.move_marker(_UP)\n elif c == 260:\n self.move_marker(_LEFT)\n elif c == 261:\n self.move_marker(_RIGHT)\n elif c == ord('d'):\n self.reveal(self.marker[0], self.marker[1])\n elif c == ord('s'):\n self.switchMark(self.marker[0], self.marker[1])\n elif c == ord('r'):\n self.reset()\n \n return self\n\n def print_to_screen(self, screen):\n \"\"\" prints itself to the curses screen \"\"\"\n h = \"arrows to move, q to return, r to reveal, e to mark\"\n screen.addstr(1,2,h)\n n = 5\n\n for i in xrange(self.width):\n for j in xrange(self.height):\n if [i,j] == self.marker:\n color = self.colormap[\"h\"]\n else:\n color = self.colormap[\"n\"]\n screen.addstr(n+j, i+1, str(self.board[i][j]), color)\n \n","sub_path":"games/minesweeperkey.py","file_name":"minesweeperkey.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"641752727","text":"from __future__ import print_function\nimport argparse\nimport sys\nimport os\nfrom glob import glob\nimport webbrowser\nfrom datetime import datetime\n\nfrom auth import get_anon_client, log_in\nfrom utils import get_metadata\n\n# file extensions accepted by imgur\nfile_extensions = ['.png', '.jpg', '.gif', '.tif',\n '.bmp', '.tiff', '.pdf', '.xcf']\n\n\nclass Uploader:\n\n \"\"\"A class that interacts with imgur's api in order to\n upload local images to imgur.com from the command line.\n \"\"\"\n\n def __init__(self, args):\n self.args = args\n self.metadata = dict(title=self.args.title,\n description=self.args.description)\n self.init_client()\n\n def init_client(self):\n \"\"\"Sets ImgurClient scope based on user preference\"\"\"\n self.client = get_anon_client()\n if self.args.user:\n self.client = log_in(self.client)\n\n def upload_pic(self, path, data, album_id=None):\n # as of now, does not check for valid file extension\n anon = self.client.auth is None\n if album_id:\n data['album'] = album_id\n image = self.client.upload_from_path(path, data, anon)\n\n self.log_upload(image)\n\n return image['id'] # return image if more data is needed\n\n def upload_album(self):\n album_data = get_metadata(\n True) if self.args.metadata else self.metadata\n album = self.client.create_album(album_data)\n print('Created album named \"{}\"'.format(album_data.get('title')))\n self.log_upload(album)\n\n album_id = album['id'] if self.client.auth else album['deletehash']\n\n # get all images in the folder with approved file extensions\n files = [glob(os.path.join(self.args.path, '*' + ext))\n for ext in file_extensions]\n files = sum(files, []) # ugly way to flatten list\n\n for f in files:\n print('Uploading {}'.format(os.path.basename(f)))\n img_data = get_metadata() if self.args.metadata else dict()\n self.upload_pic(f, img_data, album_id)\n\n return album['id'] # return album if more data is needed\n\n def log_upload(self, entity):\n \"\"\"Record time of upload and deletion links of upload in\n local file log.txt\n \"\"\"\n with open('log.txt', 'a+') as f:\n deletehash = entity['deletehash']\n link = 'http://imgur.com/delete/{}'.format(deletehash)\n record = '{} {}'.format(datetime.now().strftime('%c'), link)\n f.write(record+'\\n')\n return link\n\n def main(self):\n args = self.args\n if args.screenshot:\n if args.path.endswith('.png') or args.path.endswith('.bmp'):\n from screenshot import take_screenshot\n take_screenshot(args.path, args.delay)\n pic_id = self.upload_pic(args.path, self.metadata)\n print('Upload complete.')\n webbrowser.open(self.client.get_image(pic_id).link)\n else:\n sys.exit('File must be saved as a bitmap or png.')\n\n elif os.path.isfile(args.path):\n pic_id = self.upload_pic(args.path, self.metadata)\n print('Upload complete.')\n webbrowser.open(self.client.get_image(pic_id).link)\n\n elif os.path.isdir(self.args.path):\n album_id = self.upload_album()\n print('Upload complete.')\n webbrowser.open(self.client.get_album(album_id).link)\n\n else:\n sys.exit(\"\\nWhat you are trying to upload does not exist\")\n\n\nif __name__ == \"__main__\":\n description = \"\"\"A command line wrapper for imgur's api\"\"\"\n parser = argparse.ArgumentParser(description=description)\n parser.add_argument('path', action='store',\n help='path to file or folder to upload')\n parser.add_argument('-t', '--title',\n action='store', help='title of upload')\n parser.add_argument('-d', '--description',\n action='store', help='upload description')\n parser.add_argument('-u', '--user', action='store_true',\n help='upload to stored user account')\n parser.add_argument('-m', '--metadata', action='store_true',\n help='add data to images when uploading album')\n parser.add_argument('-s', '--screenshot', action='store_true',\n help='take screenshot and upload it')\n parser.add_argument('--delay', default=3, type=int,\n help='delay (s) before taking screenshot')\n args = parser.parse_args()\n Uploader(args=args).main()\n","sub_path":"climgur/climgur.py","file_name":"climgur.py","file_ext":"py","file_size_in_byte":4635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"466940988","text":"class Solution(object):\n def findMin(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n l, r = 0, len(nums) - 1\n if r == 0: return nums[0]\n while r - l >= 2:\n mid = (l + r) // 2\n if nums[mid] > nums[l]:\n l = mid\n elif nums[mid] < nums[r]:\n r = mid\n mid = (l + r) // 2 \n return min(nums[(mid + 1) % len(nums)], nums[(mid + 2) % len(nums)]) # nums[mid + 1 + 1] for no-rotation case.\n\n\nif __name__ == '__main__':\n # inputs\n nums = list(range(10))\n k = 0\n nums = nums[-k:] + nums[:-k]\n print(nums)\n print('-' * 30)\n res = Solution().findMin(nums)\n print(res)\n ","sub_path":"153_findMin.py","file_name":"153_findMin.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"479869104","text":"import asyncio\nimport aioredis\n\n\nREDIS_SERVER = ('localhost', 6379)\n\n\nasync def run():\n print('[~] start connection to Redis server')\n redis = await aioredis.create_redis(REDIS_SERVER)\n\n print('[~] connection established')\n print(str.format('[~] Redis database: {}', redis.db))\n\n await redis.delete('foo', 'bar')\n\n tr = redis.multi_exec()\n tr.incr('foo')\n tr.incr('bar')\n\n await tr.execute()\n redis.close()\n\n print(str.format('[~] Redis connection is closed: {}', redis.closed))\n\n await redis.wait_closed()\n\n\ndef main():\n loop = asyncio.get_event_loop()\n\n try:\n loop.run_until_complete(run())\n except KeyboardInterrupt:\n print('[x] Event loop interrupted by Ctrl + C')\n finally:\n print('[x] Event loop is closed')\n loop.close()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"packages/async_packages/aioredis_package/app1.py","file_name":"app1.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"239048917","text":"def min(arr):\r\n amin = arr[0]\r\n for i in arr:\r\n if i < amin:\r\n amin = i\r\n return amin\r\n\r\ndef avg(arr):\r\n s = 0\r\n for i in arr:\r\n s += i\r\n return s//len(arr)\r\n\r\narr1 = [10,8,12,0]\r\nprint(min(arr1))\r\nprint(avg(arr1))\r\n\r\n","sub_path":"LICENSE.md/arr_algs.py","file_name":"arr_algs.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"21355415","text":"import numpy as np\nfrom sigmoid import sigmoid_\n\ndef vec_reg_logistic_grad(y, x, theta, lambda_):\n \"\"\"Computes the regularized linear gradient of three non-empty numpy.ndarray, without any for-loop. The three arrays must have compatible dimensions.\"\"\"\n if isinstance(x, np.ndarray) == 1 and isinstance(y, np.ndarray) == 1 and isinstance(theta, np.ndarray) == 1:\n if isinstance(lambda_, (int, float)) == 1:\n if len(y) == len(x) and len(x[0]) == len(theta):\n y_pred = sigmoid_(np.dot(x, theta))\n temp = np.dot(x.T, (y_pred - y)) / len(x)\n res = np.dot(x.T, (y_pred - y)) / len(x) + np.dot(lambda_ / len(x), theta)\n res[0] = temp[0]\n return (res)\n else:\n print(\"vec_reg_log_gradient: error in size of x, y or theta\")\n else:\n print(\"vec_reg_log_gradient: lamda is not a scalar\")\n else:\n print(\"vec_reg_log_gradient: error in type of x, y or theta\")\n\nX = np.array([\n [ -6, -7, -9],\n [ 13, -2, 14],\n [ -7, 14, -1],\n [ -8, -4, 6],\n [ -5, -9, 6],\n [ 1, -5, 11],\n [ 9, -11, 8]])\nY = np.array([1,0,1,1,1,0,0])\nZ = np.array([1.2,0.5,-0.32])\n\nprint(vec_reg_logistic_grad(Y, X, Z, 1))\nprint(vec_reg_logistic_grad(Y, X, Z, 0.5))\nprint(vec_reg_logistic_grad(Y, X, Z, 0.0))\n","sub_path":"day03/ex07/vec_reg_linear_grad.py","file_name":"vec_reg_linear_grad.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"401918244","text":"\"\"\"\nOpens up magnetometer, inclinometer, and stepper motor HDF5 files. \nCalculates heading (magnetic and true) with tilt compensation. \nAlso calculates inclination based on elevation motor movement.\n\nSummer 2021\nTested On:\nStarfire (ubuntu 18.04)\nInflux 2.0.4\nGrafana 7.4.2\n\"\"\"\n\nimport serial\nimport numpy as np\nimport h5py\nimport time\nimport math\nimport requests\nimport sys\nimport os\nimport glob\n\n\n\n\"\"\"---Authorization/QUERY initialization---\"\"\"\n#Starting with Influx 2.0, authorization tokens are necessary to access databases\n#Stringing together query access\nINFLUX_TOKEN='AjsrNgY_k97FMvgfCsgc2tPTx-lOVM-aYaCMjymNVIWpoSCkYh7H4AqIV9pLQHHk07zJa5pxTn4lo-3Ashwu5Q=='\nORG=\"tim@upenn\"\nINFLUX_CLOUD_URL='localhost'\nBUCKET_NAME='sensors'\n\n#Can change precision if needed. Currently set to nanoseconds (ns).\nQUERY_URI='http://{}:8086/api/v2/write?org={}&bucket={}&precision=ns'.format(INFLUX_CLOUD_URL,ORG,BUCKET_NAME)\n\nheaders = {}\nheaders['Authorization'] = 'Token {}'.format(INFLUX_TOKEN)\n\n#Parameters for line protocol that will be sent to Influx\nlocation_tag = 'lab'\nmeasurement_name = 'heading'\n\n\n\"\"\"---Open Files---\"\"\"\nstart_time = time.perf_counter()\ndatestamp = time.strftime(\"%Y-%m-%d\")\n\n\n#A series of directory checks. Will exit from program if no folder/files are detected.\nif os.path.isdir(\"/home/user/tim-daq/data/\"+datestamp+\"-Mag\") == 0:\n print(\"No Directory Detected\")\n sys.exit()\n \nif os.path.isdir(\"/home/user/tim-daq/data/\"+datestamp+\"-Inclin\") == 0:\n print(\"No Directory Detected\")\n sys.exit()\nif os.path.isdir(\"/home/user/tim-daq/data/\"+datestamp+\"-Stepper\") == 0:\n print(\"No Directory Detected\")\n sys.exit()\n\n\nif len(os.listdir(\"/home/user/tim-daq/data/\"+datestamp+\"-Mag\")) == 0:\n print(\"No Files Detected\")\n sys.exit()\nelse:\n file_list = glob.glob(\"/home/user/tim-daq/data/\"+datestamp+\"-Mag/*.hdf5\")\n mag_file_name = max(file_list, key=os.path.getctime)\n #print(mag_file_name)\n \nif len(os.listdir(\"/home/user/tim-daq/data/\"+datestamp+\"-Inclin\")) == 0:\n print(\"No Files Detected\")\n sys.exit()\nelse:\n file_list = glob.glob(\"/home/user/tim-daq/data/\"+datestamp+\"-Inclin/*.hdf5\")\n inclin_file_name = max(file_list, key=os.path.getctime)\n #print(inclin_file_name)\nif len(os.listdir(\"/home/user/tim-daq/data/\"+datestamp+\"-Stepper\")) == 0:\n print(\"No Files Detected\")\n sys.exit()\nelse:\n file_list = glob.glob(\"/home/user/tim-daq/data/\"+datestamp+\"-Stepper/*.hdf5\")\n stepper_file_name = max(file_list, key=os.path.getctime)\n #print(inclin_file_name)\n \n\n#Opens HDF5 files \nmag_file = h5py.File(mag_file_name, 'r', libver = 'latest', swmr = True)\ninclin_file = h5py.File(inclin_file_name, 'r', libver = 'latest', swmr = True)\nstepper_file = h5py.File(stepper_file_name, 'r', libver = 'latest', swmr = True)\n\n#Opens appropriate datasets\nmag_x = mag_file['x']\nmag_len = mag_x.shape[0]\nmag_y = mag_file['y']\nmag_z = mag_file['z']\nmag_timestamp = mag_file['time']\n\ninclin_x = inclin_file['x']\ninclin_y = inclin_file['y']\ninclin_len = inclin_x.shape[0]\n\nstepper_az = stepper_file['az']\nstepper_el = stepper_file['el']\nstepper_len = stepper_az.shape[0]\n\nmag_heading_list = [] \ntrue_heading_list = []\nel_list = []\nzero_mag_deg = 0\nzero_true_deg = 0\nzero_el = 0\n\n\n\"\"\"---Main Loop---\"\"\"\nwhile True:\n \n #Grabs the latest data point index (from file dataset)\n mag_index_num = mag_file['index'][0] \n inclin_index_num = inclin_file['index'][0]\n stepper_index_num = stepper_file['index'][0]\n \n #Must refresh constantly..\n mag_file['index'].id.refresh()\n mag_x.id.refresh()\n mag_y.id.refresh()\n mag_z.id.refresh()\n mag_timestamp.refresh()\n \n inclin_file['index'].id.refresh()\n inclin_x.id.refresh()\n inclin_y.id.refresh()\n \n stepper_file['index'].id.refresh()\n stepper_az.id.refresh()\n stepper_el.id.refresh()\n \n #Creates list copies\n mag_x_list = mag_x[:]\n mag_y_list = mag_y[:]\n mag_z_list = mag_z[:]\n mag_timestamp_list = mag_timestamp[:]\n inclin_x_list = inclin_x[:]\n inclin_y_list = inclin_y[:]\n stepper_az_list = stepper_az[:]\n stepper_el_list = stepper_el[:]\n \n #Grabs latest data values\n mag_x_dat = mag_x_list[mag_index_num]\n mag_y_dat = mag_y_list[mag_index_num]\n mag_z_dat = mag_z_list[mag_index_num]\n mag_timestamp_dat = mag_timestamp_list[mag_index_num]\n \n inclin_x_dat = inclin_x_list[inclin_index_num]\n inclin_y_dat = inclin_y_list[inclin_index_num]\n\n stepper_az_dat = stepper_az_list[stepper_index_num]\n stepper_el_dat = stepper_el_list[stepper_index_num]\n \n\t\n###Heading calculations###\n declination = 11 #Found declination value online.\n \n pitch = np.deg2rad(inclin_y_dat)\n roll = -np.deg2rad(inclin_x_dat)\n\n #Calculate X and Y components of Magnetic North vector, with tilt compensation from inclinometer data \n Xh = mag_x_dat * np.cos(pitch) + mag_y_dat * np.sin(roll) * np.sin(pitch) - mag_z_dat * np.cos(roll) * np.sin(pitch) \n Yh = mag_y_dat * np.cos(roll) + mag_z_dat * np.sin(roll)\n \n \n magnetic_north = np.rad2deg(math.atan2(Yh,Xh))\n true_north = magnetic_north - declination\n \n if magnetic_north < 0: #Converts from -180-180 range to 0-360 range\n magnetic_north += 360\n if true_north < 0:\n true_north += 360\n \n #Generates a \"zero\" heading/elevatoin reading at the start of program. Future changes in angle will be added to this \"zero\" value.\n while time.perf_counter() - start_time< .05: \n mag_heading_list.append(magnetic_north)\n true_heading_list.append(true_north)\n el_list.append(inclin_x_dat)\n\n zero_mag_deg = mag_heading_list[-1]\n zero_true_deg = true_heading_list[-1]\n zero_el = el_list[-1]\n \n \n \n stepper_heading_mag = zero_mag_deg - stepper_az_dat\n if stepper_heading_mag < 0: #Converts from -180-180 range to 0-360 range\n stepper_heading_mag += 360\n stepper_elevation = zero_el - stepper_el_dat\n\n###Pushing to Influx and Grafana###\n #Line protocol setup\n line = '{measurement},location={location} mag_heading={heading},true_heading={heading2},stepper_heading_mag={heading3},elevation={elevation} {timestamp}'.format(measurement=measurement_name,location=location_tag, heading=magnetic_north,heading2=true_north,heading3 = stepper_heading_mag,elevation = stepper_elevation, timestamp=mag_timestamp_dat)\n \n #Sends data into Influx\n r = requests.post(QUERY_URI, data=line, headers=headers)\n #print(r.status_code)\n #print(line)\n \n \n #Once the end of the file has been reached, get ready to open the new one.\n if mag_index_num >= mag_len - 2:\n \n next_file_num = mag_file['filenames'][1] #Next file number taken from current open file\n next_file = str(next_file_num)\n \n mag_index_num = 0\n \n \n #Check if the next file (with correct number) exists\n file_path = \"/home/user/tim-daq/data/\"+datestamp+\"-Mag/\"+\"*\"+next_file.zfill(5)+\"*\"\n while glob.glob(file_path) == []: #If it doesn't exist, wait\n time.sleep(0.05)\n \n mag_file.close() #Close current file\n \n\n #Opens the next HDF5 file \n mag_file = h5py.File(glob.glob(file_path)[0], 'r', libver = 'latest', swmr = True)\n mag_x = mag_file['x']\n mag_len = mag_x.shape[0]\n mag_y = mag_file['y']\n mag_z = mag_file['z']\n mag_timestamp = mag_file['time']\n \n #Repeat for other sensor files.\n if inclin_index_num >= inclin_len -1:\n next_file_num = inclin_file['filenames'][1]\n next_file = str(next_file_num)\n inclin_index_num = 0\n \n \n file_path = \"/home/user/tim-daq/data/\"+datestamp+\"-Inclin/\"+\"*\"+next_file.zfill(5)+\"*\"\n while glob.glob(file_path) == []:\n time.sleep(0.05) \n inclin_file.close()\n \n inclin_file = h5py.File(glob.glob(file_path)[0], 'r', libver = 'latest', swmr = True)\n inclin_x = inclin_file['x']\n inclin_len = inclin_x.shape[0]\n inclin_y = inclin_file['y'] \n \n\n if stepper_index_num >= stepper_len - 2:\n next_file_num = stepper_file['filenames'][1]\n next_file = str(next_file_num)\n stepper_index_num = 0\n \n \n file_path = \"/home/user/tim-daq/data/\"+datestamp+\"-Stepper/\"+\"*\"+next_file.zfill(5)+\"*\"\n while glob.glob(file_path) == []:\n time.sleep(0.05) \n stepper_file.close()\n stepper_file = h5py.File(glob.glob(file_path)[0], 'r', libver = 'latest', swmr = True)\n stepper_az = stepper_file['az']\n stepper_el = stepper_file['el']\n stepper_len = stepper_az.shape[0]\n \n \n\n","sub_path":"HDF5_calculations.py","file_name":"HDF5_calculations.py","file_ext":"py","file_size_in_byte":8719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"469169186","text":"# uncompyle6 version 3.6.7\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: /home/jesse/code/confab/confab/tests/data/default/example.py\n# Compiled at: 2013-05-14 18:47:53\nenvironmentdefs = {'environment1': [\n 'host1', 'host2']}\nroledefs = {'role1': [\n 'host1']}\ncomponentdefs = {'role1': [\n 'component1']}","sub_path":"pycfiles/confapp-1.1.11-py3-none-any/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"53309350","text":"\"Helper functions for runfiles\"\n\ndef CopyRunfiles(ctx, runfiles, copy, symlink, executable, subdir):\n \"\"\"Copies all runfile to the same directory and returns new runfiles \n\n Args:\n ctx: [DotnetContext](api.md#DotnetContext)\n runfiles: depset(File) to copy to target directory of executable\n copy: target for utility copy tool\n symlink: target for utility symlink tool\n executable: [DotnetLibrary](api.md#DotnetLibrary) which directory is used as a base dir for the runfiles\n subdir: additional subdirectory to copy files to\n\n Returns:\n [runfiles](https://docs.bazel.build/versions/master/skylark/lib/runfiles.html)\n \"\"\"\n copied = {}\n created = []\n nocopy_dir = executable.result.dirname\n for f in runfiles.files.to_list():\n found = copied.get(f.basename)\n if found:\n continue\n copied[f.basename] = True\n\n if f.basename == \"mono\" or f.basename == \"mono.exe\":\n newfile = ctx.actions.declare_file(subdir + f.basename)\n ctx.actions.run(\n outputs = [newfile],\n inputs = [f] + symlink.files.to_list(),\n executable = symlink.files.to_list()[0],\n arguments = [newfile.path, f.path],\n mnemonic = \"LinkFile\",\n )\n created.append(newfile)\n elif f.dirname != nocopy_dir:\n if f.basename.find(\"hostfxr\") >= 0:\n version = f.path.split(\"/\")\n newfile = ctx.actions.declare_file(\"{}/host/fxr/{}/{}\".format(subdir, version[-2], version[-1]))\n else:\n newfile = ctx.actions.declare_file(subdir + f.basename)\n ctx.actions.run(\n outputs = [newfile],\n inputs = [f] + copy.files.to_list(),\n executable = copy.files.to_list()[0],\n arguments = [newfile.path, f.path],\n mnemonic = \"CopyFile\",\n )\n created.append(newfile)\n else:\n created.append(f)\n\n return ctx.runfiles(files = created)\n\ndef CopyDataWithDirs(dotnet, data_with_dirs, copy, subdir):\n \"\"\" Handles data targets provided with directories. Returns runfiles.\n\n Args:\n dotnet: DotnetContextInfo provider\n data_with_dirs: dict(Taret, string)\n copy: program to use for copying files\n subdir: subdirectory to use when placing provider data files\n\n Returns:\n [runfiles](https://docs.bazel.build/versions/master/skylark/lib/runfiles.html)\n\n \"\"\"\n copied = {}\n created = []\n for (k, v) in data_with_dirs.items():\n for f in k.files.to_list():\n targetpath = subdir + \"/\" + v + \"/\" + f.basename\n found = copied.get(targetpath)\n if found:\n continue\n copied[targetpath] = True\n\n newfile = dotnet.actions.declare_file(targetpath)\n dotnet.actions.run(\n outputs = [newfile],\n inputs = [f] + copy.files.to_list(),\n executable = copy.files.to_list()[0],\n arguments = [newfile.path, f.path],\n mnemonic = \"CopyFile\",\n )\n created.append(newfile)\n\n return dotnet._ctx.runfiles(files = created)\n","sub_path":"dotnet/private/rules/runfiles.bzl","file_name":"runfiles.bzl","file_ext":"bzl","file_size_in_byte":3263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"298278969","text":"import pandas as pd\nimport json\n\nfilename='zone5'\ninfo = json.load(open(filename))\n\ntab=pd.read_csv('eplusout.csv')\n\n# solar radiation\t\nsol=[]\nfor key in info[\"solar\"]:\n sol.append(info[\"solar\"][key])\n\n# zone information\nzones=[]\nfor key in sorted(info[\"inputs\"][\"zones\"]):\n zones.append(info[\"inputs\"][\"zones\"][key])\n\nadjzones=[]\nfor key in sorted(info[\"inputs\"][\"adjzones\"]):\n adjzones.append(info[\"inputs\"][\"adjzones\"][key])\n \n# terminal information\ntermoutlet=[]\nfor key in sorted(info[\"inputs\"][\"termoutlet\"]):\n termoutlet.append(info[\"inputs\"][\"termoutlet\"][key])\n \n\ntout=info[\"tout\"]\n#hsp=info[\"hsp\"]\n\n\nzmt=[]\nadjt=[]\nzmdm=[] # zone supply air flow rate\nzmdt=[] # zone supply air temperature\nint=[] # internal load\ninlet=[] # reheat coil inlet water temperature\noutlet=[] # reheat coil outlet water temperature\nmrh=[] # reheat coil water mass flow rate\n#rh=[]\n#sol=['Environment:Site Diffuse Solar Radiation Rate per Area [W/m2](TimeStep)','Environment:Site Direct Solar Radiation Rate per Area [W/m2](TimeStep)']\nfor i in range(len(zones)):\n zmt.append(str(zones[i]).upper()+':Zone Mean Air Temperature [C](TimeStep)')\n int.append(str(zones[i]).upper()+':Zone Total Internal Total Heating Rate [W](TimeStep)')\n zmdm.append(str(termoutlet[i]).upper()+':System Node Mass Flow Rate [kg/s](TimeStep)')\n zmdt.append(str(termoutlet[i]).upper()+':System Node Temperature [C](TimeStep)')\n# inlet.append(str(rhtinlet[i]).upper()+':System Node Temperature [C](TimeStep)')\n# outlet.append(str(rhtoutlet[i]).upper()+':System Node Temperature [C](TimeStep)')\n# mrh.append(str(rhtoutlet[i]).upper()+':System Node Mass Flow Rate [kg/s](TimeStep)')\n #rh.append(str(zones[i]).upper()+' RHT COIL:Heating Coil Heating Rate [W](TimeStep)')\nfor i in range(len(adjzones)):\n adjt.append(str(adjzones[i]).upper()+':Zone Mean Air Temperature [C](TimeStep)')\n\ntab['t1']=[0]*len(tab)\ntab['m1']=[0]*len(tab)\ntab['i']=[0]*len(tab)\ntab['s']=[0]*len(tab)\ntab['adjt']=[0]*len(tab)\n\nfor i in range(len(zones)):\n tab['t1']=tab['t1']+tab[zmt[i]]*tab[zmdm[i]]\n tab['i']=tab['i']+tab[int[i]]\n tab['m1']=tab['m1']+tab[zmdm[i]]\n\nfor i in range(len(adjzones)):\n tab['adjt']=tab['adjt']+tab[adjt[i]]\n\nfor i in range(len(sol)):\t\n tab['s']=tab['s']+tab[sol[i]]\t\n\t\n\t\ntab2=pd.DataFrame()\n\n#for j in range(len(walls)):\n# tab2['w'+str(j)]=tab['w'+str(j+1)]\ntab2['tout']=tab[tout]\ntab2['s']=tab['s']\ntab2['i']=tab['i']\ntab2['t1']=tab['t1']/tab['m1']\n\n# adjacent zone temperatures\ntab2['t2']=(tab[adjt[0]]+tab[adjt[1]]+tab[adjt[2]]+tab[adjt[3]])/4\ntab2['t3']=tab[adjt[4]]\n#tab2['t2']=tab['adjt']/5\n#for i in range(len(adjzones)):\n# name='t'+str(i+2)\n# tab2[name]=tab[adjt[i]]\n\n\ntab2['m']=tab[zmdm[0]]\ntab2['tret']=tab[zmdt[0]]\n #name='rh'+str(i)\n #tab2[name]=tab[mrh[i]]*(tab[inlet[i]]-tab[outlet[i]])*4200\n#tab2['rh']=tab['rh']\n\n\n\ntab2.to_csv(filename+'rawdata.csv')\n","sub_path":"office/winter/option4/sine_sp/data_process_plenum_o31.py","file_name":"data_process_plenum_o31.py","file_ext":"py","file_size_in_byte":2919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"32049110","text":"import tensorflow as tf\nfrom tensorflow.contrib import slim\n\nfrom .base_model import BaseModel, Mode\nfrom .backbones import resnet_v1 as resnet\n\n\ndef normalize_image(image, pixel_value_offset=128.0, pixel_value_scale=128.0):\n return tf.div(tf.subtract(image, pixel_value_offset), pixel_value_scale)\n\n\nclass Delf(BaseModel):\n input_spec = {\n 'image': {'shape': [None, None, None, None], 'type': tf.float32}\n }\n required_config_keys = []\n default_config = {\n 'normalize_input': False,\n 'use_attention': False,\n 'attention_kernel': 1,\n 'normalize_average': True,\n 'normalize_feature_map': True\n }\n\n def _model(self, inputs, mode, **config):\n image = inputs['image']\n if image.shape[-1] == 1:\n image = tf.tile(image, [1, 1, 1, 3])\n if config['normalize_input']:\n image = normalize_image(image)\n\n with slim.arg_scope(resnet.resnet_arg_scope()):\n _, encoder = resnet.resnet_v1_50(image,\n is_training=(mode == Mode.TRAIN),\n global_pool=False,\n scope='resnet_v1_50')\n feature_map = encoder['resnet_v1_50/block3']\n\n if config['use_attention']:\n with tf.variable_scope('attonly/attention/compute'):\n with slim.arg_scope(resnet.resnet_arg_scope()):\n with slim.arg_scope([slim.batch_norm],\n is_training=(mode == Mode.TRAIN)):\n attention = slim.conv2d(\n feature_map, 512, config['attention_kernel'], rate=1,\n activation_fn=tf.nn.relu, scope='conv1')\n attention = slim.conv2d(\n attention, 1, config['attention_kernel'], rate=1,\n activation_fn=None, normalizer_fn=None, scope='conv2')\n attention = tf.nn.softplus(attention)\n if config['normalize_feature_map']:\n feature_map = tf.nn.l2_normalize(feature_map, -1)\n descriptor = tf.reduce_sum(feature_map*attention, axis=[1, 2])\n if config['normalize_average']:\n descriptor /= tf.reduce_sum(attention, axis=[1, 2])\n else:\n descriptor = tf.reduce_max(feature_map, [1, 2])\n\n return {'descriptor': descriptor}\n\n def _loss(self, outputs, inputs, **config):\n raise NotImplementedError\n\n def _metrics(self, outputs, inputs, **config):\n raise NotImplementedError\n","sub_path":"retrievalnet/retrievalnet/models/delf.py","file_name":"delf.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"513663505","text":"\"\"\"15-8. Три кубика: при броске 3 кубиков D6 наименьший возможный результат равен 3,\nа наибольший — 18. Создайте визуализацию, которая показывает, что происходит при бро-\nске трех кубиков D6.\"\"\"\nimport pygal\nfrom die import Die\n\n# Создание двух кубиков D8.\ndie_1 = Die()\ndie_2 = Die()\ndie_3 = Die()\n\n# Моделирование серии бросков с сохранением результатов в списке.\nresults = []\nfor roll_num in range(1000):\n result = die_1.roll() + die_2.roll() + die_3.roll()\n results.append(result)\n\n# Анализ результатов.\nfrequencies = []\nmax_result = die_1.num_sides + die_2.num_sides + die_3.num_sides\nfor value in range(3, max_result + 1):\n frequency = results.count(value)\n frequencies.append(frequency)\n\n# Визуализация результатов.\nhist = pygal.Bar()\nhist.title = \"Results of rolling three D6 dice 1000 times.\"\nhist.x_labels = [str(i) for i in range(3, 19)]\nhist.x_title = \"Result\"\nhist.y_title = \"Frequency of Result\"\nhist.add('D6 + D6 + D6', frequencies)\nhist.render_to_file('three_visual.svg')\n","sub_path":"Мэтиз: Изучаем Python/projects/visual_data/pygal/15-8/three_visual.py","file_name":"three_visual.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"614251158","text":"from argparse import ArgumentParser\nfrom dataclasses import dataclass, field\nfrom typing import Sequence, Mapping, Union, ClassVar\nimport json\nfrom collections import OrderedDict\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport os\nimport cflowpost.plotting as cfplot\n\n\nCONFIG_DIR = \"config\"\nPLOT_FORMAT_JSON = \"plot_format.json\"\nPOSITIONS_JSON = \"positions.json\"\nVARIABLES_JSON = \"variables.json\"\n\n\n@dataclass\nclass CaseComparisonPlotter:\n case_dir: str\n plot_format: OrderedDict\n positions: OrderedDict[str, str]\n variables: OrderedDict\n basewidth: float = field(default=2., repr=False)\n baseheight: float = field(default=2.2, repr=False)\n sharex: Union[str, bool] = field(default=\"col\", repr=False)\n sharey: str = field(default=\"row\", repr=False)\n tight_layout: bool = field(default=True, repr=False)\n base_fontsize: float = field(default=10, repr=False)\n _model_color_key: ClassVar[str] = \"Model colors\"\n _experimental_color_key: ClassVar[str] = \"Experimental color\"\n _markevery_key: ClassVar[str] = \"markevery\"\n _xlim_key: ClassVar[str] = \"xlim\"\n _xlabel_key: ClassVar[str] = \"xlabel\"\n\n def __post_init__(self):\n cls = CaseComparisonPlotter\n self.plot_format.setdefault(\n cls._experimental_color_key, \"tab:olive\")\n self.plot_format.setdefault(cls._markevery_key, None)\n self.plot_format.setdefault(cls._xlim_key, None)\n self.plot_format.setdefault(cls._xlabel_key, None)\n\n def create_figure(self):\n nrows, ncols = len(self.variables), len(self.positions)\n figsize = (ncols*self.basewidth, nrows*self.baseheight)\n return plt.subplots(nrows, ncols,\n figsize=figsize,\n sharex=self.sharex,\n sharey=self.sharey,\n tight_layout=self.tight_layout)\n\n def read_data(self):\n models = self.plot_format[\"models\"]\n positions = self.positions.keys()\n models = [os.path.join(self.case_dir, model) for model in models]\n experimental = os.path.join(self.case_dir,\n self.plot_format[\"experimental\"])\n model_paths_by_position = OrderedDict(\n {position: [os.path.join(model, position) for model in models]\n for position in positions})\n model_data_map = {\n position: [pd.read_csv(path)\n for path in model_paths_by_position[position]]\n for position in positions}\n exp_data_map = {\n position: pd.read_csv(os.path.join(experimental, position))\n for position in positions}\n return model_data_map, exp_data_map\n\n def plot(self, ):\n model_data_map, exp_data_map = self.read_data()\n fig, axs = self.create_figure()\n positions = list(self.positions.keys())\n y_variables = list(self.variables.keys())\n model_labels = self.plot_format[\"models\"]\n experimental_label = self.plot_format[\"experimental\"]\n x_var_key = self.plot_format[\"x_var\"]\n xlabel = self.plot_format[self.__class__._xlabel_key]\n xlabel = xlabel if xlabel is not None else x_var_key\n exp_color = self.plot_format[self.__class__._experimental_color_key]\n markevery = self.plot_format[self.__class__._markevery_key]\n xlim = self.plot_format[self.__class__._xlim_key]\n for position, ax in zip(positions, axs[0]):\n ax.set_title(self.positions[position],\n fontsize=self.base_fontsize*1.5)\n for y_var_key, axs_row in zip(y_variables, axs):\n for position, ax in zip(positions, axs_row):\n model_frames = model_data_map[position]\n experimental_frame = exp_data_map[position]\n self._plot_single_ax(model_frames=model_frames,\n experimental_frame=experimental_frame,\n x_var_key=x_var_key,\n y_var_key=y_var_key,\n model_labels=model_labels,\n exp_label=experimental_label,\n exp_color=[exp_color],\n markevery=markevery,\n xlim=xlim,\n ax=ax)\n axs_row[0].set_ylabel(self.variables[y_var_key],\n fontsize=self.base_fontsize * 1.4)\n for ax in axs[-1]:\n ax.set_xlabel(xlabel, fontsize=self.base_fontsize*1.4)\n axs[0][-1].legend()\n fig.align_ylabels()\n return fig, axs\n\n @staticmethod\n def _plot_single_ax(\n model_frames,\n experimental_frame,\n x_var_key,\n y_var_key,\n model_labels,\n exp_label,\n exp_color,\n markevery,\n xlim=None,\n ax=None,):\n if ax is None:\n fig, ax = plt.subplots(1, 1)\n x_var_series = np.column_stack([data[x_var_key].to_numpy()\n for data in model_frames])\n y_var_series = np.column_stack([data[y_var_key].to_numpy()\n for data in model_frames])\n x_exp_series = experimental_frame[x_var_key]\n y_exp_series = experimental_frame[y_var_key]\n plotter = cfplot.NumericalValidation1DPlotter(num_x=x_var_series,\n num_y=y_var_series,\n exp_x=x_exp_series,\n exp_y=y_exp_series,\n num_labels=model_labels,\n exp_labels=exp_label,\n exp_colors=exp_color,\n markevery=markevery,\n legend=False)\n plotter.plot(ax=ax)\n if xlim is not None:\n ax.set_xlim(*xlim)\n return\n\n\ndef read_json_as_ordereddict(fileloc):\n with open(fileloc, \"r\") as f:\n return json.loads(f.read(), object_pairs_hook=OrderedDict)\n\n\ndef parse_args():\n parser = ArgumentParser()\n parser.add_argument(\"-c\", \"--case-dir\",\n default=\".\",\n help=\"Path to case directory.\")\n parser.add_argument(\"--dpi\", type=float, default=220)\n return parser.parse_args()\n\n\ndef main():\n args = parse_args()\n run(case_dir=args.case_dir, dpi=args.dpi)\n\n\ndef run(case_dir, dpi, **kwargs):\n config_dir = os.path.join(case_dir, CONFIG_DIR)\n json_files = (PLOT_FORMAT_JSON, POSITIONS_JSON, VARIABLES_JSON)\n json_files = [os.path.join(config_dir, file) for file in json_files]\n plot_format, positions, variables = [read_json_as_ordereddict(file)\n for file in json_files]\n plotter = CaseComparisonPlotter(plot_format=plot_format,\n case_dir=case_dir,\n positions=positions,\n variables=variables,\n **kwargs)\n fig, axs = plotter.plot()\n output_file = os.path.join(case_dir, \"plot.png\")\n fig.savefig(output_file, dpi=dpi)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"thesis-main/bin/thesis-chapter4-figures/bin/plot_radial_profile_comparison.py","file_name":"plot_radial_profile_comparison.py","file_ext":"py","file_size_in_byte":7524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"324075815","text":"# How to use VS Code debugger with Locust\nimport locust_plugins.utils\n\nlocust_plugins.utils.gevent_debugger_patch()\nfrom locust_plugins.listeners import PrintListener\nfrom locust import task, TaskSet\nfrom locust.wait_time import constant\nfrom locust.contrib.fasthttp import FastHttpLocust\n\n\nclass UserBehavior(TaskSet):\n @task\n def my_task(self):\n self.client.get(\"/\")\n\n\nclass MyHttpLocust(FastHttpLocust):\n task_set = UserBehavior\n wait_time = constant(1)\n if __name__ == \"__main__\":\n host = \"https://www.example.com\"\n\n\n# allow running as executable, to support attaching the debugger\nif __name__ == \"__main__\":\n PrintListener()\n MyHttpLocust._catch_exceptions = False\n MyHttpLocust().run()\n","sub_path":"examples/debug.py","file_name":"debug.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"134988469","text":"# -*- coding: utf-8 -*-\nfrom utilities.logs import get_logger\nfrom proof.apis import APP_DB\n\nlog = get_logger(__name__)\n\n\nclass Initializer(object):\n def __init__(self, services):\n if APP_DB == 'rapydo_tests':\n mongo = services.get('mongo')\n mongo.Article.objects.all().delete()\n\n import nltk\n nltk.download('punkt')\n\n\n\"\"\"\nclass Customizer(object):\n\n def custom_user_properties(self, properties):\n\n log.pp(properties)\n # properties[\"irods_cert\"] = get_random_name(len=12)\n return properties\n\n def custom_post_handle_user_input(self, auth, user_node, properties):\n\n print(\"TEST\", auth, user_node, properties)\n return True\n\n try:\n group = auth.db.Group.nodes.get(shortname=\"default\")\n except auth.db.Group.DoesNotExist:\n log.warning(\"Unable to find default group, creating\")\n group = auth.db.Group()\n group.fullname = \"Default user group\"\n group.shortname = \"default\"\n group.save()\n\n log.info(\"Link %s to group %s\", user_node.email, group.shortname)\n user_node.belongs_to.connect(group)\n\n return True\n\"\"\"\n\n\n\n\n\n","sub_path":"projects/proof/backend/initialization/initialization.py","file_name":"initialization.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"7040324","text":"# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n\n\nfrom libmozdata.bugzilla import BugzillaProduct\n\nfrom auto_nag.bzcleaner import BzCleaner\nfrom auto_nag.nag_me import Nag\nfrom auto_nag.team_managers import TeamManagers\nfrom auto_nag.user_activity import UserActivity\n\n\nclass TriageOwnerVacant(BzCleaner, Nag):\n def __init__(self):\n super(TriageOwnerVacant, self).__init__()\n self.query_url = None\n self.inactive_weeks_number = self.get_config(\"inactive_weeks_number\", 26)\n\n def description(self):\n return \"Components with triage owner need to be assigned\"\n\n def fetch_products(self):\n data = []\n include_fields = [\n \"name\",\n \"is_active\",\n \"components.id\",\n \"components.name\",\n \"components.team_name\",\n \"components.triage_owner\",\n \"components.is_active\",\n ]\n\n def product_handler(product, data):\n data.append(product)\n\n BugzillaProduct(\n product_names=self.get_products(),\n include_fields=include_fields,\n product_handler=product_handler,\n product_data=data,\n ).wait()\n\n return data\n\n def nag_template(self):\n return self.template()\n\n def identify_vacant_components(self):\n # Filter out products and components that are not active\n products = [\n {\n **product,\n \"components\": [\n component\n for component in product[\"components\"]\n if component[\"is_active\"]\n ],\n }\n for product in self.fetch_products()\n if product[\"is_active\"]\n ]\n\n triage_owners = set()\n for product in products:\n for component in product[\"components\"]:\n triage_owners.add(component[\"triage_owner\"])\n\n user_activity = UserActivity(self.inactive_weeks_number)\n inactive_users = user_activity.check_users(triage_owners)\n\n team_managers = TeamManagers()\n vacant_components = []\n for product in products:\n for component in product[\"components\"]:\n triage_owner = component[\"triage_owner\"]\n if triage_owner not in inactive_users:\n continue\n\n manager = team_managers.get_team_manager(component[\"team_name\"])\n\n info = {\n \"id\": component[\"id\"],\n \"manager\": manager[\"name\"],\n \"team\": component[\"team_name\"],\n \"product\": product[\"name\"],\n \"component\": component[\"name\"],\n \"triage_owner\": triage_owner,\n \"status\": user_activity.get_string_status(\n inactive_users[triage_owner][\"status\"]\n ),\n }\n\n vacant_components.append(info)\n self.add(manager[\"mozilla_email\"], info)\n\n return vacant_components\n\n def get_email_data(self, date, bug_ids):\n return self.identify_vacant_components()\n\n def organize_nag(self, data):\n return data\n\n def get_cc(self):\n return set()\n\n\nif __name__ == \"__main__\":\n TriageOwnerVacant().run()\n","sub_path":"auto_nag/scripts/vacant_triage_owner.py","file_name":"vacant_triage_owner.py","file_ext":"py","file_size_in_byte":3443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"210647384","text":"import json\nimport os\nfrom datetime import timedelta\nfrom functools import wraps\n\nfrom flask import Flask, request\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate, MigrateCommand\n\nfrom flask_jwt_extended import JWTManager, verify_jwt_in_request, get_jwt_claims\n\nfrom flask_script import Manager\n\n#using flask-cors to solve all the problems?\nfrom flask_cors import CORS\n\napp = Flask(__name__) # app.root location\nCORS(app)\n\n#not disabling loading .env\n#fadhil using dotenv for not hard-coding database URL\nfrom dotenv import load_dotenv\nfrom pathlib import Path # python3 only\nenv_path = Path('.') / '.envdummy'\nload_dotenv(dotenv_path=env_path)\nusername = os.getenv('DATABASE_USER')\npassword = os.getenv('DATABASE_PASSWORD')\nhostport = os.getenv('DATABASE_URL')\nname = os.getenv('DATABASE_NAME')\n\n\n#jwt secret, generated from random.org\n#regenerated for final project\napp.config['JWT_SECRET_KEY'] = 'bsNb0Tne6KMuuy6zE8M6ekjWaHb2XOKL'\napp.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(days=1)\n\njwt = JWTManager(app)\n\n#declare wrapper for admin, user-specific cases\ndef admin_required(fn):\n @wraps(fn)\n def wrapper(*args, **kwargs):\n verify_jwt_in_request()\n claims= get_jwt_claims()\n if not claims['isadmin']:\n return {'status': 'FORBIDDEN', 'message': 'Admin Only!'}, 403\n else:\n return fn(*args, **kwargs)\n return wrapper\n\ndef user_required(fn):\n @wraps(fn)\n def wrapper(*args, **kwargs):\n verify_jwt_in_request()\n claims= get_jwt_claims()\n if claims['isadmin']:\n return {'status': 'FORBIDDEN', 'message': 'User Only!'}, 403\n else:\n return fn(*args, **kwargs)\n return wrapper\n\n#################### TESTING\n# try:\n# env = os.environ.get('FLASK_ENV', 'development') #nama, default\n# if env == 'testing':\n# app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:JalanTidarno.23@localhost:3306/restDB_test'\n# else:\n# app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:JalanTidarno.23@localhost:3306/restDB'\n# except Exception as e:\n# raise e\n\n##### HARUS DI ATAS ##########\n\napp.config['APP_DEBUG'] = True\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://{db_user}:{db_pass}@{db_host_port}/{db_name}'.format(db_user=username,db_pass=password,db_host_port=hostport,db_name=name)\n##.format(os.getenv(\"DATABASE_USER\"),os.getenv(\"DATABASE_PASSWORD\"),os.getenv(\"DATABASE_HOST_PORT\"),os.getenv(\"DATABASE_NAME\"))\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb = SQLAlchemy(app)\nmigrate = Migrate(app, db)\nmanager = Manager(app)\nmanager.add_command('db', MigrateCommand)\n\n########## MIDDLEWARE #############\n\n\n@app.after_request\ndef after_request(response):\n try:\n requestData = request.get_json()\n except Exception as e:\n requestData = request.args.to_dict()\n if response.status_code == 200:\n app.logger.info(\"REQUEST_LOG\\t%s\", json.dumps({ \n 'status_code': response.status_code, # ini ngebuat 400 gak bisa masuk \n 'request': requestData, 'response': json.loads(response.data.decode('utf-8'))}))\n else:\n app.logger.error(\"REQUEST_LOG\\t%s\", json.dumps({ \n 'status_code': response.status_code,\n 'request': requestData, 'response': json.loads(response.data.decode('utf-8'))}))\n\n return response\n\n##add blueprint here\nfrom blueprints.user.resources import bp_user\napp.register_blueprint(bp_user, url_prefix='/users')\n\nfrom blueprints.auth import bp_auth\napp.register_blueprint(bp_auth, url_prefix='/auth')\n\nfrom blueprints.tag.resources import bp_tag\napp.register_blueprint(bp_tag, url_prefix='/tags')\n\nfrom blueprints.posting.resources import bp_posting\napp.register_blueprint(bp_posting, url_prefix='/posting')\n\nfrom blueprints.upload import bp_upload\napp.register_blueprint(bp_upload, url_prefix='/upload')\n\nfrom blueprints.point.resources import bp_point\napp.register_blueprint(bp_point, url_prefix='/point')\n\nfrom blueprints.admin import bp_admin\napp.register_blueprint(bp_admin, url_prefix='/admin')\n\nfrom blueprints.notification.resources import bp_nofity\napp.register_blueprint(bp_nofity, url_prefix='/notification')\n\ndb.create_all()","sub_path":"blueprints/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"450358517","text":"import sys\nimport re\nfrom collections import defaultdict\n\nwords = defaultdict(bool)\n\ndef get_words():\n global possible_tags\n training = open(sys.argv[1], 'r')\n line = training.readline()\n while line:\n l = line.strip()\n if l:\n vals = l.split(' ')\n words[vals[0]] = True\n line = training.readline()\n\ndef convert():\n data = open(sys.argv[2], 'r')\n out = open(sys.argv[3], 'w')\n line = data.readline()\n firstCaps = re.compile('[A-Z].+')\n AllCaps = re.compile('[A-Z]+$')\n startNumerals = re.compile('\\d+')\n allCapsWithDot = re.compile('[A-Z]+\\.[A-Z]+$')\n phoneNumber = re.compile('\\d\\d\\d.\\d\\d\\d.\\d\\d\\d\\d')\n location = re.compile('[A-Z][a-z][a-z][a-z][a-z][a-z][a-z]+$')\n while line:\n l = line.strip()\n if l:\n vals = l.split(' ')\n word = vals[0]\n if not words.get(word, False):\n if AllCaps.match(word):\n word = \"_AllCaps_\"\n elif location.match(word):\n word = \"_location_\"\n elif allCapsWithDot.match(word):\n word = \"_allCapsWithDot_\"\n elif firstCaps.match(word):\n word = \"_firstCaps_\"\n elif phoneNumber.match(word):\n word = \"_phoneNumber_\"\n elif startNumerals.match(word):\n word = \"_startNumerals_\"\n else:\n word = \"_RARE_\"\n out.write('{0} '.format(word))\n for i in range(1,len(vals)-1):\n out.write('{0} '.format(vals[i]))\n if not len(vals) == 1:\n out.write('{0}'.format(vals[len(vals)-1]))\n out.write('\\n')\n line = data.readline()\n\nget_words()\nconvert()\n","sub_path":"testing/original_code/rare_specific_conversion.py","file_name":"rare_specific_conversion.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"159106922","text":"#!/usr/bin/python3\n#My old and obsolete checker -- options are just too messy\n#Copyright Adamos - MIT license\nimport os\nimport sys, getopt\n\nimport subprocess\n\nimport zipfile\n\nimport colorful\nfrom shutil import copyfile\nimport time\nimport json\n\nuserName =\"\"\nselectedTask =\"\"\nselectedFile =\"\"\npauseOnWA = False\ndef main(argv):\n\n conFile = open(\"config.txt\")\n global userName, selectedTask, selectedFile\n userName = conFile.readline().rstrip()\n selectedTask = conFile.readline().rstrip()\n selectedFile = conFile.readline().rstrip()\n greet()\n try:\n opts, args = getopt.getopt(argv, \"n:,r:,l:,d,a:,p,z:,t:,f:,u:,c,e,g:,s:,F\", [\"pause\", \"files\", \"tasks\", \"done\"])\n except getopt.GetoptError:\n print(\"Use -h for help\")\n sys.exit(2)\n \n for opt, arg in opts:\n if opt == '-l':\n x = arg.split(',')\n runLocal(x[0], x[1])\n if opt == '-p':\n print(\"Available packs:\")\n for a in listDirs(\"./tasks/\" + selectedTask + \"/pack\"):\n print(a)\n if opt == '-a':\n print(colorful.red(\"Running on all packs!\"))\n print(\"Comparing with \" + arg +\"'s results\")\n for a in listDirs(\"./tasks/\" + selectedTask + \"/pack\"):\n runLocal(a, arg)\n if opt == '-z':\n unpackZIP(arg)\n if(opt == '-n'):\n createNewTask(arg)\n if(opt == '-r'):\n runSolution(arg)\n if(opt == '-t'):\n if arg:\n selectedTask = arg\n saveConfig()\n if(opt == '-u'):\n userName = arg\n saveConfig()\n if(opt == '-f'):\n selectedFile = arg\n saveConfig()\n if(opt == \"-c\"):\n compileFile(selectedFile)\n if(opt == '-e'):\n subprocess.call(\"geany.bat \" + \"./tasks/\"+selectedTask + \"/src/\" + selectedFile + \".cpp\")\n if(opt == '-g'):\n if not os.path.exists(\"./tasks/\" + selectedTask + \"/pack/\" + arg):\n os.makedirs(\"./tasks/\" + selectedTask + \"/pack/\" + arg)\n copyfile(\"./template/compare.txt\", \"./tasks/\"+selectedTask + \"/pack/\" + arg + \"/compare.txt\")\n if not os.path.exists(\"./tasks/\" + selectedTask + \"/pack/\" + arg + \"/in\"):\n os.makedirs(\"./tasks/\" + selectedTask + \"/pack/\" + arg + \"/in\")\n copyfile(\"./template/gen.sh\", \"./tasks/\"+selectedTask + \"/pack/\" + arg + \"/gen.sh\")\n if(opt == '-s'):\n x = arg.split(',')\n fileFromTemplate(x[0], x[1])\n if(opt == '-F'):\n x = [i for i in listDirs('./template') if i.find('.cpp') != -1]\n for i in x:\n print(i)\n if(opt == '--pause'):\n global pauseOnWA\n pauseOnWA = True\n if(opt == '--files'):\n x = [i for i in listDirs(\"./tasks/\" + selectedTask + \"/src/\") if i.find('.cpp') != -1]\n for i in x:\n print(i)\n if(opt == '--tasks'):\n print(colorful.green(\"Available tasks\"))\n for a in listDirs(\"./tasks\"):\n s_file = open(\"./tasks/\" + a + \"/status.json\")\n task_info = json.load(s_file)\n print(a + \" \" + colorful.green(task_info['done']))\n if(opt == '--done'):\n s_file = open(\"./tasks/\" + selectedTask + \"/status.json\", \"r\")\n task_info = json.load(s_file)\n s_file.close()\n task_info['done'] = 'OK'\n s_file = open(\"./tasks/\" + selectedTask + \"/status.json\", \"w\")\n json.dump(task_info, s_file, indent=4)\n\ndef greet():\n print(\"Task checker by Adamos\")\n print(colorful.red(\"username: \") + userName)\n print(colorful.red(\"selected Task: \") + selectedTask)\n print(colorful.red(\"selected Executable: \") + selectedFile)\n print()\n\ndef saveConfig():\n conf = open(\"config.txt\", \"w+\")\n conf.write(userName + \"\\n\")\n conf.write(selectedTask + \"\\n\")\n conf.write(selectedFile)\n greet()\n\ndef fileFromTemplate(fileName, templateName):\n copyfile(\"./template/\" + templateName + \".cpp\", \"./tasks/\" + selectedTask + \"/src/\" + fileName + \".cpp\")\n\ndef createNewTask(taskName):\n print(colorful.green(\"Creating task \" + taskName))\n if not os.path.exists(\"./tasks/\"+taskName):\n os.makedirs(\"./tasks/\"+taskName)\n else:\n print(colorful.red(\"This task already exists\"))\n print(\"Choose a different name\")\n sys.exit()\n if not os.path.exists(\"./tasks/\"+taskName + \"/bin\"):\n os.makedirs(\"./tasks/\"+taskName + \"/bin\")\n if not os.path.exists(\"./tasks/\"+taskName + \"/pack\"):\n os.makedirs(\"./tasks/\"+taskName + \"/pack\")\n if not os.path.exists(\"./tasks/\"+taskName + \"/src\"):\n os.makedirs(\"./tasks/\"+taskName + \"/src\")\n copyfile(\"./template/template.cpp\", \"./tasks/\" + taskName + \"/src/\" + taskName + \".cpp\")\n copyfile(\"./template/status.json\", \"./tasks/\" + taskName + \"/status.json\")\n\n\ndef compileFile(fileName):\n print(colorful.red(\"Compiling \" + fileName + \".cpp\"))\n tStart = time.time()\n subprocess.call(\"g++ -Wall -Wextra -std=c++11 -Wl,--stack,64000000 -O2 -static -I /utils/include -o \" + \" ./tasks/\" + selectedTask + \"/bin/\" + fileName + \".exe\" + \" ./tasks/\" + selectedTask + \"/src/\" + fileName +\".cpp\" )\n print(colorful.green(\"Took \" + str(time.time() - tStart)))\n\ndef unpackZIP(path):\n print(colorful.green(\"Unpacking tests from \" + path))\n zf = zipfile.ZipFile(path, 'r')\n zf.extractall(\"./tasks/\" + selectedTask + \"/pack\")\n zf.close()\n\ndef listDirs(path):\n dirList = os.listdir(path)\n sort_nicely(dirList)\n return dirList\n\ndef runSolution(packName):\n global selectedFile\n path = \"./tasks/\" + selectedTask + \"/pack/\" + packName\n if not os.path.exists(path + \"/out/\" + userName):\n os.makedirs(path + \"/out/\" + userName)\n\n print(colorful.orange(\"Generating outs for \" + packName + \": \" + selectedFile))\n for testFile in listDirs(path + \"/in\"):\n tStart = time.time() \n subprocess.call(\"./tasks/\" + selectedTask +\"/bin/\" + selectedFile, stdin=open(path + \"/in/\" + testFile), stdout=open(path + \"/out/\" + userName + \"/\" + testFile, mode=\"w+\"))\n print(colorful.green(testFile + \" took \" + str(time.time() - tStart)))\n\n\ndef runLocal(packName, compareTo):\n print(colorful.blue(\"Running testpack: \" + packName))\n path = \"./tasks/\" + selectedTask + \"/pack/\" + packName\n\n if not os.path.exists(path + \"/out/\" + userName):\n os.makedirs(path + \"/out/\" + userName)\n\n compareExe=\"\"\n compareFormat=\"\"\n cFile = open(\"./tasks/\" + selectedTask + \"/pack/\" + packName + \"/compare.txt\")\n c_comparator = cFile.readline().rstrip()\n comparators = json.load(open(\"./compare.json\"))\n print(c_comparator)\n for x in comparators:\n if(x['name'] == c_comparator):\n compareExe = \"./utils/\" + x['file']\n compareFormat = x['format']\n\n print(compareExe)\n for testFile in listDirs(path + \"/in\"):\n print(colorful.orange(\"TEST \" + testFile))\n compareArgs = [c_arg.replace(\"$in\", path + \"/in/\" + testFile).replace(\"$user_out\", path + \"/out/\" + userName + \"/\" + testFile).replace(\"$other_out\", path + \"/out/\" + compareTo + \"/\" + testFile) for c_arg in compareFormat.split()]\n \n if not os.path.isfile(path + \"/out/\" + userName + \"/\" + testFile):\n print(colorful.orange(\"Generating outs for \" + testFile))\n tStart = time.time()\n subprocess.call(\"./tasks/\" + selectedTask +\"/bin/\" + selectedFile, stdin=open(path + \"/in/\" + testFile), stdout=open(path + \"/out/\" + userName + \"/\" + testFile, mode=\"w+\"))\n print(colorful.yellow(testFile + \" took \" + str(time.time() - tStart)))\n\t\t\n outputVal = subprocess.run([compareExe] + compareArgs, stdout=subprocess.PIPE, encoding='utf8')\n if str(outputVal.stdout) == \"\":\n print(colorful.green(\"OK\"))\n else:\n print(colorful.red(\"WA\"))\n print(str(outputVal.stdout))\n if(pauseOnWA):\n xt = input()\n if(xt == \"0\"):\n sys.exit()\n\n#Better sorting of filenames with numbers\nimport re\n\ndef tryint(s):\n try:\n return int(s)\n except:\n return s\n\ndef alphanum_key(s):\n \"\"\" Turn a string into a list of string and number chunks.\n \"z23a\" -> [\"z\", 23, \"a\"]\n \"\"\"\n return [ tryint(c) for c in re.split('([0-9]+)', s) ]\n\ndef sort_nicely(l):\n \"\"\" Sort the given list in the way that humans expect.\n \"\"\"\n l.sort(key=alphanum_key)\n#end block\n\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":8630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"449316603","text":"def getAvailableLetters(lettersGuessed):\n '''\n lettersGuessed: list, what letters have been guessed so far\n returns: string, comprised of letters that represents what letters have not\n yet been guessed.\n '''\n # FILL IN YOUR CODE HERE...\n letters = []\n for i in range(97, 123):\n z = chr(i) #ASCII arithmetic to create a list which contains all the alphabetical characters\n letters.append(z) #inserting each character to letters[] list\n for letter in lettersGuessed:\n for index in letters:\n if letter == index:\n letters.remove(index)\n return ''.join(letters)\n","sub_path":"Problem_Set_3/printing_out_all_available_letters.py","file_name":"printing_out_all_available_letters.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"160090475","text":"# puzzle input\ninputFile = open(\"C:/Users/Natasha/Desktop/Advent-of-Code-2017/input_5.txt\", \"r\")\norigInput = inputFile.readlines()\norigInput = [int(line.rstrip()) for line in origInput]\ninputFile.close()\n\n# challenge part 1\ninput = origInput[:]\ncurrentPos = 0\nsteps = 0\nwhile currentPos < len(input):\n newPos = currentPos + input[currentPos]\n input[currentPos] += 1\n currentPos = newPos\n steps += 1\nprint(\"The number of steps it takes to reach the exit is:\", steps)\n\n# challenge part 2\ninput = origInput[:]\ncurrentPos = 0\nsteps = 0\nwhile currentPos < len(input):\n newPos = currentPos + input[currentPos]\n if input[currentPos] >= 3:\n input[currentPos] -= 1\n else:\n input[currentPos] += 1\n currentPos = newPos\n steps += 1\nprint(\"The number of steps it takes to reach the exit is now:\", steps)","sub_path":"Day 5.py","file_name":"Day 5.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"347459705","text":"# -*- coding: utf-8 -*-\nfrom django.http import HttpResponse # Importamos el modulo HttpResponse\nimport datetime\nfrom django.template import Template, Context\n\nclass Persona(object):\n\t\"\"\"docstring for Persona\"\"\"\n\tdef __init__(self, nombre, apellido):\n\t\tself.nombre = nombre\n\t\tself.apellido = apellido\n\n\ndef saludo(request): # primera vista\n\tp1 = Persona(\"Ing. José\", \"Gómez\")\n\t# nombre = \"José\"\n\t# apellido = \"Gómez\"\n\n\ttemas_del_curso = [\"Plantillas\", \"Modelos\", \"Formularios\", \"Vistas\", \"Despliegue\"]\n\n\tfecha_actual = datetime.datetime.now()\n\tdoc_externo = open(\"Proyecto1/template/template1.html\")\n\t\n\tplt = Template(doc_externo.read()) # Creacion de un objeto template\n\tdoc_externo.close() # Se cierra el documento para que no se consuman recursos innecesarios\n\n\tctx = Context({\"nombre_persona\": p1.nombre, \"apellido_persona\": p1.apellido, \"fecha_actual\": fecha_actual, \"temas\":temas_del_curso}) # Contexto se usa para pasar valores y funciones del template\n\n\tdocumento = plt.render(ctx)\n\treturn HttpResponse(documento)\n\ndef despedida(request): # Segunda vista\n\treturn HttpResponse(\"Una despedida al estilo de Django Fecha\")\n\ndef dameFecha(request): # Tercera vista\n\tfechaActual = datetime.datetime.now()\n\n\tdocumento = \"\"\"\n\t\n\t\n\t\n\t\t\n\t\tCurso de Django Pildora Informaticas\n\t\n\t\n\t\t

    Fecha y Hora Actuales %s

    \n\t\tEdades\n\t\n\t\n\t\"\"\" %fechaActual\n\n\treturn HttpResponse(documento)\n\ndef calculaEdad(request, edad, anio): # Cuarta vista\n\t# edadActual = 23\n\tperiodo = anio - 2019\n\tedadFutura = edad + periodo\n\n\tdocumento = \"\"\"\n\t\n\t\n\t\n\t\t\n\t\tCurso de Django Pildora Informaticas\n\t\n\t\n\t\t

    En el año %s tendras %s años

    \n\t\tSaludo\n\t\n\t\n\t\"\"\" %(anio, edadFutura)\n\n\treturn HttpResponse(documento)","sub_path":"3.VIDEO_7/Proyecto1/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"264879479","text":"from scipy.spatial import distance\nfrom matplotlib import pyplot as plt\n\n#method to compute error between numpy arrays with each row as tuple\ndef get_err( true_out, pred_out, plot=False ):\n if true_out.shape!=pred_out.shape :\n print(\"bad input dimensions to compute err: \",true_out.shape,pred_out.shape)\n\n aggreg_dist = 0\n\n for row_idx in range( len(true_out) ):\n true_point = tuple( true_out[ row_idx ] )\n pred_point = tuple( pred_out[ row_idx ] )\n curr_dist = distance.euclidean( true_point, pred_point )\n aggreg_dist += curr_dist if curr_dist > 0 else -curr_dist\n\n if plot:\n plt.plot( true_out[:,0],color=\"red\",label=\"true\" )\n plt.plot( pred_out[:,0],color=\"blue\",label=\"pred\" )\n plt.legend(loc='best')\n plt.show()\n #plt.show()\n #plt.plot( true_out[1] ) \n #plt.plot( pred_out[1] ) \n #plt.show()\n \n return aggreg_dist / len( true_out )\n\n","sub_path":"Fly_Brain_Analysis/predicting_neural_frame_analysis/generative_attempt_normal/err.py","file_name":"err.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"128843282","text":"class Solution:\n def findWords(self, words: List[str]) -> List[str]:\n if not words:\n return []\n\n rows = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm']\n output = []\n\n for w in words:\n for r in rows:\n if len(set(w.lower()) - set(r)) == 0:\n output.append(w)\n break\n\n return output","sub_path":"leetcode/keyboard_row.py","file_name":"keyboard_row.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"553841829","text":"import math\n\nMIN_LAT = math.radians(-90.0)\nMAX_LAT = math.radians(90.0)\nMIN_LON = math.radians(-180.0)\nMAX_LON = math.radians(180.0)\nEARTH_RADIUS = 6371.01\n\n\ndef bounding_coordinates(lat, lon, distance):\n \"\"\"\n Berechnung zweier Refernezpunkte die ein Rechteck ergeben,\n dass ungefähr einem Kreis mit Suchradius entspricht.\n\n siehe: http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates\n \"\"\"\n if distance <= 0:\n raise ValueError('distance must be greater than zero')\n dist_radians = distance / EARTH_RADIUS\n lat_radians = math.radians(lat)\n lon_radians = math.radians(lon)\n\n minLat = lat_radians - dist_radians\n maxLat = lat_radians + dist_radians\n\n if minLat > MIN_LAT and maxLat < MAX_LAT:\n deltaLon = math.asin(math.sin(dist_radians) / math.cos(lat_radians))\n minLon = lon_radians - deltaLon\n if minLon < MIN_LON:\n minLon += 2 * math.pi\n maxLon = lon_radians + deltaLon\n if maxLon > MAX_LON:\n maxLon -= 2 * math.pi\n else:\n minLat = max(minLat, MIN_LAT)\n maxLat = min(maxLat, MAX_LAT)\n minLon = MIN_LON\n maxLon = MAX_LON\n return (\n math.degrees(minLat), math.degrees(minLon),\n math.degrees(maxLat), math.degrees(maxLon)\n )\n\n\ndef normalize_lat(lat):\n while lat < -90.0:\n lat += 180.0\n while lat > 90.0:\n lat -= 180.0\n return lat\n\n\ndef normalize_lon(lon):\n while lon < -180.0:\n lon += 360.0\n while lon > 180.0:\n lon -= 360.0\n return lon\n","sub_path":"stimmungspegel/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"375531963","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n\nimport sys\n\nfrom flask import Flask\n\nfrom lib import db, login_manager, admin\n\nfrom auth.models import User\n\n\ndef create_app():\n app = Flask(__name__)\n app.config.from_object('settings')\n\n # init database\n db.init_app(app)\n\n # init flask-login\n login_manager.init_app(app)\n\n # init admin\n admin.init_app(app)\n for path in app.config['ADMINS']:\n __import__(path)\n\n # register blueprint\n for path, prefix in app.config['BLUEPRINTS']:\n path = path.split('.')\n module = __import__('.'.join(path[:-1]), fromlist=[path[-2]])\n if hasattr(module, path[-1]):\n bp = getattr(module, path[-1])\n app.register_blueprint(bp, url_prefix=prefix)\n\n return app\n\napp = create_app()\n\n\n# @app.before_request\n# def before_request():\n# if request.endpoint in current_app.config['SAFE_ENDPOINTS']: return\n# if current_user.is_anonymous():\n# print current_user\n# else:\n# pass\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n if sys.argv[1] == 'syncdb':\n db.syncdb()\n from auth.models import User\n session = db.Session()\n if not session.query(User).filter(User.username == 'admin').first():\n admin = User(username='admin', password='1', is_admin=True)\n session.add(admin)\n session.commit()\n else:\n app.run(host='0.0.0.0', port=5000)\n","sub_path":"runserver.py","file_name":"runserver.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"555830049","text":"# Author:duguiming\n# Description:训练RNN模型\n# Date:2019-07-08\nimport time\nimport os\nimport tensorflow as tf\nfrom data_helper.data_process import DataProcess\nfrom config.config import RNNConfig, PathConfig\nfrom model.text_model import TextRNN\n\n\ndef feed_data(x_batch, y_batch, keep_prob):\n feed_dict = {\n model.input_x: x_batch,\n model.input_y: y_batch,\n model.keep_prob: keep_prob\n }\n return feed_dict\n\n\ndef evaluate(sess, x_, y_):\n \"\"\"验证集测试\"\"\"\n data_len = len(x_)\n batch_eval = dp.batch_iter(x_, y_, 128)\n total_loss = 0.0\n total_acc = 0.0\n for x_batch, y_batch in batch_eval:\n batch_len = len(x_batch)\n feed_dict = feed_data(x_batch, y_batch, 1.0)\n loss, acc = sess.run([model.loss, model.acc], feed_dict=feed_dict)\n total_loss += loss * batch_len\n total_acc += acc * batch_len\n return total_loss / data_len, total_acc / data_len\n\n\ndef train():\n start_time = time.time()\n print(\"Loading training ...\")\n X_train, y_train = dp.process_file(pathcnfig.train_dir, word2id, cat2id, rnnconfig.seq_length)\n X_val, y_val = dp.process_file(pathcnfig.val_dir, word2id, cat2id, rnnconfig.seq_length)\n print('Time coat:{:.3f}'.format(time.time() - start_time))\n\n tf.summary.scalar('loss', model.loss)\n tf.summary.scalar('accuracy', model.acc)\n merged_summary = tf.summary.merge_all()\n writer = tf.summary.FileWriter(pathcnfig.rnn_tensorboard_dir)\n saver = tf.train.Saver()\n\n session = tf.Session()\n session.run(tf.global_variables_initializer())\n writer.add_graph(session.graph)\n\n print(\"Training and evaling...\")\n best_val_accuracy = 0\n last_improved = 0\n require_improvement = 1000\n flag = False\n\n for epoch in range(rnnconfig.num_epochs):\n batch_train = dp.batch_iter(X_train, y_train, rnnconfig.batch_size)\n start = time.time()\n for x_batch, y_batch in batch_train:\n feed_dict = feed_data(x_batch, y_batch, rnnconfig.dropout_keep_prob)\n _, global_step, train_summaries, train_loss, train_accuracy = session.run([model.optim, model.global_step,\n merged_summary, model.loss,\n model.acc], feed_dict=feed_dict)\n if global_step % rnnconfig.print_per_batch == 0:\n end = time.time()\n val_loss, val_accuracy = evaluate(session, X_val, y_val)\n writer.add_summary(train_summaries, global_step)\n\n # If improved, save the model\n if val_accuracy > best_val_accuracy:\n saver.save(session, pathcnfig.rnn_best_model_dir)\n best_val_accuracy = val_accuracy\n last_improved = global_step\n improved_str = '*'\n else:\n improved_str = ''\n print(\"step: {},train loss: {:.3f}, train accuracy: {:.3f}, val loss: {:.3f}, \"\n \"val accuracy: {:.3f},training speed: {:.3f}sec/batch {}\\n\".format(\n global_step, train_loss, train_accuracy, val_loss, val_accuracy,\n (end - start) / rnnconfig.print_per_batch, improved_str))\n start = time.time()\n\n if global_step - last_improved > require_improvement:\n print(\"No optimization over 1000 steps, stop training\")\n flag = True\n break\n if flag:\n break\n\n\nif __name__ == \"__main__\":\n pathcnfig = PathConfig()\n rnnconfig = RNNConfig()\n dp = DataProcess()\n filenames = [pathcnfig.train_dir, pathcnfig.val_dir, pathcnfig.test_dir]\n if not os.path.exists(pathcnfig.vocab_dir):\n dp.build_vocab(filenames, pathcnfig.vocab_dir, rnnconfig.vocab_size)\n\n # 读取词表和类别\n categories, cat2id = dp.read_category()\n words, word2id = dp.read_vocab(pathcnfig.vocab_dir)\n\n # 转化为向量\n if not os.path.exists(pathcnfig.vector_word_npz):\n dp.export_word2vec_vectors(word2id, pathcnfig.word2vec_save_path, pathcnfig.vector_word_npz)\n rnnconfig.pre_training = dp.get_training_word2vec_vectors(pathcnfig.vector_word_npz)\n\n model = TextRNN(rnnconfig)\n train()","sub_path":"DL/TF_CNN_RNN/train_rnn.py","file_name":"train_rnn.py","file_ext":"py","file_size_in_byte":4335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"554236416","text":"import os\nimport logging\n\nfrom pyTuttle import tuttle\n\nfrom PyQt5 import QtCore\nfrom PyQt5 import QtQuick\n\nfrom quickmamba.patterns import Singleton\nfrom pySequenceParser import sequenceParser\nfrom .sequenceWrapper import SequenceWrapper\n\nfrom quickmamba.models import QObjectListModel\n\n\nclass FileItem(QtCore.QObject):\n\n _isSelected = False\n\n class Type():\n \"\"\" Enum \"\"\"\n File = 'File'\n Folder = 'Folder'\n Sequence = 'Sequence'\n\n def __init__(self, folder, fileName, fileType, seq, supported):\n super(FileItem, self).__init__()\n\n self._filepath = os.path.join(folder, fileName)\n self._fileType = fileType\n self._isSupported = supported\n\n if fileType == FileItem.Type.File:\n if supported:\n self._fileImg = 'image://buttleofx/' + self._filepath\n else:\n self._fileImg = \"../../img/buttons/browser/file-icon.png\"\n\n try:\n # May throw exception on bad symlink\n self._fileWeight = os.stat(self._filepath).st_size\n except FileNotFoundError:\n self._fileWeight = 0\n\n self._fileExtension = os.path.splitext(fileName)[1]\n self._seq = None\n\n elif fileType == FileItem.Type.Folder:\n self._fileImg = \"../../img/buttons/browser/folder-icon.png\"\n self._seq = None\n self._fileWeight = 0.0\n self._fileExtension = \"\"\n\n elif fileType == FileItem.Type.Sequence:\n time = int(seq.getFirstTime() + (seq.getLastTime() - seq.getFirstTime()) * 0.5)\n seqPath = seq.getAbsoluteFilenameAt(time)\n\n if not os.path.exists(seqPath):\n time = seq.getFirstTime()\n seqPath = seq.getAbsoluteFilenameAt(time)\n\n seqPath = seq.getAbsoluteStandardPattern()\n\n if supported:\n self._fileImg = 'image://buttleofx/' + seqPath\n else:\n self._fileImg = \"../../img/buttons/browser/file-icon.png\"\n\n self._seq = SequenceWrapper(seq)\n self._fileWeight = self._seq.getWeight()\n (_, extension) = os.path.splitext(seqPath)\n self._fileExtension = extension\n\n # ############################################ Methods exposed to QML ############################################ #\n\n @QtCore.pyqtSlot(result=str)\n def getFilepath(self):\n return self._filepath\n\n @QtCore.pyqtSlot(result=str)\n def getFileType(self):\n return self._fileType\n\n @QtCore.pyqtSlot(result=QtCore.QSizeF)\n def getImageSize(self):\n g = tuttle.Graph()\n node = g.createNode(tuttle.getReaders(self._fileExtension)[0], self._fileImg).asImageEffectNode()\n g.setup()\n timeMin = self.getFileTime().min\n g.setupAtTime(timeMin)\n rod = node.getRegionOfDefinition(timeMin)\n width = rod.x2 - rod.x1\n height = rod.y2 - rod.y1\n return QtCore.QSizeF(width, height)\n\n @QtCore.pyqtSlot(result=bool)\n def getSupported(self):\n return self._isSupported\n\n # ######################################## Methods private to this class ####################################### #\n\n # ## Getters ## #\n\n def getFileImg(self):\n return self._fileImg\n\n def getFileName(self):\n return os.path.basename(self._filepath)\n\n def getFileWeight(self):\n return self._fileWeight\n\n def getFileTime(self):\n g = tuttle.Graph()\n node = g.createNode(tuttle.getReaders(self._fileExtension)[0], self._filepath).asImageEffectNode()\n g.setup()\n time = node.getTimeDomain()\n return time\n\n def getSelected(self):\n return self._isSelected\n\n def getSequence(self):\n return self._seq\n\n # ## Setters ## #\n\n def setFileName(self, newName):\n os.rename(self.filepath, os.path.join(os.path.dirname(self._filepath), newName))\n\n def setFilepath(self, newpath):\n import shutil\n shutil.move(self.filepath, os.path.join(newpath, self.fileName))\n\n def setSelected(self, isSelected):\n self._isSelected = isSelected\n self.isSelectedChange.emit()\n\n # ############################################# Data exposed to QML ############################################## #\n\n filepath = QtCore.pyqtProperty(str, getFilepath, setFilepath, constant=True)\n fileType = QtCore.pyqtProperty(str, getFileType, constant=True)\n fileName = QtCore.pyqtProperty(str, getFileName, setFileName, constant=True)\n fileWeight = QtCore.pyqtProperty(float, getFileWeight, constant=True)\n\n imageSize = QtCore.pyqtProperty(QtCore.QSize, getImageSize, constant=True)\n isSelectedChange = QtCore.pyqtSignal()\n isSelected = QtCore.pyqtProperty(bool, getSelected, setSelected, notify=isSelectedChange)\n fileImg = QtCore.pyqtProperty(str, getFileImg, constant=True)\n seq = QtCore.pyqtProperty(QtCore.QObject, getSequence, constant=True)\n\n\nclass FileModelBrowser(QtQuick.QQuickItem):\n \"\"\"Class FileModelBrowser\"\"\"\n\n _folder = \"\"\n _firstFolder = \"\"\n _fileItems = []\n _fileItemsModel = None\n _nameFilter = \"*\"\n\n def __init__(self, parent=None):\n super(FileModelBrowser, self).__init__(parent)\n self._fileItemsModel = QObjectListModel(self)\n self._showSeq = False\n\n # ############################################ Methods exposed to QML ############################################ #\n\n # ## Getters ## #\n\n @QtCore.pyqtSlot(str, result=QtCore.QObject)\n def getFilteredFileItems(self, fileFilter):\n suggestions = []\n\n try:\n _, dirs, _ = next(os.walk(os.path.dirname(fileFilter)))\n dirs = sorted(dirs, key=lambda v: v.upper())\n\n for d in dirs:\n if d.startswith(\".\"):\n # Ignore hidden files by default\n # TODO: need an option for that\n continue\n if d.startswith(os.path.basename(fileFilter)):\n suggestions.append(FileItem(os.path.dirname(fileFilter), d, FileItem.Type.Folder, \"\", True))\n\n except Exception:\n pass\n suggestions.sort(key=lambda fileItem: fileItem.fileName.lower())\n\n suggestionsQt = QObjectListModel(self)\n suggestionsQt.setObjectList(suggestions)\n return suggestionsQt\n\n @QtCore.pyqtSlot(result=QtCore.QObject)\n def getFileItems(self):\n return self._fileItemsModel\n\n @QtCore.pyqtSlot(result=str)\n def getFirstFolder(self):\n return self._firstFolder\n\n @QtCore.pyqtSlot(result=QtCore.QObject)\n def getLastSelected(self):\n for item in reversed(self._fileItems):\n if item.isSelected:\n return item\n return None\n\n @QtCore.pyqtSlot(result=QtCore.QObject)\n def getSelectedItems(self):\n selectedList = QObjectListModel(self)\n for item in self._fileItems:\n if item.isSelected:\n selectedList.append(item)\n return selectedList\n\n # ## Setters ## #\n\n @QtCore.pyqtSlot(str)\n def setFirstFolder(self, firstFolder):\n self._firstFolder = firstFolder\n\n # ## Others ## #\n\n @QtCore.pyqtSlot(str, int)\n def changeFileName(self, newName, index):\n if index < len(self._fileItems):\n self._fileItems[index].fileName = newName\n self.updateFileItems(self._folder)\n\n @QtCore.pyqtSlot(str)\n def createFolder(self, path):\n os.mkdir(path)\n self.updateFileItems(self._folder)\n\n @QtCore.pyqtSlot(int)\n def deleteItem(self, index):\n if index < len(self._fileItems):\n if self._fileItems[index].fileType == FileItem.Type.Folder:\n import shutil\n shutil.rmtree(self._fileItems[index].filepath)\n if self._fileItems[index].fileType == FileItem.Type.File:\n os.remove(self._fileItems[index].filepath)\n self.updateFileItems(self._folder)\n\n @QtCore.pyqtSlot(result=bool)\n def isEmpty(self):\n return not self._fileItems\n\n @QtCore.pyqtSlot(int, str)\n def moveItem(self, index, newpath):\n if index < len(self._fileItems):\n self._fileItems[index].filepath = newpath\n self.updateFileItems(self._folder)\n\n @QtCore.pyqtSlot(int)\n def selectItem(self, index):\n for item in self._fileItems:\n item.isSelected = False\n if index < len(self._fileItems):\n self._fileItems[index].isSelected = True\n\n @QtCore.pyqtSlot(int)\n def selectItems(self, index):\n if index < len(self._fileItems):\n self._fileItems[index].isSelected = True\n\n @QtCore.pyqtSlot(int, int)\n def selectItemsByShift(self, begin, end):\n if begin > end:\n tmp = begin\n begin = end\n end = tmp\n for i in range(begin, end + 1):\n if i < len(self._fileItems):\n self._fileItems[i].isSelected = True\n\n @QtCore.pyqtSlot(str)\n def updateFileItems(self, folder):\n logging.debug('updateFileItems: %s' % folder)\n if not folder:\n return\n\n self._fileItems = []\n self._fileItemsModel.clear()\n allDirs = []\n allFiles = []\n allSeqs = []\n\n items = sequenceParser.browse(folder)\n dirs = [item.getFilename() for item in items if item.getType() == sequenceParser.eTypeFolder]\n seqs = [item.getSequence() for item in items if item.getType() == sequenceParser.eTypeSequence]\n files = [item.getFilename() for item in items if item.getType() == sequenceParser.eTypeFile]\n\n for d in dirs:\n if d.startswith(\".\"):\n # Ignore hidden files by default\n # TODO: need an option for that\n continue\n allDirs.append(FileItem(folder, d, FileItem.Type.Folder, \"\", True))\n\n if self._showSeq:\n for s in seqs:\n sPath = s.getStandardPattern()\n if sPath.startswith(\".\"):\n # Ignore hidden files by default\n # TODO: need an option for that\n continue\n readers = tuttle.getReaders(sPath)\n logging.debug('SEQ readers: %s' % readers)\n supported = bool(readers)\n if not supported and self._nameFilter != \"*\":\n continue\n allSeqs.append(FileItem(folder, sPath, FileItem.Type.Sequence, s, supported))\n\n for f in files:\n if f.startswith(\".\"):\n # Ignore hidden files by default\n # TODO: need an option for that\n continue\n readers = tuttle.getReaders(f)\n logging.debug('FILE readers: %s' % readers)\n supported = bool(readers)\n if not supported and self._nameFilter != \"*\":\n continue\n allFiles.append(FileItem(folder, f, FileItem.Type.File, \"\", supported))\n\n allDirs.sort(key=lambda fileItem: fileItem.fileName.lower())\n allFiles.sort(key=lambda fileItem: fileItem.fileName.lower())\n allSeqs.sort(key=lambda fileItem: fileItem.fileName.lower())\n self._fileItems = allDirs + allFiles + allSeqs\n\n self._fileItemsModel.setObjectList(self._fileItems)\n\n # ######################################## Methods private to this class ######################################## #\n\n # ## Getters ## #\n\n def getFilter(self):\n return self._nameFilter\n\n def getFolder(self):\n return self._folder\n\n def getFolderExists(self):\n return os.path.exists(self._folder)\n\n def getParentFolder(self):\n return os.path.dirname(self._folder)\n\n def getShowSeq(self):\n return self._showSeq\n\n def getSize(self):\n return len(self._fileItems) - 1\n\n # ## Setters ## #\n\n def setFilter(self, nameFilter):\n self._nameFilter = nameFilter\n self.updateFileItems(self._folder)\n self.nameFilterChange.emit()\n\n def setFolder(self, folder):\n logging.debug('fileModelBrowser.setFolder(\"%s\")' % folder)\n self._folder = folder\n self.updateFileItems(folder)\n self.folderChanged.emit()\n\n def setShowSeq(self, checkSeq):\n self._showSeq = checkSeq\n self.updateFileItems(self._folder)\n self.showSeqChanged.emit()\n\n # ############################################# Data exposed to QML ############################################# #\n\n folderChanged = QtCore.pyqtSignal()\n folder = QtCore.pyqtProperty(str, getFolder, setFolder, notify=folderChanged)\n exists = QtCore.pyqtProperty(bool, getFolderExists, notify=folderChanged)\n parentFolder = QtCore.pyqtProperty(str, getParentFolder, constant=True)\n\n fileItems = QtCore.pyqtProperty(QtCore.QObject, getFileItems, notify=folderChanged)\n nameFilterChange = QtCore.pyqtSignal()\n nameFilter = QtCore.pyqtProperty(str, getFilter, setFilter, notify=nameFilterChange)\n size = QtCore.pyqtProperty(int, getSize, constant=True)\n showSeqChanged = QtCore.pyqtSignal()\n showSeq = QtCore.pyqtProperty(bool, getShowSeq, setShowSeq, notify=showSeqChanged)\n\n","sub_path":"buttleofx/gui/browser/fileModelBrowser.py","file_name":"fileModelBrowser.py","file_ext":"py","file_size_in_byte":13145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"281458129","text":"from sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.pipeline import Pipeline\n\nfrom feature_engine.imputation import (\n AddMissingIndicator,\n MeanMedianImputer,\n CategoricalImputer,\n)\n\nfrom feature_engine.encoding import (\n RareLabelEncoder,\n OneHotEncoder,\n)\n\nfrom classification_model.config.core import config\nfrom classification_model.processing import features as pp\n\n\ntitanic_pipe = Pipeline([\n\n # ==== IMPUTATION ====\n # imputer categorical varaibles with string 'missing\"\n ('categorical_imputation', CategoricalImputer(\n imputation_method=\"missing\",\n variables=config.model_config.categorical_vars,\n )\n ),\n\n # add missing indicator to numerical variables\n ('missing_indicator', AddMissingIndicator(\n variables=config.model_config.numerical_vars\n )\n ),\n\n # imputer numerical variables with the median\n ('median_imputation', MeanMedianImputer(\n imputation_method=\"median\",\n variables=config.model_config.numerical_vars\n )\n ),\n\n # ==== CATEGORICAL ENCODING ====\n # remove categories present in less than 5% of the obeservations\n # group thme into one category called 'Rare'\n ('rare_label_encoder', RareLabelEncoder(\n tol=config.model_config.tol,\n n_categories=config.model_config.n_categories,\n variables=config.model_config.categorical_vars,\n )\n ),\n\n # encode categorical variables using one-hot encoding into k-1 variables\n ('categorical_encoder', OneHotEncoder(\n variables=config.model_config.categorical_vars,\n drop_last=True,\n )\n ),\n\n # scale using standardization\n ('scaler', StandardScaler()),\n\n # logistic regression\n ('Logit', LogisticRegression(\n C=config.model_config.c,\n random_state=config.model_config.random_state,\n )\n ),\n])","sub_path":"assignment-4-titantic-prod/classification_model/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"110340643","text":"def quardrequat(a,b,c):\r\n import math\r\n if not all ([ isinstance(a,(int,float)) , isinstance(b,(int,float)) , isinstance(c,(int,float))]):\r\n raise TypeError('\\n bad input.\\n check if all the input are integars or floats.')\r\n else:\r\n a=float(a)\r\n b=float(b)\r\n c=float(c)\r\n delta=b**2-4*a*c\r\n if delta<0:\r\n return 'No answer exists.'\r\n if delta==0:\r\n x=-b/(2*a)\r\n x=float(' %.4f ' %x )\r\n return x\r\n if delta>0:\r\n x1=(-b+math.sqrt(delta))/(2*a)\r\n x2=(-b-math.sqrt(delta))/(2*a)\r\n x1=float(' %.4f ' %x1 )\r\n x2=float(' %.4f ' %x2 )\r\n return x1 , x2\r\n","sub_path":"equationsolver-function.py","file_name":"equationsolver-function.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"404749824","text":"from odoo import models, fields, api,_\r\nfrom datetime import date,datetime,time,timedelta\r\nfrom dateutil.relativedelta import relativedelta\r\nfrom odoo.exceptions import UserError\r\n\r\n\r\nclass HrExpensesExpenses(models.Model):\r\n _name = 'hr.expenses.expenses'\r\n _rec_name = 'expensescc_id'\r\n\r\n expensescc_id = fields.Many2one(comodel_name=\"hr.expense\", string=\"Expenses\",)\r\n date = fields.Date(string=\"Date\", required=False, )\r\n total_amount = fields.Float(string=\"Total Amount\", required=False, )\r\n expen_id = fields.Many2one(comodel_name=\"hr.expense\", string=\"\", required=False, )\r\n\r\n\r\n\r\n\r\nclass HRExpensesInherit(models.Model):\r\n _inherit = 'hr.expense'\r\n\r\n sales_id = fields.Many2one(comodel_name=\"operation.operation\", string=\"Operation\",)\r\n sales_state = fields.Char(string=\"Sales State\",compute='compute_sales_state')\r\n operations_type = fields.Many2one(comodel_name=\"product.operation.type\", string=\"Operation Type\",)\r\n is_sales = fields.Boolean(string=\"IS Sales\",related='product_id.is_sales_order')\r\n\r\n # expenses_ids = fields.Many2many(comodel_name=\"hr.expense\", relation=\"expenses_relation\", column1=\"expenses_col1\", column2=\"expenses_col2\", string=\"Expenses\",)\r\n expenses_lines_ids = fields.One2many(comodel_name=\"hr.expenses.expenses\", inverse_name=\"expen_id\", string=\"\", required=False, )\r\n is_expenses_ids = fields.Boolean(string=\"\",compute='filter_sales_id' )\r\n\r\n partner_surgeon_id = fields.Many2one(comodel_name=\"res.partner\", string=\"Surgeon\")\r\n event_id = fields.Many2one(comodel_name=\"hr.expenses.event\", string=\"Event\", )\r\n sale_order_mandatory = fields.Boolean(string=\"Sale Order Mandatory\",related='product_id.property_account_expense_id.sale_order_mandatory')\r\n\r\n total_expense_amount = fields.Float(string=\"Total Amount\",compute='compute_total_expense_amount')\r\n\r\n num_day_expire = fields.Integer(compute='compute_num_day_expire' )\r\n\r\n\r\n def get_all_operation_type(self):\r\n for rec in self.search([]):\r\n if not rec.operations_type:\r\n rec.operations_type = rec.sales_id.operation_type\r\n\r\n @api.onchange('sales_id')\r\n def compute_operations_type(self):\r\n self.operations_type = self.sales_id.operation_type\r\n\r\n # def write(self, vals):\r\n # res=super(HRExpensesInherit, self).write(vals)\r\n # if self.env.user.has_group('surgi_sales_expenses.expenses_only_view_group') and vals:\r\n # print(res,\"HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH\")\r\n # raise UserError(_('Permission Denied.'))\r\n #\r\n # return res\r\n\r\n def compute_num_day_expire(self):\r\n expiration_rec = self.env['hr.expense.expiration'].search([],limit=1)\r\n for rec in self:\r\n rec.num_day_expire=expiration_rec.num_day_expire\r\n if rec.num_day_expire:\r\n\r\n rec.filter_value_sales()\r\n\r\n # @api.depends('sales_id','expenses_lines_ids')\r\n def compute_total_expense_amount(self):\r\n for rec in self:\r\n total_expense_amount=0.0\r\n for line in rec.expenses_lines_ids:\r\n total_expense_amount+=line.total_amount\r\n rec.total_expense_amount=total_expense_amount\r\n @api.depends('sales_id')\r\n def compute_sales_state(self):\r\n for rec in self:\r\n rec.sales_state=''\r\n if rec.sales_id:\r\n rec.sales_state =rec.sales_id.state\r\n\r\n\r\n\r\n @api.onchange('name','date','sales_id')\r\n def filter_value_sales(self):\r\n sales_list=[]\r\n today_date = datetime.strptime(str(date.today()), '%Y-%m-%d').date()\r\n operation_rec = self.env['operation.operation'].search([])\r\n expiration_rec = self.env['hr.expense.expiration'].search([],limit=1)\r\n for rec in operation_rec:\r\n if rec.start_datetime:\r\n date_order = datetime.strptime(str(rec.start_datetime).split(\".\")[0],\r\n '%Y-%m-%d %H:%M:%S').date()\r\n\r\n if expiration_rec and int(str((today_date - date_order).days))<=expiration_rec.num_day_expire:\r\n sales_list.append(rec.id)\r\n return {\r\n 'domain': {'sales_id': [('id', 'in',sales_list )]}\r\n }\r\n\r\n @api.depends('sales_id')\r\n def filter_sales_id(self):\r\n for expen in self:\r\n line_list = [(5,0,0)]\r\n expen.is_expenses_ids=False\r\n for rec in self.search([]):\r\n if expen._origin.id !=rec.id and expen.sales_id.id==rec.sales_id.id:\r\n line_list.append((0,0,{\r\n 'expensescc_id': rec.id,\r\n 'date': rec.date,\r\n 'total_amount': rec.total_amount,\r\n }))\r\n expen.is_expenses_ids=True\r\n if expen.sales_id and line_list:\r\n expen.update({'expenses_lines_ids':line_list})\r\n else:\r\n expen.expenses_lines_ids=False\r\n\r\n @api.onchange('employee_id','product_id')\r\n def filter_product_id(self):\r\n product_list=[]\r\n\r\n for rec in self.env['product.product'].search([('can_be_expensed', '=', True)]):\r\n if self.employee_id.department_id.id in rec.department_ids.ids:\r\n product_list.append(rec.id)\r\n\r\n return {\r\n 'domain': {'product_id': [('id', 'in', product_list)]}\r\n }\r\n\r\nclass HrExpenseSheetInherit(models.Model):\r\n _inherit = 'hr.expense.sheet'\r\n\r\n account_reviewed= fields.Boolean(string=\"Account Reviewed\", )\r\n treasury_manager= fields.Boolean(string=\"Treasury Manager\", )\r\n check_access_expense = fields.Boolean(compute=\"compute_check_access_expense\")\r\n\r\n\r\n\r\n\r\n @api.depends('state')\r\n def compute_check_access_expense(self):\r\n for rec in self:\r\n\r\n if rec.state in ['draft','submit']:\r\n\r\n rec.check_access_expense = True\r\n elif not self.env.user.has_group('surgi_sales_expenses.expenses_add_line_group') and rec.state=='approve' :\r\n\r\n rec.check_access_expense = False\r\n elif self.env.user.has_group('surgi_sales_expenses.expenses_add_line_group') :\r\n\r\n rec.check_access_expense = True\r\n else:\r\n\r\n rec.check_access_expense = False\r\n\r\n def button_account_reviewed(self):\r\n self.account_reviewed=True\r\n def button_treasury_manager(self):\r\n self.treasury_manager=True\r\n\r\n def action_sheet_move_create(self):\r\n res=super(HrExpenseSheetInherit, self).action_sheet_move_create()\r\n if self.account_move_id:\r\n self.account_move_id.date=date.today()\r\n # for rec in self.expense_line_ids:\r\n # for line in self.account_move_id.line_ids:\r\n # # if rec.product_id==line.product_id:\r\n # line.name= \"[\"+rec.product_id.default_code+\"]\" +\" \" +rec.product_id.name\r\n return res\r\n\r\nclass AccountAccountInherit(models.Model):\r\n _inherit = 'account.account'\r\n\r\n sale_order_mandatory = fields.Boolean(string=\"Sale Order Mandatory\", )\r\n","sub_path":"surgi_sales_expenses/models/expenses.py","file_name":"expenses.py","file_ext":"py","file_size_in_byte":7102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"278520491","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 25 18:37:27 2019\n\n@author: Poor\n\"\"\"\n\nfrom flask import Blueprint,request,session\nfrom .blog_sql import get_sql,close_sql\n\nbp=Blueprint('record',__name__,url_prefix='/record')\n\n@bp.route('/view',methods=['POST'])\ndef view_rec():\n error=None\n try:\n user_id=int(session.get('user_id'))\n except:\n user_id=None\n try:\n article_id=int(request.args.get('article_id',0))\n except ValueError:\n error='{\"code\":400,\"errmsg\":\"article_id is expected to be a int\"}'\n user_ip=request.headers.get('user_ip')\n if user_ip is None:\n error='{\"code\":400,\"errmsg\":\"unknown ip\"}'\n if error is not None:\n return error\n \n try:\n sql_conn=get_sql()\n with sql_conn.begin() as connection:\n sql_insert='''\n insert ignore into \n my_viewer \n (viewer_ip,viewer_id,article_id) \n values \n (@vip,@vid,@aid) \n '''\n connection.execute(\"set @vip = '{}'\".format(user_ip))\n connection.execute(\"set @vid = '{}'\".format(user_id))\n connection.execute(\"set @aid = '{}'\".format(article_id))\n connection.execute(sql_insert)\n return '{\"code\":200,\"errmsg\":\"OK\"}'\n finally:\n close_sql()\n","sub_path":"rear/blog_server/blog_record.py","file_name":"blog_record.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"2766524","text":"# Random Forest Algorithm\r\n# data preparation\r\nimport math\r\nfrom utils import *\r\nimport pandas as pd\r\n\r\ntraining = \"training_result.csv\"\r\ntrain_data = pd.read_csv(training, sep=',')\r\n\r\ntesting = \"testing_result.csv\"\r\ntest_data = pd.read_csv(testing, sep=',')\r\nID = test_data.ix[:, :1].values\r\ntest_data = test_data.ix[:, 1:].values\r\n\r\n# training~~~~~~~~~~~~~~~~~~\r\nn_folds = 3\r\nmax_depth = 10\r\nmin_size = 1\r\nsample_size = 1.0\r\nn_trees = 5\r\nn_features = 11\r\ntest_ratio = 0.8\r\n\r\n# initial and fit random_forest with train_data\r\nrf = random_forest(train_data, n_folds, max_depth, min_size, sample_size, n_trees, n_features, test_ratio)\r\nrf.best_trained_tree() # select best trees amount all folds\r\n\r\n# testing~~~~~~~~~~~~~~~~~~\r\npredictions = rf.predict_test_data(test_data)\r\n\r\n# write the testing result in a text file\r\nfile = open('max_output.txt', 'w')\r\nfor i in range(len(predictions)):\r\n temp = str(ID[i]) + \": \" + str(int(predictions[i]))\r\n file.write(temp)\r\n file.write('\\n')\r\nfile.close()\r\n","sub_path":"data_classification.py","file_name":"data_classification.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"422978156","text":"#!/usr/bin/env python3\n\nfrom datetime import datetime\nimport re\n\nSYS_UPGRADE_LOG_FILENAME = '/var/log/pacman.log'\nUPGRADE_MESSAGE_PATTERN = r'full system upgrade'\nUPGRADE_DATE_PATTERN = r'(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2})'\nSUCCESS_COLOR = '#3b7008'\nFAILURE_COLOR = '#4d0b0b'\n\nwith open(SYS_UPGRADE_LOG_FILENAME) as logfile:\n loglines = logfile.readlines()\n for line in reversed(loglines):\n if re.search(UPGRADE_MESSAGE_PATTERN, line):\n match = re.search(UPGRADE_DATE_PATTERN, line)\n if match:\n log_datetime = match.group(1)\n upgrade_datetime = datetime.strptime(\n log_datetime,\n '%Y-%m-%d %H:%M'\n )\n daydiff = (datetime.now() - upgrade_datetime).days\n print(daydiff)\n print(daydiff)\n if daydiff > 1:\n print(FAILURE_COLOR)\n else:\n print(SUCCESS_COLOR)\n break\n","sub_path":"pacman_last_sys_upgrade.py","file_name":"pacman_last_sys_upgrade.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"593964974","text":"# coding=utf-8\r\n\r\n\"\"\"\r\nFind all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.\r\n\r\n\r\nExample 1:\r\n\r\nInput: k = 3, n = 7\r\n\r\nOutput:\r\n\r\n[[1,2,4]]\r\n\r\nExample 2:\r\n\r\nInput: k = 3, n = 9\r\n\r\nOutput:\r\n\r\n[[1,2,6], [1,3,5], [2,3,4]]\r\n\"\"\"\r\n\r\n\r\n# Definition for a binary tree node.\r\nclass Solution(object):\r\n def combinationSum3(self, k, n):\r\n \"\"\"\r\n :type k: int\r\n :type n: int\r\n :rtype: List[List[int]]\r\n \"\"\"\r\n\r\n def _dfs(nums, k, n, usedNumIndex, path, ret):\r\n if k < 0 or n < 0: return\r\n if k == 0 and n == 0: ret.append(path)\r\n for i in range(usedNumIndex, len(nums)):\r\n _dfs(nums, k - 1, n - nums[i], i + 1, path + [nums[i]], ret)\r\n\r\n ret = []\r\n _dfs(range(1, 10), k, n, 0, [], ret)\r\n return ret\r\n\r\n\r\nif __name__ == '__main__':\r\n print(Solution().combinationSum3(4, 15))\r\n","sub_path":"zishell/solution/medium/solution216_combinationSumIII.py","file_name":"solution216_combinationSumIII.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"328501246","text":"#!/usr/bin/env python2.7\n\"\"\"\nThin wrapper for vcfeval, as a convenience to stick a vcfeval output directory\nalong with the other toil-vg output. Can be run standalone as well.\n\"\"\"\nfrom __future__ import print_function\nimport argparse, sys, os, os.path, random, subprocess, shutil, itertools, glob\nimport json, time, timeit, errno\nfrom uuid import uuid4\nimport logging\n\nfrom toil.common import Toil\nfrom toil.job import Job\nfrom toil.realtimeLogger import RealtimeLogger\nfrom toil_vg.vg_common import *\nfrom toil_vg.context import Context, run_write_info_to_outstore\n\nlogger = logging.getLogger(__name__)\n\ndef vcfeval_subparser(parser):\n \"\"\"\n Create a subparser for vcf evaluation. Should pass in results of subparsers.add_parser()\n \"\"\"\n\n # Add the Toil options so the job store is the first argument\n Job.Runner.addToilOptions(parser)\n\n # General options\n parser.add_argument(\"--call_vcf\", type=make_url, required=True,\n help=\"input vcf (must be bgzipped and have .tbi\")\n parser.add_argument(\"out_store\",\n help=\"output store. All output written here. Path specified using same syntax as toil jobStore\")\n # Add common options shared with everybody\n add_common_vg_parse_args(parser)\n\n # Add common calling options shared with toil_vg pipeline\n vcfeval_parse_args(parser)\n\n # Add common docker options shared with toil_vg pipeline\n add_container_tool_parse_args(parser)\n\ndef vcfeval_parse_args(parser):\n \"\"\" centralize reusable vcfevaling parameters here \"\"\"\n\n parser.add_argument(\"--vcfeval_baseline\", type=make_url,\n help=\"Path to baseline VCF file for comparison (must be bgzipped and have .tbi)\")\n\n parser.add_argument(\"--vcfeval_fasta\", type=make_url,\n help=\"Path to DNA sequence file, required for vcfeval. Maybe be gzipped\")\n\n parser.add_argument(\"--vcfeval_bed_regions\", type=make_url,\n help=\"BED file of regions to consider\")\n parser.add_argument(\"--vcfeval_opts\", type=str,\n help=\"Additional options for vcfeval (wrapped in \\\"\\\")\",\n default=None)\n parser.add_argument(\"--vcfeval_cores\", type=int,\n default=1,\n help=\"Cores to use for vcfeval\")\n parser.add_argument(\"--vcfeval_score_field\", default=None,\n help=\"vcf FORMAT field to use for ROC score. overrides vcfeval_opts\")\n parser.add_argument(\"--vcfeval\", action=\"store_true\",\n help=\"run rtg vcfeval comparison. (will be run by default if no other tool specified)\")\n parser.add_argument(\"--happy\", action=\"store_true\",\n help=\"run hap.py comparison.\")\n parser.add_argument(\"--sveval\", action=\"store_true\",\n help=\"run bed-based sv comparison.\")\n parser.add_argument(\"--min_sv_len\", type=int, default=20,\n help=\"minimum length to consider when doing bed sv comparison (using --sveval)\")\n parser.add_argument(\"--sv_region_overlap\", type=float, default=1.0,\n help=\"sv must overlap bed region (--vcfeval_bed_regions) by this fraction to be considered\")\n parser.add_argument(\"--sv_overlap\", type=float, default=0.5,\n help=\"minimum reciprical overlap required for bed intersection to count as TP\")\n parser.add_argument(\"--sv_smooth\", type=int, default=0,\n help=\"mege up svs (in calls and truth) that are at most this many bases apart\")\n\ndef validate_vcfeval_options(options):\n \"\"\" check some options \"\"\"\n # we can relax this down the road by optionally doing some compression/indexing\n assert options.vcfeval_baseline and options.vcfeval_baseline.endswith(\".vcf.gz\")\n assert options.call_vcf.endswith(\".vcf.gz\")\n\n assert not (options.happy or options.vcfeval) or options.vcfeval_fasta\n\n \ndef parse_f1(summary_path):\n \"\"\" grab the best f1 out of vcfeval's summary.txt \"\"\"\n\n # get the F1 out of summary.txt\n # expect header on 1st line and data on 3rd and below\n # we take the best F1 found over these lines (which should correspond to best\n # point on quality ROC curve)\n # todo: be more robust\n f1 = None\n with open(summary_path) as sum_file:\n header = sum_file.readline().split()\n assert header[-1] == 'F-measure' \n line = sum_file.readline()\n for line in sum_file:\n data = line.strip().split()\n assert len(data) == len(header)\n line_f1 = float(data[-1])\n if f1 is None or line_f1 > f1:\n f1 = line_f1\n return f1\n\ndef parse_happy_summary(summary_path):\n \"\"\" Turn the happy summary into a dictionary we can easily get F1 scores etc. from \"\"\"\n results = {} # make something like: results[INDEL][METRIC.F1_Score] = 0.9x\n with open(summary_path) as sum_file:\n header = sum_file.readline().split(',')\n for line in sum_file:\n row = line.split(',')\n cat = row[0]\n if row[1] == 'ALL':\n cat += '.ALL'\n assert cat not in results\n results[cat] = {}\n for column in range(1, len(header)):\n results[cat][header[column]] = row[column] if len(row[column]) else '0'\n return results\n\ndef run_vcfeval_roc_plot(job, context, roc_table_ids, names=[], kind=None, number=0, title=None,\n show_scores=False, line_width=2, ps_plot=False):\n \"\"\"\n Draw some rocs from the vcfeval output. Return (snps_id, nonsnps_id,\n weighted_id)\n \n kind specifies the subtype of roc plot (e.g. 'snp-unclipped'). number gives\n the number of this plot in all plots of that kind. title gives an optional\n human-readable title.\n \"\"\"\n\n # make a local work directory\n work_dir = job.fileStore.getLocalTempDir()\n\n # dummy default names\n if not names:\n names = ['vcfeval_output-{}'.format(i) for i in range(len(roc_table_ids))]\n\n # rely on unique input names\n assert len(names) == len(set(names))\n \n # download the files\n table_file_paths = [os.path.join(work_dir, name, name) + '.tsv.gz' for name in names]\n table_file_rel_paths = [os.path.join(name, name) + '.tsv.gz' for name in names]\n for table_path, name, file_id in zip(table_file_paths, names, roc_table_ids):\n # rtg gets naming information from directory structure, so we read each file into\n # its own dir\n os.makedirs(os.path.join(work_dir, name))\n job.fileStore.readGlobalFile(file_id, table_path)\n RealtimeLogger.info('Downloaded {} to {}'.format(file_id, table_path))\n\n # Make sure the kind has 'roc' in it\n if kind is None:\n kind = 'roc'\n else:\n kind = 'roc-{}'.format(kind)\n \n plot_filename = title_to_filename(kind, number, title, 'svg')\n out_roc_path = os.path.join(work_dir, plot_filename)\n\n roc_opts = []\n if title:\n roc_opts += ['--title', title]\n if show_scores:\n roc_opts += ['--scores']\n if line_width:\n roc_opts += ['--line-width', line_width]\n if ps_plot:\n roc_opts += ['precision-sensitivity']\n\n out_ids = []\n\n roc_cmd = ['rtg', 'rocplot', '--svg', os.path.basename(out_roc_path)]\n roc_cmd += roc_opts + table_file_rel_paths\n \n context.runner.call(job, roc_cmd, work_dir = work_dir)\n\n return context.write_output_file(job, out_roc_path, os.path.join('plots', plot_filename))\n\ndef run_extract_sample_truth_vcf(job, context, sample, input_baseline_id, input_baseline_tbi_id):\n \"\"\"\n \n Extract a single-sample truth VCF from the given truth VCF .vcf.gz and .vcf.gz.tbi.\n \n Returns a pair of file IDs for the resulting .vcf.gz and .vcf.gz.tbi.\n \n Filtering the truth down is useful because it can save memory.\n \n TODO: use this in toil-vg vcfeval, instead of just providing it as a utility.\n \n \"\"\"\n \n # Make a local work directory\n work_dir = job.fileStore.getLocalTempDir()\n \n # Download the truth vcf\n vcfeval_baseline_name = 'full-truth.vcf.gz'\n job.fileStore.readGlobalFile(input_baseline_id, os.path.join(work_dir, vcfeval_baseline_name))\n job.fileStore.readGlobalFile(input_baseline_tbi_id, os.path.join(work_dir, vcfeval_baseline_name + '.tbi')) \n \n # Make the single-sample VCF\n single_name = 'single-truth-{}.vcf.gz'.format(sample)\n context.runner.call(job, ['bcftools', 'view', vcfeval_baseline_name, '-s', sample, '-o', single_name, '-O', 'z'], work_dir=work_dir)\n \n # Index it\n context.runner.call(job, ['tabix', '-f', '-p', 'vcf', single_name], work_dir=work_dir)\n \n # Upload file and index\n single_vcf_id = context.write_output_file(job, os.path.join(work_dir, single_name))\n single_vcf_tbi_id = context.write_output_file(job, os.path.join(work_dir, single_name + '.tbi'))\n \n return single_vcf_id, single_vcf_tbi_id\n\ndef run_vcfeval(job, context, sample, vcf_tbi_id_pair, vcfeval_baseline_id, vcfeval_baseline_tbi_id, \n fasta_path, fasta_id, bed_id, out_name = None, score_field=None):\n \"\"\"\n \n Run RTG vcf_eval to compare VCFs.\n \n Return a results dict like:\n \n {\n \"f1\": f1 score as float,\n \"summary\": summary file ID,\n \"archive\": output archive ID,\n \"snp\": ROC .tsv.gz data file ID for SNPs,\n \"non_snp\": ROC .tsv.gz data file ID for non-SNP variants,\n \"weighted\": ROC .tsv.gz data file ID for a weighted combination of SNP and non-SNP variants\n }\n \n Some ROC data file IDs may not be present if they were not calculated.\n \n \"\"\"\n\n # make a local work directory\n work_dir = job.fileStore.getLocalTempDir()\n\n # download the vcf\n call_vcf_id, call_tbi_id = vcf_tbi_id_pair[0], vcf_tbi_id_pair[1]\n call_vcf_name = \"calls.vcf.gz\"\n job.fileStore.readGlobalFile(vcf_tbi_id_pair[0], os.path.join(work_dir, call_vcf_name))\n job.fileStore.readGlobalFile(vcf_tbi_id_pair[1], os.path.join(work_dir, call_vcf_name + '.tbi'))\n\n # and the truth vcf\n vcfeval_baseline_name = 'truth.vcf.gz'\n job.fileStore.readGlobalFile(vcfeval_baseline_id, os.path.join(work_dir, vcfeval_baseline_name))\n job.fileStore.readGlobalFile(vcfeval_baseline_tbi_id, os.path.join(work_dir, vcfeval_baseline_name + '.tbi')) \n # download the fasta (make sure to keep input extension)\n fasta_name = \"fa_\" + os.path.basename(fasta_path)\n job.fileStore.readGlobalFile(fasta_id, os.path.join(work_dir, fasta_name))\n\n # download the bed regions\n bed_name = \"bed_regions.bed\" if bed_id else None\n if bed_id:\n job.fileStore.readGlobalFile(bed_id, os.path.join(work_dir, bed_name))\n\n # use out_name if specified, otherwise sample\n if sample and not out_name:\n out_name = sample \n if out_name:\n out_tag = '{}_vcfeval_output'.format(out_name)\n else:\n out_tag = 'vcfeval_output'\n \n # output directory\n out_name = out_tag\n # indexed sequence\n sdf_name = fasta_name + \".sdf\"\n \n # make an indexed sequence (todo: allow user to pass one in)\n context.runner.call(job, ['rtg', 'format', fasta_name, '-o', sdf_name], work_dir=work_dir) \n\n # run the vcf_eval command\n cmd = ['rtg', 'vcfeval', '--calls', call_vcf_name,\n '--baseline', vcfeval_baseline_name,\n '--template', sdf_name, '--output', out_name,\n '--threads', str(context.config.vcfeval_cores)]\n\n if bed_name is not None:\n cmd += ['--evaluation-regions', bed_name]\n\n if context.config.vcfeval_opts:\n cmd += context.config.vcfeval_opts\n\n # override score field from options with one from parameter\n if score_field:\n for opt in ['-f', '--vcf-score-field']:\n if opt in cmd:\n opt_idx = cmd.index(opt)\n del cmd[opt_idx]\n del cmd[opt_idx]\n cmd += ['--vcf-score-field', score_field]\n \n if sample:\n # Pass the sample name along, since it is needed if the truth VCF has multiple samples\n cmd += ['--sample', sample]\n\n \n try:\n context.runner.call(job, cmd, work_dir=work_dir)\n except:\n # Dump everything we need to replicate the alignment\n logging.error(\"VCF evaluation failed. Dumping files.\")\n context.write_output_file(job, os.path.join(work_dir, call_vcf_name))\n context.write_output_file(job, os.path.join(work_dir, vcfeval_baseline_name))\n # TODO: Dumping the sdf folder doesn't seem to work right. But we can dump the fasta\n context.write_output_file(job, os.path.join(work_dir, fasta_name))\n if bed_name is not None:\n context.write_output_file(job, os.path.join(work_dir, bed_name))\n \n raise\n\n\n # copy results to outstore \n \n # vcfeval_output_summary.txt\n out_summary_id = context.write_output_file(job, os.path.join(work_dir, out_tag, 'summary.txt'),\n out_store_path = '{}_summary.txt'.format(out_tag))\n\n # vcfeval_output.tar.gz -- whole shebang\n context.runner.call(job, ['tar', 'czf', out_tag + '.tar.gz', out_tag], work_dir = work_dir)\n out_archive_id = context.write_output_file(job, os.path.join(work_dir, out_tag + '.tar.gz'))\n\n # truth VCF\n context.write_output_file(job, os.path.join(work_dir, vcfeval_baseline_name))\n context.write_output_file(job, os.path.join(work_dir, vcfeval_baseline_name + '.tbi'))\n \n # vcfeval_output_f1.txt (used currently by tests script)\n f1 = parse_f1(os.path.join(work_dir, os.path.basename(out_name), \"summary.txt\"))\n f1_path = os.path.join(work_dir, \"f1.txt\") \n with open(f1_path, \"w\") as f:\n f.write(str(f1))\n context.write_output_file(job, f1_path, out_store_path = '{}_f1.txt'.format(out_tag))\n\n # Start the output dict\n out_dict = {\n \"f1\": f1, \n \"summary\": out_summary_id, \n \"archive\": out_archive_id\n }\n\n # roc data (written to outstore to allow re-plotting)\n for roc_name in ['snp', 'non_snp', 'weighted']:\n roc_file = os.path.join(work_dir, out_tag, '{}_roc.tsv.gz'.format(roc_name))\n if os.path.isfile(roc_file):\n # Save this one\n dest_file = os.path.join('roc', out_tag, '{}_roc.tsv.gz'.format(roc_name))\n out_dict[roc_name] = context.write_output_file(job, roc_file, dest_file)\n\n return out_dict\n\ndef run_happy(job, context, sample, vcf_tbi_id_pair, vcfeval_baseline_id, vcfeval_baseline_tbi_id, \n fasta_path, fasta_id, bed_id, fasta_idx_id = None, out_name = None):\n \"\"\"\n \n Run hap.py to compare VCFs.\n \n Return a results dict like:\n \n {\n \"parsed_summary\": parsed summary file dict, including F1 scores,\n \"summary\": summary file ID,\n \"archive\": output archive ID\n }\n \n The parsed summary dict is by variant type ('SNP', 'INDEL'), and then by metric name (like 'METRIC.F1_Score').\n \n \"\"\"\n \n\n # make a local work directory\n work_dir = job.fileStore.getLocalTempDir()\n\n # download the vcf\n call_vcf_id, call_tbi_id = vcf_tbi_id_pair[0], vcf_tbi_id_pair[1]\n call_vcf_name = \"calls.vcf.gz\"\n job.fileStore.readGlobalFile(vcf_tbi_id_pair[0], os.path.join(work_dir, call_vcf_name))\n job.fileStore.readGlobalFile(vcf_tbi_id_pair[1], os.path.join(work_dir, call_vcf_name + '.tbi'))\n\n # and the truth vcf\n vcfeval_baseline_name = 'truth.vcf.gz'\n job.fileStore.readGlobalFile(vcfeval_baseline_id, os.path.join(work_dir, vcfeval_baseline_name))\n job.fileStore.readGlobalFile(vcfeval_baseline_tbi_id, os.path.join(work_dir, vcfeval_baseline_name + '.tbi'))\n \n # download the fasta (make sure to keep input extension)\n fasta_name = \"fa_\" + os.path.basename(fasta_path)\n job.fileStore.readGlobalFile(fasta_id, os.path.join(work_dir, fasta_name))\n\n # download or create the fasta index which is required by hap.py\n if fasta_idx_id:\n job.fileStore.readGlobalFile(fasta_idx_id, os.path.join(work_dir, fasta_name + '.fai'))\n else:\n context.runner.call(job, ['samtools', 'faidx', fasta_name], work_dir=work_dir)\n\n # download the bed regions\n bed_name = \"bed_regions.bed\" if bed_id else None\n if bed_id:\n job.fileStore.readGlobalFile(bed_id, os.path.join(work_dir, bed_name))\n\n # use out_name if specified, otherwise sample\n if sample and not out_name:\n out_name = sample \n if out_name:\n out_tag = '{}_happy'.format(out_name)\n else:\n out_tag = 'happy_output'\n \n # output directory\n out_name = os.path.join(out_tag, 'happy')\n os.makedirs(os.path.join(work_dir, out_tag))\n \n # run the hap.py command\n cmd = ['hap.py', vcfeval_baseline_name, call_vcf_name,\n '--report-prefix', out_name, '--reference', fasta_name, '--write-vcf', '--write-counts', '--no-roc',\n '--threads', str(job.cores)]\n\n if bed_name:\n cmd += ['--false-positives', bed_name]\n \n try:\n context.runner.call(job, cmd, work_dir=work_dir)\n except:\n # Dump everything we need to replicate the alignment\n logging.error(\"hap.py VCF evaluation failed. Dumping files.\")\n context.write_output_file(job, os.path.join(work_dir, call_vcf_name))\n context.write_output_file(job, os.path.join(work_dir, vcfeval_baseline_name))\n # TODO: Dumping the sdf folder doesn't seem to work right. But we can dump the fasta\n context.write_output_file(job, os.path.join(work_dir, fasta_name))\n if bed_name is not None:\n context.write_output_file(job, os.path.join(work_dir, bed_name))\n \n raise\n\n\n # copy results to outstore \n \n # happy_output_summary.csv\n out_summary_id = context.write_output_file(job, os.path.join(work_dir, out_name + '.summary.csv'),\n out_store_path = '{}_summary.csv'.format(out_tag))\n\n # happy_output.tar.gz -- whole shebang\n context.runner.call(job, ['tar', 'czf', out_tag + '.tar.gz', out_tag], work_dir = work_dir)\n out_archive_id = context.write_output_file(job, os.path.join(work_dir, out_tag + '.tar.gz'))\n\n # happy_output_f1.txt Snp1-F1 TAB Indel-F1 (of variants marked as PASS)\n happy_results = parse_happy_summary(os.path.join(work_dir, out_name + '.summary.csv'))\n f1_path = os.path.join(work_dir, \"happy_f1.txt\") \n with open(f1_path, \"w\") as f:\n f.write('{}\\t{}\\n'.format(happy_results['SNP']['METRIC.F1_Score'], happy_results['INDEL']['METRIC.F1_Score']))\n context.write_output_file(job, f1_path, out_store_path = '{}_f1.txt'.format(out_tag))\n \n return {\n \"parsed_summary\": happy_results,\n \"summary\": out_summary_id,\n \"archive\": out_archive_id\n }\n\ndef run_sv_eval(job, context, sample, vcf_tbi_id_pair, vcfeval_baseline_id, vcfeval_baseline_tbi_id,\n min_sv_len, sv_overlap, sv_region_overlap, sv_smooth = 0, bed_id = None, out_name = ''):\n \"\"\" Run something like Peter Audano's bed-based comparison. Uses bedtools and bedops to do\n overlap comparison between indels. Of note: the actual sequence of insertions is never checked!\"\"\"\n\n # make a local work directory\n work_dir = job.fileStore.getLocalTempDir()\n\n # download the vcf\n call_vcf_id, call_tbi_id = vcf_tbi_id_pair[0], vcf_tbi_id_pair[1]\n call_vcf_name = \"{}calls.vcf.gz\".format(out_name)\n job.fileStore.readGlobalFile(vcf_tbi_id_pair[0], os.path.join(work_dir, call_vcf_name))\n job.fileStore.readGlobalFile(vcf_tbi_id_pair[1], os.path.join(work_dir, call_vcf_name + '.tbi'))\n\n # and the truth vcf\n vcfeval_baseline_name = '{}truth.vcf.gz'.format(out_name)\n job.fileStore.readGlobalFile(vcfeval_baseline_id, os.path.join(work_dir, vcfeval_baseline_name))\n job.fileStore.readGlobalFile(vcfeval_baseline_tbi_id, os.path.join(work_dir, vcfeval_baseline_name + '.tbi'))\n\n # and the regions bed\n if bed_id:\n regions_bed_name = '{}regions.bed'.format(out_name)\n job.fileStore.readGlobalFile(bed_id, os.path.join(work_dir, regions_bed_name))\n else:\n regions_bed_name = None\n\n if out_name and not out_name.endswith('_'):\n out_name = '{}_'.format(out_name)\n\n # convert vcfs to BEDs\n call_bed_name = '{}calls.bed'.format(out_name)\n baseline_bed_name = '{}truth.bed'.format(out_name)\n for vcf_name, bed_name in zip([call_vcf_name, vcfeval_baseline_name], [call_bed_name, baseline_bed_name]):\n # vg call sometimes makes IDs that are too long for bedops. we zap the ids here just in case\n temp_vcf_name = 'idfix-{}.vcf'.format(os.path.splitext(os.path.basename(vcf_name))[0])\n with open(os.path.join(work_dir, temp_vcf_name), 'w') as temp_vcf_file:\n context.runner.call(job, ['bcftools', 'view', '-h', vcf_name],\n work_dir = work_dir, outfile = temp_vcf_file)\n context.runner.call(job, [['bcftools', 'view', '-H', vcf_name],\n ['awk', '-F', '\\t', '-v', 'OFS=\\t', '{$3=\\\".\\\"; print $0;}']],\n work_dir = work_dir, outfile = temp_vcf_file)\n # then convert the fixed if vcf into bed with bedops\n with open(os.path.join(work_dir, bed_name + '.1del'), 'w') as bed_file:\n vcf2bed_cmd = [['cat', temp_vcf_name], ['vcf2bed']]\n context.runner.call(job, vcf2bed_cmd, work_dir = work_dir, outfile = bed_file, tool_name = 'bedops')\n \n # then expand the deletions, as vcf2bed writes them all with 1-sized intervals for some reason\n expand_deletions(os.path.join(work_dir, bed_name + '.1del'), os.path.join(work_dir, bed_name))\n\n # if the region bed's there, intersect both the calls and baseline \n if bed_id:\n clipped_calls_name = \"{}clipped_calls.bed\".format(out_name)\n clipped_baseline_name = \"{}clipped_baseline.bed\".format(out_name)\n\n \"\"\"\n bedtools intersect -a SV_FILE.bed -b sd_regions_200_0.bed -wa -f 0.50 -u\n\n * Get all SV variants that intersect SDs\n * -wa: Print whole SV record (not just the intersecting part)\n * -f 0.50: Require 50% of the SV to be in the SD\n * Prevents very large DELs from being tagged if they intersect with part of a region.\n * -u: Print matching SV call only once (even if it intersects with multiple variants)\n * Probably has no effect because of -f 0.50 and the way merging is done, but I leave it in in case I tweak something.\n \"\"\"\n for bed_name, clipped_bed_name in zip([call_bed_name, baseline_bed_name],\n [clipped_calls_name, clipped_baseline_name]):\n with open(os.path.join(work_dir, clipped_bed_name), 'w') as clipped_bed_file:\n context.runner.call(job, ['bedtools', 'intersect', '-a', bed_name, '-b', regions_bed_name,\n '-wa', '-f', str(sv_region_overlap), '-u'],\n work_dir = work_dir, outfile = clipped_bed_file)\n else:\n clipped_calls_name = call_bed_name\n clipped_baseline_name = baseline_bed_name\n \n # now do the intersection comparison\n\n \"\"\"\n To compare SV calls among sets, I typically use a 50% reciprocal overlap. A BED record of an insertion is only the point of insertion (1 bp) regardless of how large the insertion is. To compare insertions, I add the SV length (SVLEN) to the start position and use bedtools overlap. WARNING: Remember to collapse the insertion records back to one bp. If you accidentally intersected with SDs or TRF regions, SVs would arbitrarily hit records they don't actually intersect. I have snakemake pipelines handle this (bed files in \"byref\" or \"bylen\" directories) so it can never be mixed up.\n\n Intersect SVs:\n\n bedtools intersect -a SV_FILE_A.bed -b SV_FILE_B -wa -f 0.50 -r -u\n\n * Same bedtools command as before, but with \"-r\" to force A to overlap with B by 50% AND B to overlap with A by 50%. \"-u\" becomes important because clustered insertions (common in tandem repeats) will overlap with more than one variant.\n \"\"\"\n\n # expand the bed regions to include the insertion lengths for both sets.\n # we also break insertions and deletions into separate file. Otherwise, insertions can\n # intersect with deletions, inflating our accuracy.\n clipped_calls_ins_name = '{}ins_calls.bed'.format(out_name)\n clipped_baseline_ins_name = '{}ins_calls_baseline.bed'.format(out_name)\n clipped_calls_del_name = '{}del_calls.bed'.format(out_name)\n clipped_baseline_del_name = '{}del_calls_baseline.bed'.format(out_name)\n expand_insertions(os.path.join(work_dir, clipped_calls_name), os.path.join(work_dir, clipped_calls_ins_name),\n os.path.join(work_dir, clipped_calls_del_name), min_sv_len)\n expand_insertions(os.path.join(work_dir, clipped_baseline_name), os.path.join(work_dir, clipped_baseline_ins_name),\n os.path.join(work_dir, clipped_baseline_del_name), min_sv_len)\n\n tp_ins_name = '{}ins-TP-call.bed'.format(out_name)\n tp_del_name = '{}del-TP-call.bed'.format(out_name)\n tp_ins_rev_name = '{}ins-TP-baseline.bed'.format(out_name)\n tp_del_rev_name = '{}del-TP-baseline.bed'.format(out_name)\n fp_ins_name = '{}ins-FP.bed'.format(out_name)\n fp_del_name = '{}del-FP.bed'.format(out_name)\n fn_ins_name = '{}ins-FN.bed'.format(out_name)\n fn_del_name = '{}del-FN.bed'.format(out_name) \n for tp_indel_name, tp_indel_rev_name, calls_bed_indel_name, baseline_bed_indel_name, fp_indel_name, fn_indel_name in \\\n [(tp_ins_name, tp_ins_rev_name, clipped_calls_ins_name, clipped_baseline_ins_name, fp_ins_name, fn_ins_name),\n (tp_del_name, tp_del_rev_name, clipped_calls_del_name, clipped_baseline_del_name, fp_del_name, fn_del_name)]:\n\n # smooth out features so, say, two side-by-side deltions get treated as one. this is in keeping with\n # the coarse-grained nature of the analysis and is optional\n if sv_smooth > 0:\n calls_merge_name = calls_bed_indel_name[:-4] + '_merge.bed'\n baseline_merge_name = baseline_bed_indel_name[:-4] + '_merge.bed' \n with open(os.path.join(work_dir, calls_merge_name), 'w') as calls_merge_file:\n context.runner.call(job, ['bedtools', 'merge', '-d', str(sv_smooth), '-i', calls_bed_indel_name],\n work_dir = work_dir, outfile = calls_merge_file)\n with open(os.path.join(work_dir, baseline_merge_name), 'w') as baseline_merge_file:\n context.runner.call(job, ['bedtools', 'merge', '-d', str(sv_smooth), '-i', baseline_bed_indel_name],\n work_dir = work_dir, outfile = baseline_merge_file)\n calls_bed_indel_name = calls_merge_name\n baseline_bed_indel_name = baseline_merge_name\n \n # run the 50% overlap test described above for insertions and deletions\n with open(os.path.join(work_dir, tp_indel_name), 'w') as tp_file:\n context.runner.call(job, ['bedtools', 'intersect', '-a', calls_bed_indel_name,\n '-b', baseline_bed_indel_name, '-wa', '-f', str(sv_overlap), '-r', '-u'],\n work_dir = work_dir, outfile = tp_file) \n # we run other way so we can get false positives from the calls and true positives from the baseline \n with open(os.path.join(work_dir, tp_indel_rev_name), 'w') as tp_file: \n context.runner.call(job, ['bedtools', 'intersect', '-b', calls_bed_indel_name,\n '-a', baseline_bed_indel_name, '-wa', '-f', str(sv_overlap), '-r', '-u'],\n work_dir = work_dir, outfile = tp_file)\n # put the false positives in their own file\n with open(os.path.join(work_dir, fp_indel_name), 'w') as fp_file:\n context.runner.call(job, ['bedtools', 'subtract', '-a', calls_bed_indel_name,\n '-b', tp_indel_name], work_dir = work_dir, outfile = fp_file)\n # and the false negatives\n with open(os.path.join(work_dir, fn_indel_name), 'w') as fn_file:\n context.runner.call(job, ['bedtools', 'subtract', '-a', baseline_bed_indel_name,\n '-b', tp_indel_rev_name], work_dir = work_dir, outfile = fn_file)\n # todo: should we write them out in vcf as well?\n\n # summarize results into a table\n results = summarize_sv_results(os.path.join(work_dir, tp_ins_name),\n os.path.join(work_dir, tp_ins_rev_name),\n os.path.join(work_dir, fp_ins_name),\n os.path.join(work_dir, fn_ins_name),\n os.path.join(work_dir, tp_del_name),\n os.path.join(work_dir, tp_del_rev_name),\n os.path.join(work_dir, fp_del_name),\n os.path.join(work_dir, fn_del_name))\n\n # write the results to a file\n summary_name = os.path.join(work_dir, '{}sv_accuracy.tsv'.format(out_name))\n with open(summary_name, 'w') as summary_file:\n header = ['Cat', 'TP', 'TP-baseline', 'FP', 'FN', 'Precision', 'Recall', 'F1']\n summary_file.write('#' + '\\t'.join(header) +'\\n')\n summary_file.write('\\t'.join(str(x) for x in ['Total'] + [results[c] for c in header[1:]]) + '\\n')\n summary_file.write('\\t'.join(str(x) for x in ['INS'] + [results['{}-INS'.format(c)] for c in header[1:]]) + '\\n')\n summary_file.write('\\t'.join(str(x) for x in ['DEL'] + [results['{}-DEL'.format(c)] for c in header[1:]]) + '\\n')\n summary_id = context.write_output_file(job, os.path.join(work_dir, summary_name))\n\n # tar up some relavant data\n tar_dir = os.path.join(work_dir, '{}sv_evaluation'.format(out_name))\n os.makedirs(tar_dir)\n for dir_file in os.listdir(work_dir):\n if os.path.splitext(dir_file)[1] in ['.bed', '.tsv', '.vcf.gz', '.vcf.gz.tbi']:\n shutil.copy2(os.path.join(work_dir, dir_file), os.path.join(tar_dir, dir_file))\n context.runner.call(job, ['tar', 'czf', os.path.basename(tar_dir) + '.tar.gz', os.path.basename(tar_dir)],\n work_dir = work_dir)\n archive_id = context.write_output_file(job, os.path.join(work_dir, tar_dir + '.tar.gz'))\n\n return results\n\ndef expand_deletions(in_bed_name, out_bed_name):\n \"\"\"\n Expand every deletion in a BED file and update its end coordinate to reflect its length.\n with open(in_bed_name) as in_bed, open(out_ins_bed_name, 'w') as out_ins, open(out_del_bed_name, 'w') as out_del:\n ** We do this before intersection with regions of interest **\n \"\"\"\n with open(in_bed_name) as in_bed, open(out_bed_name, 'w') as out_bed:\n for line in in_bed:\n if line.strip():\n toks = line.strip().split('\\t')\n ref_len = len(toks[5])\n alt_len = len(toks[6])\n if ref_len > alt_len:\n assert int(toks[2]) == int(toks[1]) + 1\n # expand the deletion\n toks[2] = str(int(toks[1]) + ref_len)\n out_bed.write('\\t'.join(toks) + '\\n')\n else:\n # leave insertions as is for now\n out_bed.write(line)\n\ndef expand_insertions(in_bed_name, out_ins_bed_name, out_del_bed_name, min_sv_size):\n \"\"\"\n Go through every insertion in a BED file and update its end coordinate to reflect its length. This is done\n to compare two sets of insertions. We also break out deletions into their own file. \n ** We do this after intersection with regions of interest but before comparison **\n \"\"\"\n with open(in_bed_name) as in_bed, open(out_ins_bed_name, 'w') as out_ins, open(out_del_bed_name, 'w') as out_del:\n for line in in_bed:\n if line.strip():\n toks = line.strip().split('\\t')\n ref_len = len(toks[5])\n alt_len = len(toks[6])\n # filter out some vg call nonsense\n if toks[5] == '.' or toks[6] == '.':\n continue\n if ref_len < alt_len and alt_len >= min_sv_size:\n assert int(toks[2]) == int(toks[1]) + 1\n # expand the insertion\n toks[2] = str(int(toks[1]) + alt_len)\n out_ins.write('\\t'.join(toks) + '\\n')\n elif ref_len >= min_sv_size:\n # just filter out the deletion\n out_del.write(line)\n\ndef summarize_sv_results(tp_ins, tp_ins_baseline, fp_ins, fn_ins,\n tp_del, tp_del_baseline, fp_del, fn_del):\n \"\"\"\n Use the various bed files to compute accuracies. Also return a tarball of \n all the files used.\n \"\"\"\n def wc(f):\n with open(f) as ff:\n return sum(1 for line in ff)\n\n def pr(tp, fp, fn):\n prec = float(tp) / float(tp + fp) if tp + fp else 0\n rec = float(tp) / float(tp + fn) if tp + fn else 0\n f1 = 2.0 * tp / float(2 * tp + fp + fn) if tp else 0\n return prec, rec, f1\n\n header = []\n row = []\n\n # results in dict\n results = {}\n results['TP-INS'] = wc(tp_ins)\n results['TP-baseline-INS'] = wc(tp_ins_baseline)\n results['FP-INS'] = wc(fp_ins)\n results['FN-INS'] = wc(fn_ins)\n ins_pr = pr(results['TP-INS'], results['FP-INS'], results['FN-INS'])\n results['Precision-INS'] = ins_pr[0]\n results['Recall-INS'] = ins_pr[1]\n results['F1-INS'] = ins_pr[2]\n\n results['TP-DEL'] = wc(tp_del)\n results['TP-baseline-DEL'] = wc(tp_del_baseline)\n results['FP-DEL'] = wc(fp_del)\n results['FN-DEL'] = wc(fn_del)\n del_pr = pr(results['TP-DEL'], results['FP-DEL'], results['FN-DEL'])\n results['Precision-DEL'] = del_pr[0]\n results['Recall-DEL'] = del_pr[1]\n results['F1-DEL'] = del_pr[2]\n\n results['TP'] = results['TP-INS'] + results['TP-DEL']\n results['TP-baseline'] = results['TP-baseline-INS'] + results['TP-baseline-DEL'] \n results['FP'] = results['FP-INS'] + results['FP-DEL']\n results['FN'] = results['FN-INS'] + results['FN-DEL']\n tot_pr = pr(results['TP'], results['FP'], results['FN'])\n results['Precision'] = tot_pr[0]\n results['Recall'] = tot_pr[1]\n results['F1'] = tot_pr[2]\n\n return results \n\ndef vcfeval_main(context, options):\n \"\"\" command line access to toil vcf eval logic\"\"\"\n\n # check some options\n validate_vcfeval_options(options)\n \n # How long did it take to run the entire pipeline, in seconds?\n run_time_pipeline = None\n \n # Mark when we start the pipeline\n start_time_pipeline = timeit.default_timer()\n\n # Default to vcfeval\n if not options.happy and not options.sveval:\n options.vcfeval = True\n\n with context.get_toil(options.jobStore) as toil:\n if not toil.options.restart:\n start_time = timeit.default_timer()\n \n # Upload local files to the remote IO Store\n vcfeval_baseline_id = toil.importFile(options.vcfeval_baseline)\n call_vcf_id = toil.importFile(options.call_vcf)\n vcfeval_baseline_tbi_id = toil.importFile(options.vcfeval_baseline + '.tbi')\n call_tbi_id = toil.importFile(options.call_vcf + '.tbi') \n fasta_id = toil.importFile(options.vcfeval_fasta) if options.vcfeval_fasta else None\n bed_id = toil.importFile(options.vcfeval_bed_regions) if options.vcfeval_bed_regions is not None else None\n\n end_time = timeit.default_timer()\n logger.info('Imported input files into Toil in {} seconds'.format(end_time - start_time))\n\n # Init the outstore\n init_job = Job.wrapJobFn(run_write_info_to_outstore, context, sys.argv)\n \n # Make a root job\n if options.vcfeval:\n vcfeval_job = Job.wrapJobFn(run_vcfeval, context, None,\n (call_vcf_id, call_tbi_id),\n vcfeval_baseline_id, vcfeval_baseline_tbi_id,\n options.vcfeval_fasta, fasta_id, bed_id,\n score_field=options.vcfeval_score_field,\n cores=context.config.vcfeval_cores, memory=context.config.vcfeval_mem,\n disk=context.config.vcfeval_disk)\n init_job.addFollowOn(vcfeval_job)\n \n if options.happy:\n happy_job = Job.wrapJobFn(run_happy, context, None,\n (call_vcf_id, call_tbi_id),\n vcfeval_baseline_id, vcfeval_baseline_tbi_id,\n options.vcfeval_fasta, fasta_id, bed_id,\n cores=context.config.vcfeval_cores, memory=context.config.vcfeval_mem,\n disk=context.config.vcfeval_disk)\n init_job.addFollowOn(happy_job)\n\n if options.sveval: \n sv_job = Job.wrapJobFn(run_sv_eval, context, None,\n (call_vcf_id, call_tbi_id),\n vcfeval_baseline_id, vcfeval_baseline_tbi_id,\n options.min_sv_len, options.sv_overlap, options.sv_region_overlap,\n options.sv_smooth, bed_id, \n cores=context.config.vcfeval_cores, memory=context.config.vcfeval_mem,\n disk=context.config.vcfeval_disk)\n init_job.addFollowOn(sv_job)\n\n # Run the job\n toil.start(init_job)\n else:\n toil.restart()\n\n end_time_pipeline = timeit.default_timer()\n run_time_pipeline = end_time_pipeline - start_time_pipeline\n \n print(\"All jobs completed successfully. Pipeline took {} seconds.\".format(run_time_pipeline))\n \n \n","sub_path":"src/toil_vg/vg_vcfeval.py","file_name":"vg_vcfeval.py","file_ext":"py","file_size_in_byte":38332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"573880016","text":"# The MIT License (MIT)\n#\n# Copyright (c) 2019 Chris Osterwood for Capable Robot Components\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\nimport time\n\nimport board\nimport digitalio\nimport analogio\nfrom micropython import const\n\nfrom adafruit_bus_device.i2c_device import I2CDevice\n\n# pylint: disable=bad-whitespace\n_I2C_ADDR_USB = const(0x2D)\n_REVISION = const(0x0000)\n_VENDOR_ID = const(0x3000)\n_PRODUCT_ID = const(0x3002)\n_DEVICE_ID = const(0x3004)\n_HUB_CONFIG_1 = const(0x3006)\n_HUB_CONFIG_2 = const(0x3007)\n_HUB_CONFIG_3 = const(0x3008)\n_PORT_SWAP = const(0x30FA)\n_HUB_CTRL = const(0x3104)\n_SUSPEND = const(0x3197)\n_POWER_STATUS = const(0x30E5)\n_REMAP_12 = const(0x30FB)\n_REMAP_34 = const(0x30FC)\n_POWER_STATE = const(0x3100)\n_CONNECTION = const(0x3194)\n_DEVICE_SPEED = const(0x3195)\n_POWER_SELECT_1 = const(0x3C00)\n_POWER_SELECT_2 = const(0x3C04)\n_POWER_SELECT_3 = const(0x3C08)\n_POWER_SELECT_4 = const(0x3C0C)\n_CHARGE_CONFIG = const(0x343C)\n \n_CFG_REG_CMD = bytearray([0x99, 0x37, 0x00])\n_DEFAULT_PORT_MAP = [1, 2, 3, 4]\n_CUSTOM_PORT_MAP = [2, 4, 1, 3]\n\n_I2C_ADDR_MCP = const(0x20)\n_GPIO = const(0x09)\n# pylint: enable=bad-whitespace\n\ndef _register_length(addr):\n if addr in [_REVISION]:\n return 4\n\n if addr in [_VENDOR_ID, _PRODUCT_ID, _DEVICE_ID, _POWER_STATE]:\n return 2\n\n return 1\n\ndef bytearry_to_int(b, lsb_first=True):\n if lsb_first:\n x = 0\n shift = 0\n for char in b:\n x |= (char << shift*8)\n shift += 1\n else:\n x = 0\n for char in b:\n x <<= 8\n x |= char\n return x\n\ndef set_bit(value, bit):\n return value | (1< 0 \n\nclass USBHub:\n\n def __init__(self, i2c1_bus, i2c2_bus, force=False):\n\n ## Setup pins so that statue upon switchign to output\n ## is identical to the board electrical default. This\n ## allows object to be created an no state change occur.\n self.pin_rst = digitalio.DigitalInOut(board.USBRESET)\n self.pin_rst.switch_to_output(value=True)\n\n self.pin_hen = digitalio.DigitalInOut(board.USBHOSTEN)\n self.pin_hen.switch_to_output(value=False)\n\n try:\n self.pin_bcen = digitalio.DigitalInOut(board.USBBCEN)\n self.pin_bcen.switch_to_output(value=False)\n except AttributeError:\n print(\"WARN : Firmware does not define pin for battery charge configuration\")\n self.pin_bcen = None\n\n self.vlim = analogio.AnalogIn(board.ANVLIM)\n self.vlogic = analogio.AnalogIn(board.AN5V)\n\n self.i2c_device = I2CDevice(i2c2_bus, _I2C_ADDR_USB, probe=False)\n self.mcp_device = I2CDevice(i2c1_bus, _I2C_ADDR_MCP, probe=False)\n\n ## Here we are using the port remapping to determine if the hub\n ## has been previously configured. If so, we don't need to reset\n ## it or configure it and can just control it as-is.\n ##\n ## If the hub has not been configured (e.g. when the board is first \n ## powered on), this call will raise an OSError. That will then trigger\n ## the normal reset & configure process.\n try:\n self.remap = self.get_port_remap()\n print(\"USB Hub has been configured\")\n except OSError:\n self.remap = _DEFAULT_PORT_MAP\n print(\"USB Hub is in default state\")\n\n if self.remap == _DEFAULT_PORT_MAP or force:\n self.reset()\n self.configure()\n self.set_mcp_config()\n\n def _write_register(self, address, xbytes):\n\n if len(xbytes) != _register_length(address):\n raise ValueError(\"Incorrect payload length for register %d\" % address)\n\n ## 2 bytes for 'write' and count\n ## 4 bytes for address (base + offset)\n ## num bytes actually get written\n length = 2+4+len(xbytes)\n\n ## Prepare the pre-amble\n out = [\n 0x00,\n 0x00,\n length, # Length of rest of packet\n 0x00, # Write configuration register\n len(xbytes) & 0xFF, # Will be writing N bytes (later)\n 0xBF, 0x80,\n (address >> 8) & 0xFF, address & 0xFF\n ]\n\n ## Print address registers and data payload\n # row = [out[7], out[8], len(xbytes)] + list(xbytes)\n # print(row)\n\n with self.i2c_device as i2c:\n ## Write the pre-amble and then the payload\n i2c.write(bytearray(out+xbytes))\n\n ## Execute the Configuration Register Access command\n i2c.write(_CFG_REG_CMD)\n\n def _read_register(self, address):\n length = _register_length(address)\n\n ## Prepare the pre-amble\n out = [\n 0x00,\n 0x00,\n 0x06, # Length of rest of packet\n 0x01, # Read configuration register\n length & 0xFF, # Will be reading N bytes (later)\n 0xBF, 0x80,\n (address >> 8) & 0xFF, address & 0xFF\n ]\n\n inbuf = bytearray(length+1)\n\n with self.i2c_device as i2c:\n ## Write the pre-amble\n i2c.write(bytearray(out))\n\n ## Execute the Configuration Register Access command\n i2c.write(_CFG_REG_CMD)\n\n ## Access the part of memory where our data is\n i2c.write_then_readinto(bytearray([0x00, 0x06]), inbuf, stop=False)\n\n ## First byte is the length of the rest of the message.\n ## We don't want to return that to the caller\n return inbuf[1:length+1]\n\n # pylint: disable=invalid-name\n @property\n def id(self):\n buf = self._read_register(_REVISION)\n device_id = (buf[3] << 8) + buf[2]\n revision_id = buf[0]\n\n return device_id, revision_id\n\n @property\n def vendor_id(self):\n return bytearry_to_int(self._read_register(_VENDOR_ID))\n\n @property\n def product_id(self):\n return bytearry_to_int(self._read_register(_PRODUCT_ID))\n\n @property\n def speeds(self):\n conn = bytearry_to_int(self._read_register(_CONNECTION))\n speed = bytearry_to_int(self._read_register(_DEVICE_SPEED))\n\n out = [0]*5\n\n ## Have to follow logical to physical remapping\n for idx, port in enumerate(self.remap):\n out[port] = (speed >> (idx*2)) & 0b11\n\n ## Upstream port is not in the speed register, so take data from\n ## the connection register. Unfortunately, no way to know speed.\n out[0] = (conn & 0b1)*3\n\n return out\n\n def attach(self):\n ## 0xAA 0x55 : Exit SOC_CONFIG and Enter HUB_CONFIG stage\n ## 0xAA 0x56 : Exit SOC_CONFIG and Enter HUB_CONFIG stage with SMBus slave enabled\n out = [0xAA, 0x56, 0x00]\n\n with self.i2c_device as i2c:\n i2c.write(bytearray(out))\n\n def reset(self): \n time.sleep(0.05)\n\n if self.pin_bcen is not None:\n # Turn on 10 ohm resistor for charge strapping\n self.pin_bcen.value = True\n \n # Put in reset for at least 10 ms\n self.pin_rst.value = False\n time.sleep(0.05)\n\n # Must wait at least 1 ms after RESET_N deassertion for straps to be read\n # Testing has found this delay must be MUCH longer than 1 ms for subsequent\n # I2C calls to suceed.\n self.pin_rst.value = True\n time.sleep(0.05)\n\n if self.pin_bcen is not None:\n # Turn 10 ohm resistor off, so that SPI bus can operate properly\n self.pin_bcen.value = False\n\n def configure(self, opts={}):\n \n if \"highspeed_disable\" in opts.keys():\n highspeed_disable = opts[\"highspeed_disable\"]\n else:\n highspeed_disable = False\n \n self.set_hub_config_1(highspeed_disable=highspeed_disable, multitt_enable=True)\n\n ## Reverse DP/DM pints of upstream port and ports 3 & 4\n self.set_port_swap(values=[True, False, False, True, True])\n self.set_hub_control(lpm_disable=True)\n self.set_hub_config_3(port_map_enable=True)\n\n ## Remap ports so that case physcial markings match the USB\n self.set_port_remap(ports=_CUSTOM_PORT_MAP)\n\n self.set_charging_config()\n\n self.attach()\n\n time.sleep(0.02)\n\n\n def upstream(self, state):\n self.pin_hen.value = not state\n\n def set_port_swap(self, values=[False, False, False, False, False]):\n value = 0\n\n for idx, bit in enumerate(values):\n if bit:\n value = set_bit(value, idx)\n\n self._write_register(_PORT_SWAP, [value])\n\n def set_hub_control(self, lpm_disable=False, reset=False):\n value = lpm_disable << 1 | \\\n reset\n\n self._write_register(_HUB_CTRL, [value])\n\n def set_hub_config_1(self, self_powered=True, vsm_disable=False, highspeed_disable=False, multitt_enable=False, \n eop_disable=False, individual_current_sense=True, individual_port_power=True):\n\n ## individual_current_sense : 0 -> ganged sensing, 1 -> individual, 2 or 3 -> current sense not supported\n\n value = self_powered << 7 | \\\n vsm_disable << 6 | \\\n highspeed_disable << 5 | \\\n multitt_enable << 4 | \\\n eop_disable << 3 | \\\n individual_current_sense << 1 | \\\n individual_port_power\n\n self._write_register(_HUB_CONFIG_1, [value])\n\n def set_hub_config_3(self, port_map_enable=True, string_descriptor_enable=False):\n value = port_map_enable << 3 | \\\n string_descriptor_enable\n\n self._write_register(_HUB_CONFIG_3, [value])\n\n def set_port_remap(self, ports=[1, 2, 3, 4]):\n self.remap = ports\n\n port12 = ((ports[1] << 4) & 0xFF) | (ports[0] & 0xFF)\n port34 = ((ports[3] << 4) & 0xFF) | (ports[2] & 0xFF)\n\n self._write_register(_REMAP_12, [port12])\n self._write_register(_REMAP_34, [port34])\n\n def set_charging_config(self, ports=[1,2,3,4], ucs_lim=0b11, enable=True, dcp=True, se1=0b00, china_mode=False):\n\n ## ucs_lim : When controlling UCS through I2C, this sets the current limit.\n ## 0b00 : 500 mA\n ## 0b01 : 1000 mA\n ## 0b10 : 1500 mA\n ## 0b11 : 2000 mA\n\n ## 'dcp' is Dedicated Charging Mode. Ignored if china_mode is enabled.\n ## This mode only active when a USB Host is not present. When a host is \n ## present, CDP mode is used.\n\n ## Bit 1 & 2 are SE1. Enables SE1 charging mode for certain devices. \n ## This mode is only activated when a USB host is not present. When a \n ## host is present, the mode of operation is CDP. When SE1 mode and DCP \n ## mode are both enabled, the hub toggles between the two modes of \n ## operation as necessary to ensure the device can charge.\n ##\n ## 0b00 : Mode Disabled\n ## 0b01 : 1A mode (D-: 2.7V, D+: 2.0V)\n ## 0b10 : 2A mode (D-: 2.0V, D+: 2.7V)\n ## 0b11 : 2.5A mode enabled (D-: 2.7V, D+: 2.7V)\n\n ## Bit 0 is Battery Charging Support Enable. This bit enables CDP and \n ## must be set for any battery charging functions to be enabled. Other \n ## functions in addi- tion to CDP are enabled by setting their \n ## respective bits in addition to this bit.\n\n value = (ucs_lim & 0b11) << 6 | \\\n dcp << 5 | \\\n china_mode << 4 | \\\n (se1 & 0b11) << 1 | \\\n enable \n\n for port in ports:\n ## Register address is based on the port number\n self._write_register(_CHARGE_CONFIG+port-1, [value])\n\n def set_mcp_config(self, inputs=[False, False, False, False]):\n \"\"\"Set direction on MCP IO pins. 'inputs' list will set GP0 thru GP4 to inputs, if respective position is true\"\"\"\n\n ## Bits 7 thru 4 control USB data enables on downstream ports 1 thru 4, respectively.\n ## They must be set to 0 to make them outputs.\n value = 0b00000000 | \\\n inputs[3] << 3 | \\\n inputs[2] << 2 | \\\n inputs[1] << 1 | \\\n inputs[0]\n\n with self.mcp_device as i2c:\n ## Write to IODIR register and defaults to other registers.\n ## 0x09 (GPIO) register has to be 0b0000_0000 so that downstream ports default to enabled\n i2c.write(bytearray([0x00, value, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]))\n\n def _read_mcp_register(self, addr):\n inbuf = bytearray(1)\n\n with self.mcp_device as i2c:\n i2c.write_then_readinto(bytearray([addr]), inbuf)\n \n return inbuf[0]\n\n def data_state(self):\n value = self._read_mcp_register(_GPIO)\n return [not get_bit(value, 7), not get_bit(value, 6), not get_bit(value, 5), not get_bit(value, 4)]\n\n def data_enable(self, ports=[]):\n inbuf = bytearray(1)\n\n with self.mcp_device as i2c:\n i2c.write_then_readinto(bytearray([_GPIO]), inbuf)\n\n for port in ports:\n inbuf[0] = clear_bit(inbuf[0], 8-port)\n\n i2c.write(bytearray([_GPIO])+inbuf)\n\n def data_disable(self, ports=[]):\n inbuf = bytearray(1)\n\n with self.mcp_device as i2c:\n i2c.write_then_readinto(bytearray([_GPIO]), inbuf)\n\n for port in ports:\n inbuf[0] = set_bit(inbuf[0], 8-port)\n\n i2c.write(bytearray([_GPIO])+inbuf)\n\n\n def get_port_remap(self):\n port12 = bytearry_to_int(self._read_register(_REMAP_12))\n port34 = bytearry_to_int(self._read_register(_REMAP_34))\n\n return [port12 & 0x0F, (port12 >> 4) & 0x0F, port34 & 0x0F, (port34 >> 4) & 0x0F]\n\n def power_state(self, ports=[1,2,3,4]):\n out = []\n\n for port in ports:\n data = self._read_register(_POWER_SELECT_1+(port-1)*4)[0]\n\n ## Bits 3:0 mapping:\n ## 0b000 : Port power is disabled\n ## 0b001 : Port is on if USB2 port power is on\n ## 0b010 : Port is on if designated GPIO is on\n\n ## Upstream disconnect and downstream connection cause 0b010\n ## So, we need to check for value > 0 (not just bit 0) to determine\n ## if port power is on or not.\n out.append((data & 0b111) > 0)\n\n return out\n\n def power_disable(self, ports=[]):\n for port in ports:\n self._write_register(_POWER_SELECT_1+(port-1)*4, [0x80])\n\n def power_enable(self, ports=[]):\n for port in ports:\n self._write_register(_POWER_SELECT_1+(port-1)*4, [0x81])\n\n @property\n def rails(self):\n vlim, vlogic = None, None\n\n if self.vlim is not None:\n voltage = float(self.vlim.value) / 65535.0 * self.vlim.reference_voltage \n vlim = voltage * (1870 + 20000) / 1870\n \n if self.vlogic is not None:\n voltage = float(self.vlogic.value) / 65535.0 * self.vlogic.reference_voltage \n vlogic = voltage * 2\n\n return vlim, vlogic\n \n","sub_path":"capablerobot_usbhub.py","file_name":"capablerobot_usbhub.py","file_ext":"py","file_size_in_byte":16216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"615444650","text":"import json\nimport os\nfrom urllib.parse import urlparse\n\nsites_to_domains = dict()\ndomains_to_ip = dict()\nip = dict()\ndomains = set()\nos.system('export PATH=$PATH:~/go/bin')\n\nwith open(\"1.json\") as f:\n i = 0\n for line in f:\n i += 1\n obj = json.loads(line)\n url = urlparse(obj[\"requestURL\"])\n domain = url.netloc\n sites_to_domains.setdefault(obj['siteURL'],set()).add(domain)\n cmd = 'echo ' + domain + ' | zdns A -retries 10'\n output = os.popen(cmd).readlines()\n for op in output:\n obj = json.loads(op)\n try:\n domain = obj['name']\n if obj['status'] == 'NOERROR':\n answers = obj['data']['answers']\n for answer in answers:\n domains_to_ip.setdefault(domain, set()).add(answer['answer'])\n ip.setdefault(answer['answer'], 0)\n ip[answer['answer']] += 1\n else:\n domains_to_ip.setdefault(domain, set()).add(obj['status'])\n except Exception as e:\n print(\"Exception: \", e)\n print(i)\n\nfor key in sites_to_domains:\n domain_list = \", \".join(sites_to_domains[key])\n sites_to_domains[key] = domain_list\n\nfor key in domains_to_ip:\n ip_list = \", \".join(domains_to_ip[key])\n domains_to_ip[key] = ip_list\n\nwith open(\"sites_to_domains_single.txt\", \"w\") as f:\n json.dump(sites_to_domains, f)\n\nwith open(\"domains_to_ip_single.txt\", \"w\") as f:\n json.dump(domains_to_ip, f)\n\nwith open(\"ip_freq_single.txt\", \"w\") as f:\n json.dump(ip, f)\n","sub_path":"src/ipsets_single.py","file_name":"ipsets_single.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"404385240","text":"import re\nimport os\nimport os.path as osp\nfrom fuzzywuzzy import process, fuzz\nfrom unidecode import unidecode\nimport pandas as pd\nfrom multiprocessing import Pool\nfrom functools import partial\n\nif os.path.exists('./config.ini'):\n import configparser\n config = configparser.ConfigParser()\n config.read('./config.ini')\n dst_path = config.get('config','BASE_MODEL_PATH')\nelse:\n dst_path = os.environ['BASE_MODEL_PATH']\n\nprint('bas path for references is : %s'%dst_path)\nref_marque_modele_path = dict(\n siv=osp.join(dst_path, 'esiv_marque_modele_genre.csv'),\n caradisiac=osp.join(dst_path, 'caradisiac_marque_modele.csv'),\n siv_caradisiac=osp.join(dst_path, 'esiv_caradisiac_marque_modele_genre.csv')\n )\n\nref_marque_modele = dict()\nfor key, value in ref_marque_modele_path.items():\n if os.path.exists(value):\n ref_marque_modele[key] = pd.read_csv(value).rename(columns={'alt': 'modele'})\n\ndef hash_table1(x):\n assert 'marque' in ref_marque_modele[x].columns\n assert 'modele' in ref_marque_modele[x].columns\n\n return ref_marque_modele[x].groupby(['marque']).apply(lambda x: x['modele'].to_list()).to_dict()\n\n\ndef hash_table2(x):\n assert 'marque' in ref_marque_modele[x].columns\n assert 'modele' in ref_marque_modele[x].columns\n #assert 'href' in ref_marque_modele[x].columns # link ref\n #assert 'src' in ref_marque_modele[x].columns # image ref source\n gp = ref_marque_modele[x].groupby(['marque', 'modele'])\n if not (gp.size() == 1).all():\n print(\"Be careful, your mapping %s is not unique\"%x)\n print(\"take first of :\")\n print(gp.size()[gp.size()>1])\n # assert (gp == 1).all(),\n\n return gp.first().to_dict('index')\n\n# dictionnaire pour acceder rapidement à tous les modeles d'une marque\nmarques_dict = {x: hash_table1(x) for x in ref_marque_modele.keys()}\n\n# dictionnaire pour acceder rapidement à href et src (images de caradisiac)\nsrc_dict = {x: hash_table2(x) for x in ref_marque_modele.keys()}\n\n\ndef reg_class(x):\n return '^(CLASSE ?)?{x} *[0-9]+(.*)'.format(x=x)\n\n\ndef reg_no_class(x):\n # '^(CLASSE ?){x}(?:\\w)(.*)'\n return '^(CLASSE ?){x}'.format(x=x)\n\n\nreplace_regex = {\n 'marque': {\n 'BW|B\\.M\\.W\\.|B\\.M\\.W|BMW I': 'BMW',\n 'FIAT\\.': 'FIAT',\n 'MERCEDES BENZ|MERCEDESBENZ|MERCEDES-BENZ': 'MERCEDES',\n 'NISSAN\\.': 'NISSAN',\n 'VOLKSWAGEN VW': 'VOLKSWAGEN',\n 'NON DEFINI|NULL': ''\n },\n 'modele': {\n 'KA\\+': 'KA',\n 'MEGANERTE\\/|MEGANERTE': 'MEGANE',\n 'MEGANE SCENIC': 'SCENIC',\n 'MEGANESCENIC': 'SCENIC',\n '(.*)ARA PIC(.*)': 'XSARA PICASSO', # XARA PICA -> XSARA PICASSO\n '(.*)ARAPIC(.*)': 'XSARA PICASSO',\n #'CLIOCHIPIE|CLIOBEBOP\\/|CLIORN\\/RT|CLIOBACCAR': 'CLIO I',\n #'CLIOSTE': 'CLIO I',\n 'CLIORL\\/RN\\/|CLIORL\\/RN|CLIOS' : 'CLIO',\n ' III$': ' 3',\n ' IV$': ' 4',\n '\\+2$': ' 2',\n 'NON DEFINI|NULL': '',\n 'BLUETEC|TDI|CDI': '',\n 'BLUETEC|TDI|CDI': '',\n 'REIHE': 'SERIE',\n 'DIESEL|ESSENCE': '',\n '\\s3P\\s': '', #3 PORTES\n '\\d+KWH':'' #KWH\n },\n 'MERCEDES': {**{reg_class(x): 'CLASSE %s'%x for x in ['A','B','C','E','G','S','V','X']},\n **{reg_no_class(x): '%s'%x for x in ['CL', 'GL', 'SL']}\n },\n 'RENAULT': {' ?(SOCIETE)': ''},\n 'BMW': {**{'(SERIE ?){x}'.format(x=x): '{x}'.format(x=x) for x in ['I', 'M', 'Z', 'X']},\n 'XDRIVE.*?\\s' : \"\" # Remove XDRIVEXXX unitil the next \\s\n },\n 'PEUGEOT': {\n 'EXPERT TRAVELLER': 'TRAVELLER' # undetermined case -> most recent\n },\n 'CITROEN' : {\n 'AIRCROSS': '',\n 'C4 SPACETOURER' : 'C4 PICASSO',\n 'JUMPY SPACE TOURER':'JUMPY' # undetermined case -> most recent\n },\n 'TOYOTA' : {\n 'PLUS|\\+':'',\n 'HYBRID':''\n },\n 'VOLKSWAGEN' : {\n 'PLUS|\\+':'',\n 'PASSAT CC':'CC'\n },\n 'FIAT': {\n '(X|L|C)$':'' # Letter at the end is removed\n },\n 'AUDI': {\n 'SPORTBACK|LIMOUSINE|ALLROAD|QUATRO|AVANT|LIMOUSINE':''\n },\n 'LAND ROVER': {\n 'SPORT$':''\n },\n 'OPEL': {\n '\\sX$':'' # X at the end is removed. eg. GRANDLAND X --> GRANDLAND\n },\n 'VOLVO': {\n 'CROSS COUNTRY':''\n },\n 'SEAT': {\n '\\sXL$|\\sXL\\s':'' # XL is removed at the end or between spaces\n },\n 'FORD': {\n 'CUSTOM|COURRIER|CONNECT' : ''\n }\n }\n\n\ndef cleaning(row: dict, column: str):\n \"\"\"Cleaning function\n\n Args:\n row: Detected boxes\n column: Image used for detection\n\n Returns:\n row: Cleaned marque and model\n \"\"\"\n if column == 'marque':\n row['marque'] = (\n unidecode(row['marque'])\n .replace('[^\\w\\s]', '')\n .replace('_', ' ')\n .replace('-', '')\n .upper()\n .strip()\n )\n\n elif column == 'modele':\n row['modele'] = (\n unidecode(row['modele'])\n .strip()\n .upper()\n .strip()\n )\n\n if row['marque'] not in ['MINI', 'DS']:\n row['modele'] = row['modele'].replace(row['marque'], '').strip()\n\n for a, b in replace_regex[column].items():\n row[column] = re.sub(a, b, row[column])\n\n # Renplacement conditionnel du modele\n if column == 'modele':\n if row['marque'] in replace_regex.keys():\n for a, b in replace_regex[row['marque']].items():\n row['modele'] = re.sub(a, b, row['modele'])\n\n return row\n\n\ntol = dict(marque=0.85, modele=0.7)\n\n\ndef fuzzymatch(row, column='marque', table_ref_name='siv'):\n score = 0\n match = ''\n\n if row[column] == '' or (column == 'modele' and row['score_marque'] < tol['marque']):\n row[column] = match\n row['score_%s'%column] = score\n return row\n\n try:\n if column == 'marque':\n choices = ref_marque_modele[table_ref_name][column].to_list()\n match, score = process.extractOne(\n str(row[column]),\n choices,\n )\n elif column == 'modele':\n choices = marques_dict[table_ref_name][row['marque']]\n match, score = process.extractOne(\n str(row[column]),\n choices,\n scorer=fuzz.WRatio\n )\n\n except Exception as e:\n print(e)\n print('Error in matching: {}'.format(column))\n print('Input {}'.format(row[column]))\n\n # print(\"%s => %s (%d)\"%(row[column], match, score))\n\n if score > tol[column]:\n row[column] = match\n\n row['score_%s'%column] = score\n\n return row\n\n\ndef wrap_cleaning(column, key_row):\n key = key_row[0]\n row = key_row[1]\n new_row = {'index': key}\n res = cleaning(row, column)\n\n new_row.update(res)\n return new_row\n\n\ndef wrap_fuzzymatch(table_ref_name, column, key_row):\n key = key_row[0]\n row = key_row[1]\n new_row = {'index': key}\n res = fuzzymatch(row, column, table_ref_name)\n new_row.update(res)\n return new_row\n\n\ndef df_cleaning(df, column, num_workers):\n if num_workers == 0:\n res = [wrap_cleaning(column, key_row) for key_row in df.iterrows()]\n else:\n # multiprocess le nettoyage\n pool = Pool(num_workers)\n func = partial(wrap_cleaning, column)\n res = pool.map(func, df.iterrows())\n pool.close()\n\n df_res = pd.DataFrame(res)\n return df_res.set_index('index').sort_index()\n\n\ndef df_fuzzymatch(df, column, table_ref_name, num_workers):\n # fuzzy match pour marque et modele hors des references\n if column == 'marque':\n filter = df[column].isin(ref_marque_modele[table_ref_name][column].to_list())\n elif column == 'modele':\n filter = df.eval('marque + modele').isin(ref_marque_modele[table_ref_name].eval('marque + modele'))\n\n df.loc[filter,'score_%s'%column] = 100\n df.loc[~filter,'score_%s'%column] = 0\n\n if num_workers == 0:\n res = [wrap_fuzzymatch(table_ref_name, column, key_row) for key_row in df.iterrows()]\n else:\n # multiprocess le fuzzy\n pool = Pool(num_workers)\n func = partial(wrap_fuzzymatch, table_ref_name, column)\n res = pool.map(func, df[~filter].iterrows())\n pool.close()\n\n df_res = pd.DataFrame(res)\n return pd.concat([df_res, df[filter].reset_index()]).set_index('index').sort_index()\n\ndict_post_cleaning = {'caradisiac':\n {\n ('CITROEN', 'DS3') : ('DS', 'DS 3')\n }\n }\n\n\ndef df_post_cleaning(df, table_ref_name):\n for before, after in dict_post_cleaning.get(table_ref_name, {}).items():\n # mitght wnat to instal numexp for optim\n filter = df.eval('marque == \"%s\" and modele == \"%s\"'%before)\n df.loc[filter, 'marque'] = after[0]\n df.loc[filter, 'modele'] = after[1]\n\n return df\n\n\ndef df_process(df, table_ref_name, num_workers):\n for column in ['marque', 'modele']:\n df = df_cleaning(df, column, num_workers)\n df = df_fuzzymatch(df, column, table_ref_name, num_workers)\n\n df = df_post_cleaning(df, table_ref_name)\n\n df['score'] = (df['score_marque'] + df['score_modele']) / 200\n\n return df[['marque', 'modele', 'score']]\n\n\ndef test_process():\n row = dict(modele='renault clio', marque='renault')\n res = fuzzymatch(cleaning(row))\n assert res == {\"marque\": \"RENAULT\", \"modele\": \"CLIO\", \"score\": 1}, res\n row = dict(modele='', marque='renault')\n cleaned = cleaning(row)\n res = fuzzymatch(cleaned)\n assert res == {\"marque\": \"RENAULT\", \"modele\": \"\", \"score\": 0.5}, res\n\n\nif __name__ == '__main__':\n test_process()\n","sub_path":"sivnorm/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":9972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"514608787","text":"#!/usr/bin/env python3\n# encoding=utf-8\ncf = open(\"commentslist.txt\").readlines()\nclist = []\nfor lines in cf:\n clist.append(lines.split())\n\ngf = open(\"gradeslist.txt\").read()\nglist = gf.split()\n\nwordfreq = dict()\nfor comments in clist:\n for word in comments:\n wordfreq[word] = wordfreq.get(word, 0) + 1\n\nworddict = dict()\ni = 0\nfor word in (word for word in wordfreq.keys() if wordfreq[word] > 1):\n worddict[word] = i\n i = i + 1\n\nsvmfile = open(\"svm.txt\", \"w\")\nfor g, c in zip(glist, clist):\n svmfile.write(str(g) + \" \")\n cdict = dict()\n for word in worddict.keys():\n if word in c:\n cdict[worddict[word]] = c.count(word)\n for (word, freq) in cdict.items():\n svmfile.write(str(word) + \":\" + str(freq) + \" \")\n svmfile.write(\"\\n\")\nsvmfile.close()\n","sub_path":"code/make_svm_file.py","file_name":"make_svm_file.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"54578110","text":"from func import primes\n\n__author__ = \"Bungogood\"\n\n'''\nProblem 7\n\n10001st prime\n'''\n\ndef f(x):\n p = primes()\n for _ in range(x-1):\n next(p)\n return next(p)\n\nif __name__ == \"__main__\":\n print(f(10001))","sub_path":"Problem-007.py","file_name":"Problem-007.py","file_ext":"py","file_size_in_byte":220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"388044238","text":"# pylint: disable=W0621,C0114,C0115,C0116,W0212,W0613\n\nclass ExonMock:\n # pylint: disable=too-few-public-methods\n def __init__(self, start, stop, frame):\n self.start = start\n self.stop = stop\n self.frame = frame\n\n\nclass TranscriptModelMock:\n # pylint: disable=too-many-instance-attributes\n def __init__(\n self, strand, cds_start, cds_end, exons, coding=None, is_coding=True\n ):\n self.strand = strand\n self.cds = [cds_start, cds_end]\n self.exons = exons\n self.chrom = \"1\"\n self.gene = \"B\"\n self.tr_id = \"123\"\n self.tr_name = \"123\"\n\n if coding is None:\n self.coding = self.exons\n else:\n self.coding = coding\n self._is_coding = is_coding\n\n def CDS_regions(self): # pylint: disable=invalid-name\n return self.coding\n\n def is_coding(self):\n return self._is_coding\n\n def all_regions(self):\n return self.exons\n\n\nclass ReferenceGenomeMock:\n # pylint: disable=no-self-use\n def get_sequence(self, chromosome, pos, pos_last):\n print((\"get\", chromosome, pos, pos_last))\n return \"\".join([chr(i) for i in range(pos, pos_last + 1)])\n\n\nclass CodeMock:\n # pylint: disable=too-few-public-methods\n startCodons = [\"ABC\", \"DEF\"]\n CodonsAaKeys: dict = {}\n\n\nclass AnnotatorMock:\n # pylint: disable=too-few-public-methods\n\n def __init__(self, reference_genome):\n self.reference_genome = reference_genome\n self.code = CodeMock()\n","sub_path":"dae/dae/effect_annotation/tests/mocks.py","file_name":"mocks.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"558526029","text":"from selenium import webdriver\r\nimport time, random\r\n\r\n# --------------------------------\r\n# - Meeting Bot by © Jared Turck -\r\n# --------------------------------\r\n\r\n# enter meeting ID 700-760-517\r\n# enter the same meeting with 200 bots\r\n\r\n\r\ndef timeout(cm, tm=1):\r\n time.sleep(tm)\r\n\r\ndef input_meeting_id():\r\n meeting_ID = input(\"Enter meeting ID: \")\r\n while False in (lambda m : [m.isdigit() == True, len(m) == 9])(meeting_ID.replace(\"-\", \"\")):\r\n meeting_ID = input(\"Incorrect input!\\nEnter meeting ID: \")\r\n return meeting_ID\r\n\r\ndef read_meeting_id_from_file():\r\n with open(\"meeting_id.txt\", \"r\") as file:\r\n return file.read()\r\n\r\ndef add_bot(current_bot_name):\r\n meeting_ID = read_meeting_id_from_file()\r\n driver = webdriver.Chrome(\"chromedriver.exe\")\r\n\r\n driver.get(\"https://app.gotomeeting.com/home.html\")\r\n input1 = driver.find_element_by_id(\"meetingId\")\r\n timeout(input1.send_keys((lambda x : x[:3]+\"-\"+x[3:6]+\"-\"+x[6:])(meeting_ID.replace(\"-\",\"\"))), tm=3)\r\n timeout(driver.find_element_by_id(\"joinMeeting\").click(), tm=1)\r\n timeout(driver.find_element_by_xpath('//button[@data-automation-id=\"onboarding-continue-no-audio\"]').click(), tm=1)\r\n\r\n # add a bot to the meeting\r\n driver.find_element_by_id(\"attendee-name\").send_keys(current_bot_name)\r\n driver.find_element_by_xpath('//button[@data-automation-id=\"change-name-and-email-dialog__submit\"]').click()\r\n\r\n\r\nadd_bot(\"bot_\" + str(random.randint(1,999999)))\r\ninput(\"end...\")\r\n","sub_path":"Python/!PYTHON/py/meeting bot/add_bot.py","file_name":"add_bot.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"418588121","text":"from yahoo_finance import Share\nimport numpy as np\nimport pandas as pd\nfrom datetime import datetime, timedelta\n\n\ndef get_yahoo_csv(symbols, years_before):\n '''\n INPUT: historical price for symbols in seleted period of time.\n OUTPUT: save as .csv file in each symbols.\n '''\n days_before = years_before * 365 #trasfer years into days\n today = datetime.now().strftime('%Y-%m-%d') #make today as str\n date = datetime.now() - timedelta(days=days_before) #date is days before from today\n\n symbol = Share(symbols) \n sym = pd.DataFrame(symbol.get_historical(date.strftime('%Y-%m-%d'), today))[::-1]\n sym.columns = map(str.lower, sym.columns)\n sym.index = sym['date']\n sym = sym.drop(['symbol', 'date'], axis=1)\n \n print(\"Inserted {} days {} data.\".format(days_before, symbol.get_name()))\n sym.to_csv(\"{}.csv\".format(symbol.get_name()))\n return sym","sub_path":"[DSCI6005] LSTM_TimeSeries_Analysis_YAHOO_API/getData_yahoo.py","file_name":"getData_yahoo.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"290554793","text":"#!/home/arcsight/miniconda/bin/python2.7\n\n__date__ = \"07/19/2015\"\n__author__ = \"AlienOne\"\n__copyright__ = \"MIT\"\n__credits__ = [\"Justin Jessup\"]\n__license__ = \"MIT\"\n__version__ = \"1.0\"\n__maintainer__ = \"AlienOne\"\n__email__ = \"Jessup.Justin@target.com\"\n__status__ = \"Production\"\n\n\nimport os\nimport csv\nimport psutil\nimport datetime\nimport smtplib\nimport socket\nimport subprocess\nimport threading\nfrom datetime import timedelta\nfrom email.mime.text import MIMEText\n\n\ndef git_backup_report(working_dir):\n \"\"\"\n GitHub backup of critical files\n :param working_dir: Current working directory\n :return: GitHub sync standard output\n \"\"\"\n os.chdir(working_dir)\n git_pull = subprocess.Popen(['git', 'pull', '-q'], stdout=subprocess.PIPE).communicate()\n git_add = subprocess.Popen(['git', 'add', '-A'], stdout=subprocess.PIPE).communicate()\n git_commit = subprocess.Popen(['git', 'commit', '-m', ' \"updates\"'], stdout=subprocess.PIPE).communicate()\n git_push = subprocess.Popen(['git', 'push', '-q'], stdout=subprocess.PIPE).communicate()\n git_actions = [git_pull, git_add, git_commit, git_push]\n for action in git_actions:\n return action\n\n\ndef email_alert(textfile, sender, rcpts, subject, smtp_server):\n \"\"\"\n Generic email function to send an email alert\n :param textfile: Attachment\n :param sender: Email address\n :param rcpts: List email addresses\n :param subject: String\n :param smtp_server: String\n :return: None\n \"\"\"\n fp = open(textfile, 'r')\n msg = MIMEText(fp.read())\n fp.close()\n msg['Subject'] = subject\n msg['From'] = ', '.join(sender)\n msg['To'] = ', '.join(rcpts)\n s = smtplib.SMTP(smtp_server)\n s.sendmail(sender, rcpts, msg.as_string())\n s.quit()\n\n\ndef get_stats():\n report_dict = {}\n\n \"\"\"CPU\"\"\"\n count = psutil.cpu_count(logical=True)\n utilization = str(psutil.cpu_percent(interval=1)) + \"%\"\n report_dict.update({'CPU Count': count, 'CPU Utilization': utilization})\n\n \"\"\"OS Tier Memory\"\"\"\n memory = psutil.virtual_memory()\n keys = [key.title() for key in dir(memory) if not key.startswith('_') and not key.startswith('__')]\n keys.remove('Count')\n keys.remove('Index')\n keys.remove('Percent')\n values = [(str(round(float(getattr(memory, key.lower())/1024/1024/1024), 2)) + 'GB') for key in keys]\n keys = [('Memory ' + key) for key in keys]\n report_dict.update(dict(zip(keys, values)))\n\n \"\"\"JVM Memory Utilization\"\"\"\n cmd = \"/usr/java/jdk1.7.0_79/bin/jstat -gc `lsof -i TCP:9999| grep LISTEN | tail -n 1 | awk '{print $2}'`| \" \\\n \"tail -n 1 | awk '{ print $3, $4, $6, $8, $9 }'\"\n ps = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)\n output = ps.stdout.read()\n ps.stdout.close()\n ps.wait()\n output = output.decode(\"utf-8\")\n jvm_mem_max = 4096\n jvm_mem_used = round(sum([float(x.strip()) for x in output.split(' ')])/1024, 2)\n jvm_mem_free = jvm_mem_max - jvm_mem_used\n report_dict.update({'JVM Mem Max': (str(jvm_mem_max) + \"MB\"),\n 'JVM Mem Used': (str(jvm_mem_used) + \"MB\"),\n 'JVM Mem Free': (str(jvm_mem_free) + \"MB\")})\n\n \"\"\"Disk Usage\"\"\"\n arc_partition = \"/opt/data\"\n disk = psutil.disk_usage(arc_partition)\n keys = [key.title() for key in dir(disk) if not key.startswith('_') and not key.startswith('__')]\n keys.remove('Count')\n keys.remove('Index')\n keys.remove('Percent')\n values = [(str(round(float(getattr(disk, key.lower())/1024/1024/1024), 2)) + 'GB') for key in keys]\n keys = [('Disk ' + key) for key in keys]\n report_dict.update(dict(zip(keys, values)))\n\n \"\"\"Boot Time\"\"\"\n boot = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime(\"%Y-%m-%d %H:%M:%S\")\n report_dict.update({'Last Reboot': boot})\n\n \"\"\"OS Uptime\"\"\"\n with open('/proc/uptime', 'r') as f:\n uptime_seconds = float(f.readline().split()[0])\n uptime_string = str(timedelta(seconds = uptime_seconds))\n report_dict.update({'OS Uptime': uptime_string})\n\n \"\"\"JVM UpTime\"\"\"\n cmd = \"ps -p `lsof -i TCP:9999| grep LISTEN | \" \\\n \"tail -n 1 | awk '{print $2}'` -o etime \"\n ps = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)\n output = ps.stdout.read()\n ps.stdout.close()\n ps.wait()\n output = output.decode(\"utf-8\")\n output = output.split(' ' )\n output = output[len(output) - 1].split('\\n')[0]\n report_dict.update({'JVM Uptime': output})\n\n \"\"\"Build CSV Report\"\"\"\n hostname = socket.gethostname()\n the_date = datetime.datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\")\n csv_filename = \"/home/arcsight/LoggerStats/simlogc17/stats_report.csv\"\n report_dict.update({'DateTime': the_date, 'Hostname': hostname})\n headers = [\"Hostname\", \"DateTime\", \"OS Uptime\", \"Last Reboot\", \"Memory Total\", \"Memory Used\",\n \"Memory Available\", \"Memory Free\", \"Memory Buffers\", \"Memory Cached\", \"Memory Active\",\n \"Memory Inactive\", \"JVM Uptime\", \"JVM Mem Max\", \"JVM Mem Used\", \"JVM Mem Free\",\n \"CPU Count\", \"CPU Utilization\", \"Disk Total\", \"Disk Free\", \"Disk Used\"]\n products = [report_dict]\n if not os.path.isfile(csv_filename):\n with open(csv_filename, 'w') as fh:\n w = csv.DictWriter(fh, headers)\n w.writer.writerow(headers)\n w.writerows(products)\n else:\n with open(csv_filename, 'a') as fh:\n w = csv.DictWriter(fh, headers)\n w.writerows(products)\n working_dir = \"/home/arcsight/LoggerStats/simlogc17\"\n git_backup_report(working_dir)\n threading.Timer(300, get_stats).start()\n\n\ndef email_report():\n csv_filename = \"/home/arcsight/LoggerStats/simlogc17/stats_report.csv\"\n email_file = csv_filename\n sender = \"root@localhost\"\n rcpts = \"Jessup.Justin@target.com\"\n subject = \"ESM Metrics Report\"\n smtp_server = \"localhost\"\n #email_alert(email_file, sender, rcpts, subject, smtp_server)\n threading.Timer(86400, email_report).start()\n\n\ndef main():\n get_stats()\n #email_report()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"get_logger_stats.py","file_name":"get_logger_stats.py","file_ext":"py","file_size_in_byte":6106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"513428688","text":"from tkinter import *\n\n# root = Tk()\n\n# img = PhotoImage(file=\"../../Pictures/FinishHim.png\")\n\n# Label(root, image=img).pack(side=\"right\")\n\n# explanation = \"\"\"\n# \t\t\t\tAt present, only GIF and PPM/PGM\n# \t\t\t\tformats are supported, but an interface \n# \t\t\t\texists to allow additional image file\n# \t\t\t\tformats to be added easily.\n# \t\t\t \"\"\"\n# Label(root, \n# \t\t\tjustify=LEFT,\n# \t\t\tpadx = 10, \n# \t\t\ttext=explanation).pack(side=\"left\")\n\n# root.mainloop()\n\n\n\n\nroot = Tk()\n# logo = PhotoImage(file=\"../images/python_logo_small.gif\")\nimg = PhotoImage(file=\"../../Pictures/FinishHim.png\")\n\nLabel(root, \n compound = CENTER,\n text=\"\"\"At present, only GIF and PPM/PGM\n\t\t\t\t\tformats are supported, but an interface \n\t\t\t\t\texists to allow additional image file\n\t\t\t\t\tformats to be added easily.\"\"\", \n image=img).pack(side=\"right\")\n\nroot.mainloop()\n\n# We can have the image on the right side and the text left justified with a padding of 10 pixel on the left and right side by changing the Label command like this: \n'''\nw = Label(root, \n\t\t justify=LEFT,\n\t\t compound = LEFT,\n\t\t padx = 10, \n\t\t text=explanation, \n\t\t image=logo).pack(side=\"right\")\n'''\n","sub_path":"Area52/Modules/tkinter/tkinter Image pack.py","file_name":"tkinter Image pack.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"220985575","text":"# Copyright (c) 2015-present, Facebook, Inc.\n# All rights reserved.\n# model settings\nnorm_cfg = dict(type='SyncBN', requires_grad=True)\nmodel = dict(\ntype='EncoderDecoder',\n pretrained=None,\n backbone=dict(\n type='XCiT',\n patch_size=16,\n embed_dim=384,\n depth=12,\n num_heads=8,\n mlp_ratio=4,\n qkv_bias=True,\n ),\n neck=dict(\n type='FPN',\n in_channels=[384, 384, 384, 384],\n out_channels=384,\n num_outs=4),\n decode_head=dict(\n type='FPNHead',\n in_channels=[384, 384, 384, 384],\n in_index=[0, 1, 2, 3],\n feature_strides=[16, 16, 16, 16],\n channels=128,\n dropout_ratio=0.1,\n num_classes=150,\n norm_cfg=norm_cfg,\n align_corners=False,\n loss_decode=dict(\n type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)),\n # model training and testing settings\n train_cfg=dict(),\n test_cfg=dict(mode='whole'))\n","sub_path":"semantic_segmentation/configs/_base_/models/sem_fpn_xcit_p16.py","file_name":"sem_fpn_xcit_p16.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"366664056","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport time\nfrom multiprocessing import Process, Value, Lock\n\n\ndef func(val, lock):\n\tfor i in range(50):\n\t\ttime.sleep(0.01)\n\t\twith lock:\n\t\t\tval.value += 1\n\t\t\nif __name__ == \"__main__\":\n\t # 多进程无法使用全局变量,multiprocessing 提供的 Value 是一个代理器,\n\t # 可以实现在多进程中共享这个变量\n\tv = Value('i', 0)\n\tlock = Lock()\n\tprocs = [Process(target=func, args=(v, lock)) for i in range(10)]\n\t\n\tfor p in procs:\n\t\tp.start()\n\tfor p in procs:\n\t\tp.join()\n\t\t\n\tprint(v.value)","sub_path":"linux_lou_plus/step_7/multiprocess/process_sys.py","file_name":"process_sys.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"318877850","text":"import psutil, os\nimport pdb\nimport subprocess as sp\nid = 0\np = None\n\nwhile p == None:\n\tfor proc in psutil:\n\t\tpsutil.process_iter()\n\t\tif \"PROCEXP\" in str(proc.name):\n\t\t\t\tp = proc\nfor maps in p.memory_maps():\n\tfor m in maps:\n\t\tprint(m)\np = pdb.Pdb()","sub_path":"getpid.py","file_name":"getpid.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"210825744","text":"import subprocess\nimport argparse\nimport pandas as pd\nimport os\nimport glob\nimport shutil\nimport sys\n\n#local imports\nfrom plink_helper.plink_driver import Driver\n\n#QC and data cleaning\nclass QC(Driver):\n def __init__(self, geno_path, rare=False):\n super().__init__(geno_path)\n # create new names for each step\n self.geno_call_rate = geno_path + \"_call_rate\"\n self.geno_het = self.geno_call_rate + \"_het\"\n self.geno_sex = self.geno_het + \"_sex\"\n self.geno_relatedness = self.geno_sex + \"_relatedness\"\n self.geno_variant = self.geno_relatedness + \"_variant\"\n self.geno_final = self.geno_variant + \"_final\"\n self.tmp_file_list = [self.geno_call_rate, self.geno_het, self.geno_sex, self.geno_relatedness, self.geno_variant]\n self.rare = rare\n\n def call_rate_pruning(self, geno_path):\n\n out_path = self.out_path\n\n step = \"PRUNING FOR CALL RATE\"\n print(step)\n bash1 = \"awk '{print $1,$2,$6}' \" + geno_path + '.fam > ' + geno_path + '.phenos'\n bash2 = \"plink --bfile \" + geno_path + \" --mind 0.05 --make-bed --out \" + geno_path + \"_call_rate\"\n bash3 = \"mv \" + geno_path + \"_call_rate.irem \" + out_path + \"CALL_RATE_OUTLIERS.txt\"\n\n cmds = [bash1, bash2, bash3]\n\n self.run_cmds(cmds, step)\n \n \n def het_pruning(self, geno_path):\n\n out_path = self.out_path\n \n step = \"PRUNING FOR HETEROZYGOSITY\"\n print(step)\n \n \n bash1 = \"plink --bfile \" + geno_path + \" --geno 0.01 --maf 0.05 --indep-pairwise 50 5 0.5 --out \" + out_path + \"pruning\"\n bash2 = \"plink --bfile \" + geno_path + \" --extract \" + out_path + \"pruning.prune.in --make-bed --out \" + out_path + \"pruned_data\"\n bash3 = \"plink --bfile \" + out_path + \"pruned_data --het --out \" + out_path + \"prunedHet\"\n bash4 = \"awk '{if ($6 <= -0.25) print $0 }' \" + out_path + \"prunedHet.het > \" + out_path + \"outliers1.txt\" \n bash5 = \"awk '{if ($6 >= 0.25) print $0 }' \" + out_path + \"prunedHet.het > \" + out_path + \"outliers2.txt\" \n bash6 = \"cat \" + out_path + \"outliers2.txt \" + out_path + \"outliers1.txt > \" + out_path + \"HETEROZYGOSITY_OUTLIERS.txt\"\n bash7 = \"plink --bfile \" + geno_path + \" --remove \" + out_path + \"HETEROZYGOSITY_OUTLIERS.txt --make-bed --out \" + geno_path + \"_het\"\n\n cmds = [bash1, bash2, bash3, bash4, bash5, bash6, bash7]\n \n self.run_cmds(cmds, step)\n\n \n def sex_check(self, geno_path):\n\n out_path = self.out_path\n \n step = \"CHECKING SEXES\"\n print(step)\n\n bash1 = \"plink --bfile \" + geno_path + \" --check-sex 0.25 0.75 --maf 0.05 --out \" + out_path + \"gender_check1\"\n bash2 = \"plink --bfile \"+ geno_path + \" --chr 23 --from-bp 2699520 --to-bp 154931043 --maf 0.05 --geno 0.05 --hwe 1E-5 --check-sex 0.25 0.75 --out \" + out_path + \"gender_check2\"\n bash3 = \"grep 'PROBLEM' \" + out_path + \"gender_check1.sexcheck > \" + out_path + \"problems1.txt\"\n bash4 = \"grep 'PROBLEM' \" + out_path + \"gender_check2.sexcheck > \" + out_path + \"problems2.txt\"\n bash5 = \"cat \" + out_path + \"problems1.txt \" + out_path + \"problems2.txt > \" + out_path + \"GENDER_FAILURES.txt\"\n bash6 = \"cut -f 1,2 \" + out_path + \"GENDER_FAILURES.txt > \" + out_path + \"samples_to_remove.txt\"\n bash7 = \"plink --bfile \" + geno_path + \" --remove \" + out_path + \"samples_to_remove.txt --make-bed --out \" + geno_path + \"_sex\"\n\n cmds = [bash1, bash2, bash3, bash4, bash5, bash6, bash7]\n\n self.run_cmds(cmds, step)\n\n\n def ancestry_comparison(self, geno_path, ref_path):\n \n out_path = self.out_path\n step = \"PCA for Ancestry Comparison\"\n print(step)\n \n # set up files to add numbers for plotting (as done in Cornelis's script)\n \n bash1 = f\"plink --bfile {geno_path} --bmerge {ref_path} --out {out_path}bin_snplis --make-bed\"\n bash2 = f\"plink --bfile {geno_path} --flip {out_path}bin_snplis-merge.missnp --make-bed --out {geno_path}_flip\"\n bash3 = f\"plink --bfile {geno_path}_flip --bmerge {ref_path} --out {out_path}bin_snplis --make-bed\"\n bash4 = f\"plink --bfile {geno_path}_flip --exclude {out_path}bin_snplis-merge.missnp --out {geno_path}_flip_pruned --make-bed\"\n bash5 = f\"plink --bfile {geno_path}_flip_pruned --bmerge {ref_path} --out {out_path}bin_snplis --make-bed\"\n bash6 = f\"plink --bfile {out_path}bin_snplis --geno 0.01 --out {out_path}pca --make-bed --pca 4\"\n \n # then add some names here and there\n bash7 = f'grep \"EUROPE\" {out_path}pca.eigenvec > {out_path}eur.txt'\n bash8 = f'grep \"ASIA\" {out_path}pca.eigenvec > {out_path}asia.txt'\n bash9 = f'grep \"AFRICA\" {out_path}pca.eigenvec > {out_path}afri.txt'\n bash10 = f'grep -v -f {out_path}eur.txt {out_path}pca.eigenvec | grep -v -f {out_path}asia.txt | grep -v -f {out_path}afri.txt > {out_path}new_samples.txt'\n bash11 = f'cut -d \" \" -f 3 {geno_path}.fam > {out_path}new_samples_add.txt'\n bash12 = f'paste {out_path}new_samples_add.txt {out_path}new_samples.txt > {out_path}new_samples2.txt'\n bash13 = f\"awk -v label='1' -v OFS=' ' '{{print label, $0}}' {out_path}eur.txt > {out_path}euro.txt\"\n bash14 = f\"awk -v label='2' -v OFS=' ' '{{print label, $0}}' {out_path}asia.txt > {out_path}asiao.txt\"\n bash15 = f\"awk -v label='3' -v OFS=' ' '{{print label, $0}}' {out_path}afri.txt > {out_path}afrio.txt\"\n bash16 = f'cat {out_path}new_samples2.txt {out_path}euro.txt {out_path}asiao.txt {out_path}afrio.txt > {out_path}pca.eigenvec2'\n \n # R script for PCA plotting and filtering\n bash17 = f\"cp gwas/PCA_in_R.R {out_path}\"\n \n # eventually convert this to python and add to qc as function\n bash18 = f\"Rscript {out_path}PCA_in_R.R {out_path} --no-save\"\n \n # then back to plink to remove outliers\n bash19 = f\"plink --bfile {geno_path} --keep {out_path}PCA_filtered_europeans.txt --make-bed --out {geno_path}_heterozyg_hapmap\"\n bash20 = f\"cat {out_path}PCA_filtered_asians.txt {out_path}PCA_filtered_africans.txt {out_path}PCA_filtered_mixed_race.txt > {out_path}hapmap_outliers.txt\"\n \n cmds = [bash1, bash2, bash3, bash4, bash5, bash6, bash7, bash8, bash9, bash10, bash11, bash12, bash13, bash14, bash15, bash16, bash17, bash18, bash19, bash20]\n \n self.run_cmds(cmds, step) \n\n \n def relatedness_pruning(self, geno_path):\n\n out_path = self.out_path\n \n step = \"RELATEDNESS PRUNING\"\n print(step)\n\n bash1 = \"gcta --bfile \" + geno_path + \" --make-grm --out \" + out_path + \"GRM_matrix --autosome --maf 0.05\" \n bash2 = \"gcta --grm-cutoff 0.125 --grm \" + out_path + \"GRM_matrix --out \" + out_path + \"GRM_matrix_0125 --make-grm\"\n bash3 = \"plink --bfile \" + geno_path + \" --keep \" + out_path + \"GRM_matrix_0125.grm.id --make-bed --out \" + geno_path + \"_relatedness\"\n\n cmds = [bash1, bash2, bash3]\n\n self.run_cmds(cmds, step)\n\n\n ##variant checks\n def variant_pruning(self, geno_path):\n\n out_path = self.out_path\n \n step = \"VARIANT-LEVEL PRUNING\"\n print(step)\n\n # variant missingness\n bash1 = \"plink --bfile \" + geno_path + \" --make-bed --out \" + geno_path + \"_geno --geno 0.05\"\n\n #missingness by case control (--test-missing), using P > 1E-4\n bash2 = \"plink --bfile \" + geno_path + \"_geno --test-missing --out \" + out_path + \"missing_snps\" \n bash3 = \"awk '{if ($5 <= 0.0001) print $2 }' \" + out_path + \"missing_snps.missing > \" + out_path + \"missing_snps_1E4.txt\"\n bash4 = \"plink --bfile \" + geno_path + \"_geno --exclude \" + out_path + \"missing_snps_1E4.txt --make-bed --out \" + geno_path + \"_geno_missingsnp\"\n\n #missingness by haplotype (--test-mishap), using P > 1E-4\n bash5 = \"plink --bfile \" + geno_path + \"_geno_missingsnp --test-mishap --out \" + out_path + \"missing_hap\" \n bash6 = \"awk '{if ($8 <= 0.0001) print $9 }' \" + out_path + \"missing_hap.missing.hap > \" + out_path + \"missing_haps_1E4.txt\"\n bash7 = \"cat \" + out_path + \"missing_haps_1E4.txt | tr '|' '\\n' > \" + out_path + \"missing_haps_1E4_final.txt\"\n bash8 = \"plink --bfile \" + geno_path + \"_geno_missingsnp --exclude \" + out_path + \"missing_haps_1E4_final.txt --make-bed --out \" + geno_path + \"_geno_missingsnp_missinghap\"\n\n\n ###### THIS DOES NOT WORK WITHOUT PHENOTYPES!!!!!!!!\n #HWE from controls only using P > 1E-4\n bash9 = \"plink --bfile \" + geno_path + \"_geno_missingsnp_missinghap --filter-controls --hwe 1E-4 --write-snplist --out \" + out_path + \"hwe\"\n bash10 = \"plink --bfile \" + geno_path + \"_geno_missingsnp_missinghap --extract \" + out_path + \"hwe.snplist --make-bed --out \" + geno_path + \"_geno_missingsnp_missinghap_hwe\"\n bash11 = \"#### moved \" + geno_path + \"_geno_missingsnp_missinghap_hwe to \" + geno_path + \"_variant #####\"\n cmds = [bash1, bash2, bash3, bash4, bash5, bash6, bash7, bash8, bash9, bash10, bash11]\n\n self.run_cmds(cmds, step)\n\n exts = [\".bed\",\".bim\",\".fam\",\".log\"]\n for ext in exts:\n \n shutil.move(geno_path + \"_geno_missingsnp_missinghap_hwe\" + ext, geno_path + \"_variant\" + ext)\n\n\n def rare_prune(self, geno_path):\n\n out_path = self.out_path\n rare = self.rare\n # OPTIONAL STEP: if --rare flag included when running, rare variants will be left alone, otherwise they will be pruned with --maf 0.01\n bash = \"plink --bfile \" + geno_path + \" --maf 0.01 --make-bed --out \" + geno_path + \"_MAF\"\n \n if rare:\n print(\"SKIPPING FINAL MAF PRUNING (0.01)... RARE VARIANTS LEFT ALONE\")\n # call logging to do some custom logging\n log = self.logging()\n log.write(\"SKIPPING FINAL MAF PRUNING (0.01)... RARE VARIANTS LEFT ALONE\")\n log.write(\"\\n\")\n log.write(\"\\n\")\n\n exts = [\".bed\",\".bim\",\".fam\",\".log\"]\n for ext in exts:\n shutil.move(geno_path + ext, geno_path + \"_final\" + ext)\n\n log.write(\"MOVED \" + geno_path + \" to \" + geno_path + \"_final\")\n log.write(\"\\n\") \n\n else:\n print(\"RARE VARIANTS (MAF <= 0.01) PRUNING\")\n # call logging to do some custom logging\n log = self.logging()\n log.write(\"RARE VARIANTS (MAF <= 0.01) PRUNING WITH THE FOLLOWING COMMANDS:\")\n log.write(\"\\n\")\n log.write(\"\\n\")\n subprocess.run(bash, shell=True)\n log.write(bash)\n log.write(\"\\n\")\n\n new_log = open(geno_path + \".log\", \"r\")\n new_log_read = new_log.read()\n new_log.close()\n\n log.write(new_log_read)\n log.write(\"\\n\")\n log.write(\"***********************************************\")\n log.write(\"\\n\")\n log.write(\"\\n\")\n\n exts = [\".bed\",\".bim\",\".fam\",\".log\"]\n for ext in exts:\n shutil.move(geno_path + \"_MAF\" + ext, geno_path + \"_final\" + ext)\n\n log.write(\"MOVED \" + geno_path + \"_MAF to \" + geno_path + \"_final\")\n log.write(\"\\n\")\n log.close()\n \n \n def cleanup(self):\n print(\"CLEANING UP THE DIRECTORY OF INTERMEDIATE FILES\")\n print(\"***********************************************\")\n print()\n \n save_files = [self.geno_path + ext for ext in ['.bim','.bed','.fam','.log','.hh', '.phenos', '.PLINK_STEPS.log']] + [self.geno_final + ext for ext in ['.bim','.bed','.fam','.hh']] + [self.out_path + 'imputed']\n all_files = glob.glob(self.out_path + '*')\n rm_files = [x for x in all_files if x not in save_files]\n for file in rm_files:\n os.remove(file)\n \n","sub_path":"gwas/qc.py","file_name":"qc.py","file_ext":"py","file_size_in_byte":11954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"124418501","text":"#\n# Copyright (C) 2017 NEC, Corp.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n\nfrom neutron_lib.plugins import constants as nlib_const\nfrom neutron_lib.plugins import directory\nfrom oslo_config import cfg\nfrom oslo_log import helpers as log_helpers\nfrom oslo_log import log as logging\n\nfrom neutron_lbaas.drivers import driver_base\nfrom neutron_lbaas.drivers import driver_mixins\n\nfrom networking_odl.common import constants as odl_const\nfrom networking_odl.journal import full_sync\nfrom networking_odl.journal import journal\n\ncfg.CONF.import_group('ml2_odl', 'networking_odl.common.config')\nLOG = logging.getLogger(__name__)\n\nLBAAS_RESOURCES = {\n odl_const.ODL_LOADBALANCER: odl_const.ODL_LOADBALANCERS,\n odl_const.ODL_LISTENER: odl_const.ODL_LISTENERS,\n odl_const.ODL_POOL: odl_const.ODL_POOLS,\n odl_const.ODL_MEMBER: odl_const.ODL_MEMBERS,\n odl_const.ODL_HEALTHMONITOR: odl_const.ODL_HEALTHMONITORS\n}\n\n\nclass OpenDaylightLbaasDriverV2(driver_base.LoadBalancerBaseDriver):\n @log_helpers.log_method_call\n def __init__(self, plugin):\n super(OpenDaylightLbaasDriverV2, self).__init__(plugin)\n LOG.debug(\"Initializing OpenDaylight LBaaS driver\")\n self.load_balancer = ODLLoadBalancerManager(self)\n self.listener = ODLListenerManager(self)\n self.pool = ODLPoolManager(self)\n self.member = ODLMemberManager(self)\n self.health_monitor = ODLHealthMonitorManager(self)\n\n\nclass OpenDaylightManager(driver_mixins.BaseManagerMixin):\n \"\"\"OpenDaylight LBaaS Driver for the V2 API\n\n This code is the backend implementation for the OpenDaylight\n LBaaS V2 driver for OpenStack Neutron.\n \"\"\"\n\n @log_helpers.log_method_call\n def __init__(self, driver, obj_type):\n LOG.debug(\"Initializing OpenDaylight LBaaS driver\")\n super(OpenDaylightManager, self).__init__(driver)\n self.journal = journal.OpenDaylightJournalThread()\n self.obj_type = obj_type\n full_sync.register(nlib_const.LOADBALANCERV2, LBAAS_RESOURCES,\n self.get_resources)\n self.driver = driver\n\n def _journal_record(self, context, obj_type, obj_id, operation, obj):\n obj_type = (\"lbaas/%s\" % obj_type)\n journal.record(context, obj_type, obj_id, operation, obj)\n self.journal.set_sync_event()\n\n @staticmethod\n def get_resources(context, resource_type):\n plugin = directory.get_plugin(nlib_const.LOADBALANCERV2)\n if resource_type == odl_const.ODL_MEMBER:\n return full_sync.get_resources_require_id(plugin, context,\n plugin.get_pools,\n 'get_pool_members')\n\n obj_getter = getattr(plugin, 'get_%s' % LBAAS_RESOURCES[resource_type])\n return obj_getter(context)\n\n @log_helpers.log_method_call\n @driver_base.driver_op\n def create(self, context, obj):\n self._journal_record(context, self.obj_type, obj.id,\n odl_const.ODL_CREATE, obj)\n\n @log_helpers.log_method_call\n @driver_base.driver_op\n def update(self, context, obj):\n self._journal_record(context, self.obj_type, obj.id,\n odl_const.ODL_UPDATE, obj)\n\n @log_helpers.log_method_call\n @driver_base.driver_op\n def delete(self, context, obj):\n self._journal_record(context, self.obj_type, obj.id,\n odl_const.ODL_DELETE, obj)\n\n\nclass ODLLoadBalancerManager(OpenDaylightManager,\n driver_base.BaseLoadBalancerManager):\n\n @log_helpers.log_method_call\n def __init__(self, driver):\n super(ODLLoadBalancerManager, self).__init__(\n driver, odl_const.ODL_LOADBALANCER)\n\n @log_helpers.log_method_call\n @driver_base.driver_op\n def refresh(self, context, lb):\n # TODO(lijingjing): implement this method\n # This is intended to trigger the backend to check and repair\n # the state of this load balancer and all of its dependent objects\n pass\n\n @log_helpers.log_method_call\n @driver_base.driver_op\n def stats(self, context, lb):\n # TODO(rajivk): implement this method\n pass\n\n # NOTE(mpeterson): workaround for pylint\n # pylint raises false positive of abstract-class-instantiated\n @property\n def db_delete_method(self):\n return driver_base.BaseLoadBalancerManager.db_delete_method\n\n\nclass ODLListenerManager(OpenDaylightManager,\n driver_base.BaseListenerManager):\n\n @log_helpers.log_method_call\n def __init__(self, driver):\n super(ODLListenerManager, self).__init__(\n driver, odl_const.ODL_LISTENER)\n\n\nclass ODLPoolManager(OpenDaylightManager,\n driver_base.BasePoolManager):\n\n @log_helpers.log_method_call\n def __init__(self, driver):\n super(ODLPoolManager, self).__init__(\n driver, odl_const.ODL_POOL)\n\n\nclass ODLMemberManager(OpenDaylightManager,\n driver_base.BaseMemberManager):\n\n @log_helpers.log_method_call\n def __init__(self, driver):\n super(ODLMemberManager, self).__init__(\n driver, odl_const.ODL_MEMBER)\n\n journal.register_url_builder(odl_const.ODL_MEMBER,\n self.lbaas_member_url_builder)\n\n @staticmethod\n def lbaas_member_url_builder(row):\n return (\"lbaas/pools/%s/member\" % row.data.pool.id)\n\n\nclass ODLHealthMonitorManager(OpenDaylightManager,\n driver_base.BaseHealthMonitorManager):\n\n @log_helpers.log_method_call\n def __init__(self, driver):\n super(ODLHealthMonitorManager, self).__init__(\n driver, odl_const.ODL_HEALTHMONITOR)\n","sub_path":"networking_odl/lbaas/lbaasv2_driver_v2.py","file_name":"lbaasv2_driver_v2.py","file_ext":"py","file_size_in_byte":6264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"88664227","text":"import sys\n\ndef lun(x):\n d = {}\n for y in set(x):\n cnt = x.count(y)\n d.setdefault(cnt, list())\n d[cnt].append(y)\n f = sorted(d.keys())[0]\n print(0 if f > 1 else x.index(sorted(d[f])[0]) + 1)\n\nwith open(sys.argv[1], \"r\") as f:\n _ = list(map(lun, [[int(z) for z in x.split(\" \")] for x in f.read().split(\"\\n\") if x]))\n","sub_path":"Easy/lowest_unique_number.py","file_name":"lowest_unique_number.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"576905808","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nimport urllib.request\r\nimport time\r\nfrom PIL import Image\r\nimport os\r\nfrom PyPDF2 import PdfFileWriter, PdfFileReader\r\n\r\nComicNumber = 1\r\npages_to_delete = [0] #First page is 0\r\n\r\ncomlink = str(input('Enter link of site '))\r\n\r\nresponse = requests.get(comlink) \r\n\r\nsoup = BeautifulSoup(response.text, 'html.parser')\r\n\r\nfirst = True\r\nissue = str(input('Enter name of download '))\r\nkeyword = str(input('Input keyword for img '))\r\n\r\ndirectory = r\"C:\\Users\\Divyansh\\Desktop\\STuff\\Comics\\Manga\\\\\" + issue\r\nos.makedirs(directory)\r\nprint(directory)\r\nfor links in soup.find_all('a'):\r\n link = links.get('href')\r\n print(link)\r\n if '136' not in str(link):\r\n if 'chapter' in str(link):\r\n print(link)\r\n\r\n l = 1\r\n\r\n imagelist= []\r\n\r\n response = requests.get(link) \r\n\r\n soup = BeautifulSoup(response.text, 'html.parser')\r\n\r\n for page in soup.find_all('img'):\r\n if 'ldkmanga' not in str(page.get('src')):\r\n if keyword in str(page.get('src')):\r\n try:\r\n print(page.get('src'))\r\n urllib.request.urlretrieve(page.get('src'), r\"C:\\Users\\Divyansh\\Desktop\\STuff\\Python Files\\Tests\\\\\" + str(l) + \".jpg\")\r\n photo = Image.open(r\"C:\\Users\\Divyansh\\Desktop\\STuff\\Python Files\\Tests\\\\\" + str(l) + \".jpg\")\r\n pdf = photo.convert('RGB')\r\n imagelist.append(pdf)\r\n os.remove(r\"C:\\Users\\Divyansh\\Desktop\\STuff\\Python Files\\Tests\\\\\" + str(l) + \".jpg\")\r\n except:\r\n print('fel')\r\n l = l + 1\r\n\r\n ComicNumber = ComicNumber + 1\r\n\r\n link =link.replace(link[:34], '')\r\n link =link.replace('/', '')\r\n link =link.replace('-', ' ')\r\n print(link)\r\n\r\n comicname = link\r\n print(directory + '\\\\' + link)\r\n\r\n photo.save(directory + '\\\\' +comicname + '.pdf', save_all=True, append_images=imagelist)\r\n print('PDF MADE')\r\n\r\n #issue = str(int(issue) + 1)\r\n infile = PdfFileReader(directory+ '\\\\' + comicname + '.pdf', 'rb')\r\n output = PdfFileWriter()\r\n\r\n for i in range(infile.getNumPages()):\r\n if i not in pages_to_delete:\r\n p = infile.getPage(i)\r\n output.addPage(p)\r\n\r\n with open(directory + '\\\\' + comicname + '.pdf', 'wb') as f:\r\n output.write(f)\r\n\r\n print('Spoiler Fixed')\r\n","sub_path":"hooray.py","file_name":"hooray.py","file_ext":"py","file_size_in_byte":2680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"555799546","text":"from flask import Flask, render_template\nimport requests\n\napp = Flask(__name__)\n\n@app.route('/')\ndef hello_world():\n\treturn render_template('./home.html')\n\n@app.route('/resorts/')\ndef resorts_page():\n\treturn render_template(\"./mainpage_resorts.html\")\n\n@app.route('/resorts//')\ndef resort_page(resort):\n\tif resort == '1':\n\t\treturn render_template('./Steamboat.html')\n\tif resort == '2':\n\t\treturn render_template('./Vail.html')\n\tif resort == '3':\n\t\treturn render_template('./Breckenridge.html')\n\treturn 'nothing found'\n\n@app.route('/trails/')\ndef trails_page():\n\treturn render_template(\"./mainpage_trails.html\")\n\n@app.route('/trails//')\ndef trail_page(trail):\n\tif trail == '1':\n\t\treturn render_template('./flash_of_gold.html')\n\tif trail == '2':\n\t\treturn render_template('./strawberry_lane.html')\n\tif trail == '3':\n\t\treturn render_template('./aspen_alley_trail.html')\n\treturn 'nothing found'\n\n@app.route('/photos/')\ndef photos_page():\n\treturn render_template(\"./mainpage_photos.html\")\n\n@app.route('/photos//')\ndef photo_page(photo):\n\tif photo == '1':\n\t\treturn render_template('./flash_of_gold_pic.html')\n\tif photo == '2':\n\t\treturn render_template('./strawberry_lane_pic.html')\n\tif photo == '3':\n\t\treturn render_template('./aspen_alley_trail_pic.html')\n\treturn 'nothing found'\n\n@app.route('/about/')\ndef about_page():\n\treturn render_template('./about.html')\n\n@app.route('/carousel/')\ndef cmove():\n\treturn render_template('./carousel.html')\n\n@app.route('/githubstats/')\ndef githubstats():\n\tgithub_commits = \"https://api.github.com/repos/RobertHale/HikingAdventure/stats/contributors\"\n\tgithub_issues = \"https://api.github.com/repos/RobertHale/HikingAdventure/issues?state=all\"\n\n\t# Grab Total Commits\n\tresponse_c = requests.get(github_commits)\n\tcommit_array = response_c.json()\n\tperson = commit_array[0]\n\tcommits = 0\n\tcommits_each = {};\n\tfor person in commit_array:\n\t\tcommits = commits + person['total']\n\t\t# Stores each person's commit count separately\n\t\tcommits_each[person['author']['login']] = person['total']\n\n\n\t# Grab Total issues\n\tresponse_i = requests.get(github_issues)\n\tissue_array = response_i.json()\n\tlatest_issue = issue_array[0]\n\tissues = latest_issue['number']\n\n\n\t# Return data in a string\n\tdata = str(commits) + \" \" + str(issues) + \" \" + str(commits_each.get(\"victor40\", 0)) + \" \" + str(commits_each.get(\"duoALopez\", 0)) + \" \" + str(commits_each.get(\"alexdai186\", 0)) + \" \" + str(commits_each.get(\"RobertHale\", 0)) + \" \" + str(commits_each.get(\"vponakala\", 0)) + \" \" + str(commits_each.get(\"davepcast\", 0))\n\treturn data\n\nif __name__ == \"__main__\":\n\tapp.run()\n","sub_path":"flaskapp.py","file_name":"flaskapp.py","file_ext":"py","file_size_in_byte":2589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"46006973","text":"\"\"\"\nMicro Service that overrides attributes based on Registration Authority\n\"\"\"\nimport logging\n\nfrom satosa.internal_data import InternalResponse\nfrom satosa.micro_services.base import ResponseMicroService\n\nlogger = logging.getLogger('satosa')\n\nclass AttributeOverride(ResponseMicroService):\n \"\"\"\n Metadata info extracting micro_service\n \"\"\"\n\n def __init__(self, config, internal_attributes, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.overrides = config.get('overrides', {})\n logger.info(\"AttributeOverride micro_service is active\")\n\n def process(self, context, internal_response):\n logger.info(\"Process AttributeOverride\")\n try:\n ra = context.state['metadata']['ra']\n overrides = self.overrides[ra]\n logger.debug(f\"ra: {ra}\")\n for src, values in overrides.items():\n logger.debug(f\" src attribute: {src}\")\n for value, destination in values.items():\n dst_a = destination[0]\n dst_v = destination[1]\n logger.debug(f\" value: {value}\")\n logger.debug(f\" will replace dst attribute: {dst_a}\")\n logger.debug(f\" with value: {dst_v}\")\n # First, clear all the dst attribute values\n internal_response.attributes[dst_a] = [ v for v in internal_response.attributes[dst_a] if v != dst_v ]\n # Add the override value if the source contains the condition value\n if value in internal_response.attributes[src]:\n internal_response.attributes[dst_a].append(dst_v)\n\n except Exception as e:\n logger.debug(\"AttributeOverride {}\".format(e))\n\n return super().process(context, internal_response)\n","sub_path":"src/svs/attribute_override.py","file_name":"attribute_override.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"277396154","text":"# USAGE\n# python correct_skew.py --image images/neg_28.png\n\n\nimport numpy as np\nimport argparse\nimport cv2\nimport os\nimport sys\nfrom datetime import datetime\nimport logging\n\n'''\n# import mylogging\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\nformatter = logging.Formatter(\"%(asctime)s:%(level)s:%(filename)s:%(lineno)s: %(message)s\")\nfile_handler = logging.FileHandler(\"mylogger.log\")\nfile_handler.setLevel(logging.DEBUG)\nfile_handler.setFormatter(formatter)\n\nstream_handler = logging.StreamHandler()\nstream_handler.setLevel(logging.DEBUG)\nstream_handler.setFormatter(formatter)\n\nlogger.addHandler(file_handler)\nlogger.addHandler(stream_handler)\n'''\n\n\ndef getDeskewedFilename(srcName, id=None):\n\tfilename_w_ext = os.path.basename(srcName)\n\tfilename, file_extension = os.path.splitext(filename_w_ext)\n\thms = datetime.now().strftime('%d%H%M%S')\n\tif id != None:\n\t\tnewName = srcName.replace(filename, 'de'+filename+\"_\"+id+\"_\"+hms)\n\telse:\n\t\tnewName = srcName.replace(filename, 'de'+filename+\"_\"+hms)\n\treturn newName\n\n\ndef deskewImage(filename):\n\tlogging.info(filename)\n\ttry:\n\t\timage = cv2.imread(filename)\n\texcept:\n\t\tlogging.exception(\"message\")\n\n\t# cv2.imshow(\"Original\", image)\n\t# logging.info(\"Image...\\n\", image)\n\tret, image = cv2.threshold(image, 170, 255, cv2.THRESH_BINARY)\n\t# cv2.imshow(\"Original after threshold\", image)\n\n\t# convert the image to grayscale and flip the foreground\n\t# and background to ensure foreground is now \"white\" and\n\t# the background is \"black\"\n\tgray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\t# logging.info(\"\\nGray...\\n\", gray)\n\tgray = cv2.bitwise_not(gray)\n\t# cv2.imshow(\"Gray\", gray)\n\n\t# threshold the image, setting all foreground pixels to 255 and all background pixels to 0\n\tthresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]\n\t# logging.info(\"Thresh...\\n\", thresh)\n\t# cv2.imshow(\"Thresh\", thresh)\n\n\t# cv2.waitKey(0)\n\n\t# grab the (x, y) coordinates of all pixel values that\n\t# are greater than zero, then use these coordinates to\n\t# compute a rotated bounding box that contains all\n\t# coordinates\n\t# logging.info(\"np.where....\\n\", np.where(thresh > 0))\n\tcoords = np.column_stack(np.where(thresh > 0))\n\t# logging.info(\"coords..\\n\", coords)\n\tangle = cv2.minAreaRect(coords)[-1]\n\tlogging.info(\"angle: {}\".format(angle))\n\n\t'''\n\tlogging.info('----------------------------')\n\tcntrs, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\tfor cntr in cntrs:\n\t\tapprox = cv2.approxPolyDP(cntr, 0.01 * cv2.arcLength(cntr, True), True)\n\n\t\tif len(approx) == 4 and cv2.contourArea(cntr) > 10:\n\t\t\tlogging.info(\"size: \", cv2.contourArea(cntr))\n\t\t\tcv2.drawContours(image, [cntr], -1, (0, 0, 255), 1)\n\t\t\tcv2.imshow('Contour selected', image)\n\t\t\tcv2.waitKey(0)\n\tlogging.info('----------------------------')\n\t'''\n\n\t# the `cv2.minAreaRect` function returns values in the\n\t# range [-90, 0); as the rectangle rotates clockwise the\n\t# returned angle trends to 0 -- in this special case we\n\t# need to add 90 degrees to the angle\n\tif abs(angle) != 0.0:\n\t\tlogging.info(\"Angle needs to be adjusted..\")\n\t\tif angle < -45:\n\t\t\tangle = -(90 + angle)\n\n\t\t# otherwise, just take the inverse of the angle to make\n\t\t# it positive\n\t\telse:\n\t\t\tangle = -angle\n\n\t# rotate the image to deskew it\n\t(h, w) = image.shape[:2]\n\tcenter = (w // 2, h // 2)\n\tmiddle = cv2.getRotationMatrix2D(center, angle, 1.0)\n\trotated = cv2.warpAffine(image, middle, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)\n\n\trotated = cv2.cvtColor(rotated, cv2.COLOR_BGR2GRAY)\n\n\t'''\n\t# save rotated image to new file\n\tdeskewedFileName = getDeskewedFilename(filename)\n\tcv2.imwrite(deskewedFileName, rotated)\n\t'''\n\n\t# height, width, channels = rotated.shape\n\theight, width = rotated.shape\n\t# logging.info(\"Heiht:{}, Width:{}, Channels:{}\".format(height, width, channels))\n\t# dim2 = rotated.reshape(channels, height, width)\n\t# logging.info(dim2)\n\n\t# draw the correction angle on the image so we can validate it\n\t# cv2.putText(rotated, \"Angle: {:.2f} degrees\".format(angle), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)\n\n\t# show the output image\n\tlogging.info(\"[INFO] angle: {:.5f}\".format(angle))\n\t# cv2.imshow(\"Input\", image)\n\tcv2.imshow(\"Deskewed\", rotated)\n\tcv2.waitKey(0)\n\n\t'''\n\tShould have some logic to avoid memory leak.... like below\n\t'''\n\t# thresh.release()\n\t# gray.release()\n\t# image.release()\\\n\tdel thresh\n\tdel gray\n\tdel image\n\treturn deskewedFileName, rotated\n\n\nif __name__ == '__main__':\n\tif len(sys.argv) == 1:\n\t\t# deskewImage(\"../images/hkli_image4of5-2.png\")\n\t\t# deskewImage(\"../images/hkli_image1of5-1.png\")\n\t\t# deskewImage(\"../images/hkli_image1of5-2.png\")\n\t\t# deskewImage(\"../images/hkli_deskewed1.png\")\n\t\tdeskewImage(\"../images/hkli_skewed1_ppt.png\")\n\telse:\n\t\t# construct the argument parse and parse the argumentss\n\t\tap = argparse.ArgumentParser()\n\t\tap.add_argument(\"-i\", \"--image\", required=True, help=\"path to input image file\")\n\t\targs = vars(ap.parse_args())\n\t\tfilename = args[\"image\"]\n\t\tdeskewImage(filename)","sub_path":"hkfmi_apps/correct_skew.py","file_name":"correct_skew.py","file_ext":"py","file_size_in_byte":4989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"625701328","text":"class MyStatic:\n def reset(self): # 파이썬 메소드 선언 방식\n self.x = 0\n self.y = 0\n\na = MyStatic()\nMyStatic.reset(a) # 클래스 메소드\n# a.reset() 인스턴스 메소드\n\nprint('x의 값', a.x)\nprint('y의 값', a.y)\n\n\n","sub_path":"py_oop/py_static.py","file_name":"py_static.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"81496867","text":"from lxml import etree\nfrom copy import deepcopy\nimport json\nimport requests\n\nclass spiderLOLData():\n headers = {\"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) \"\n \"Chrome/48.0.2564.116 Safari/537.36\"}\n playerDetailUrl = \"http://lolbox.duowan.com/playerDetail.php\"\n testUrl = \"http://httpbin.org/get\"\n baseUrl = \"http://lolbox.duowan.com\"\n def __init__(self,serverName, playerName):\n self.data = {'serverName':serverName,'playerName':playerName}\n listUrl = self.baseUrl + '/matchList.php'\n r = requests.get(listUrl,params=self.data,headers = self.headers)\n self.html = etree.HTML(r.text)\n\n def getPageNum(self):\n result = self.html.xpath('//span[@class=\"page-num\"]')\n pageNum = result[0].text[3]\n return int(pageNum)\n\n def getPage(self,num):\n listUrl = self.baseUrl + '/matchList.php'\n data = deepcopy(self.data)\n data['page'] = num\n r = requests.get(listUrl,params=data,headers = self.headers)\n html = etree.HTML(r.text)\n return html\n\n def getRecordId(self,html):\n result = html.xpath('//li/@id')\n resList = []\n for item in result:\n item = item[3:]\n resList.append(item)\n return resList\n\n def getRecordIdAll(self):\n num = self.getPageNum()\n list = []\n for i in range(num):\n html = spl.getPage(i + 1)\n list.extend(spl.getRecordId(html))\n return list\n\n def getGameDetails(self,matchId):\n perGameDetailUrl = self.baseUrl + '/matchList/ajaxMatchDetail2.php'\n data = deepcopy(self.data)\n list = self.getRecordIdAll()\n data['favorate'] = '0'\n data['matchId'] = matchId\n r = requests.get(perGameDetailUrl,params=data,headers=self.headers)\n html = etree.HTML(r.text)\n listName = html.xpath('//div[@id=\"zj-table--A\"]//img/@data-playername')\n listMoney = html.xpath('//div[@id=\"zj-table--A\"]//td[@class=\"col2\"]')\n listKill = html.xpath('//div[@id=\"zj-table--A\"]//td[@class=\"col3\"]')\n listEquip = html.xpath('//div[@id=\"zj-table--A\"]//td[@class=\"col4\"]')\n gameInfo = {}\n gameList = []\n for i in range(len(listName)):\n info = {}\n info['name'] = listName[i]\n info['money'] = listMoney[i].text\n info['KDA'] = listKill[i].text\n gameList.append(info)\n gameInfo[\"胜利\"] = gameList\n listName = html.xpath('//div[@id=\"zj-table--B\"]//img/@data-playername')\n listMoney = html.xpath('//div[@id=\"zj-table--B\"]//td[@class=\"col2\"]')\n listKill = html.xpath('//div[@id=\"zj-table--B\"]//td[@class=\"col3\"]')\n listEquip = html.xpath('//div[@id=\"zj-table--B\"]//td[@class=\"col4\"]')\n gameList = []\n for i in range(len(listName)):\n info = {}\n info['Name'] = listName[i]\n info['Money'] = listMoney[i].text\n info['KDA'] = listKill[i].text\n gameList.append(info)\n gameInfo['失败'] = gameList\n return gameInfo\n\n def getGameDetailsAll(self):\n recordList = self.getRecordIdAll()\n dc = {}\n for record in recordList:\n dc[record] = self.getGameDetails(record)\n jsGameInfo = json.dumps(dc,indent=2,separators=(',',':'),sort_keys= True,ensure_ascii=False)\n print(jsGameInfo)\n #jsGameInfo = json.dumps(gameInfo,indent=2,separators=(',',':'),sort_keys= True,ensure_ascii=False)\n\nspl = spiderLOLData('电信九','cxllxn')\nspl.getGameDetailsAll()\n\n\n\n\n\n\n","sub_path":"Spider/spiderLOL.py","file_name":"spiderLOL.py","file_ext":"py","file_size_in_byte":3626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"579113725","text":"sql_list = [\r\n\t'DROP TABLE IF EXISTS id_source',\r\n\tf'CREATE TABLE id_source( \\\r\n\t\trow_id\t\tINTEGER PRIMARY KEY AUTOINCREMENT, \\\r\n\t\tversion \tTEXT, \\\r\n\t\tbatch_key \tBOOLEAN, \\\r\n\t\tcreated_on \tTEXT, \\\r\n\t\tcreated_at \tTEXT \\\r\n\t)',\r\n\r\n\t'DROP TABLE IF EXISTS batch_audit',\r\n\tf'CREATE TABLE batch_audit( \\\r\n\t\trow_id\t\tINTEGER PRIMARY KEY, \\\r\n\t\tcreated_on \tTEXT, \\\r\n\t\tcreated_at \tTEXT \\\r\n\t)',\r\n\r\n\t'DROP TABLE IF EXISTS proc_audit',\r\n\tf'CREATE TABLE proc_audit( \\\r\n\t\trow_id \t\tINTEGER PRIMARY KEY, \\\r\n\t\tbatch_id \tINTEGER, \\\r\n\t\tproc_action\tINTEGER, \\\r\n\t\tcreated_on \tTEXT, \\\r\n\t\tcreated_at \tTEXT \\\r\n\t)',\r\n\r\n\t'DROP TABLE IF EXISTS proc_action',\r\n\tf'CREATE TABLE proc_action( \\\r\n\t\trow_id\t\tINTEGER PRIMARY KEY AUTOINCREMENT, \\\r\n\t\taction \t\tTEXT \\\r\n\t)',\r\n\r\n\t'DROP TABLE IF EXISTS proc_status',\r\n\tf'CREATE TABLE proc_status( \\\r\n\t\trow_id\t\tINTEGER PRIMARY KEY AUTOINCREMENT, \\\r\n\t\tstatus \t\tTEXT \\\r\n\t)',\r\n\r\n\t'DROP TABLE IF EXISTS etl_audit',\r\n\tf'CREATE TABLE etl_audit( \\\r\n\t\trow_id\t\tINTEGER PRIMARY KEY AUTOINCREMENT, \\\r\n\t\tbatch_id \tINTEGER, \\\r\n\t\tproc_id \tINTEGER, \\\r\n\t\tline_id\t\tINTEGER, \\\r\n\t\tstatus_id \tINTEGER, \\\r\n\t\tupdated_on \tTEXT, \\\r\n\t\tupdated_at \tTEXT \\\r\n\t)',\r\n\r\n\t'DROP TABLE IF EXISTS etl_outcome',\r\n\tf'CREATE TABLE etl_outcome( \\\r\n\t\trow_id\t\tINTEGER PRIMARY KEY AUTOINCREMENT, \\\r\n\t\tetl_id \t\tINTEGER, \\\r\n\t\tmessage \tINTEGER, \\\r\n\t\tcreated_on \tTEXT, \\\r\n\t\tcreated_at \tTEXT \\\r\n\t)',\r\n\r\n\t'DROP TABLE IF EXISTS outcome_messages',\r\n\tf'CREATE TABLE outcome_messages( \\\r\n\t\trow_id\t\tINTEGER PRIMARY KEY AUTOINCREMENT, \\\r\n\t\tmessage \tTEXT \\\r\n\t)',\r\n\r\n\tf'INSERT INTO proc_status(status) VALUES \\\r\n\t(\\'PENDING\\'), \\\r\n\t(\\'ERROR\\'), \\\r\n\t(\\'SKIPPED\\'), \\\r\n\t(\\'COMPLETE\\')',\r\n\r\n\tf'INSERT INTO outcome_messages(message) VALUES \\\r\n\t(\\'MATCH\\'), \\\r\n\t(\\'NO MATCH\\'), \\\r\n\t(\\'SUGGEST A CORRECTION\\')',\r\n]","sub_path":"__model__.py","file_name":"__model__.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"385837944","text":"\"\"\"\nCameraSystem\nSystem responsible for:\n\n\nWorks on entities with components:\n[\"CameraComponent\",\"TransformComponent\"]\n\"\"\"\nfrom engine.base.systems import System\nfrom engine.core.utils.mipy.py_extensions import overrides,implements\nfrom engine.core.utils.rect import *\nfrom engine.core.utils.vector import *\nfrom engine.core import GLOBAL\n\n\nclass CameraSystem(System):\n\n\tdef __init__(self,scene):\n\t\tsuper(CameraSystem,self).__init__(scene)\n\t\tself.updateCollection()\n\n\t@overrides(System.updateCollection)\n\tdef updateCollection(self):\n\t\tself.collection = self.getEntitiesWithComponents((\"TransformComponent\",\"CameraComponent\"))\n\t\n\n\t@overrides(System.updateLate)\n\tdef updateLate(self,dt,messenger):\n\t\tfor ent in self.collection:\n\t\t\tif ent.getComponent(\"CameraComponent\").active == 1:\n\t\t\t\ttransform_component = ent.getComponent(\"TransformComponent\")\n\t\t\t\tcamera_component \t= ent.getComponent(\"CameraComponent\")\n\t\t\t\tGLOBAL.G_camera.y \t= int(transform_component.position.y)\n\t\t\t\tGLOBAL.G_camera.x \t= int(transform_component.position.x)\n\t\t\t\tGLOBAL.G_camera.angle \t= int(camera_component.angle) \n\t\t\t\tGLOBAL.G_camera.zoom \t= float(camera_component.zoom)\t\n\t\t\t\tbreak\n","sub_path":"engine/base/systems/camerasystem.py","file_name":"camerasystem.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"617586327","text":"from flask import Blueprint, render_template, abort, session, flash, redirect\nfrom flask import url_for, request\nfrom conference_app.models import Session\nfrom datetime import datetime\n\nadmin_add_session_page = Blueprint('admin_add_session_page', __name__)\nadmin_show_sessions_page = Blueprint('admin_show_sessions_page', __name__)\nadmin_delete_session_page = Blueprint('admin_delete_session_page', __name__)\n\n\n@admin_add_session_page.route('/add', methods=['POST'])\ndef add_session():\n session = Session(c_title=request.form['c_title'],\n c_description=request.form['c_description'],\n c_venue=request.form['c_venue'],\n c_date=datetime.strptime(request.form['c_date'],\n '%Y%m%d%H%M'))\n session.save()\n flash('New session was successfully posted')\n return redirect(url_for('admin_show_sessions_page.show_sessions'))\n\n@admin_show_sessions_page.route('/show')\ndef show_sessions():\n sessions = Session.query.all()\n return render_template('admin/show_sessions.html', sessions=sessions)\n\n@admin_delete_session_page.route('/delete/')\ndef delete_session(c_id):\n session = Session.query.get(c_id)\n session.delete()\n return redirect(url_for('admin_show_sessions_page.show_sessions'))\n\n\n \n","sub_path":"conference/conference_app/views/session_admin.py","file_name":"session_admin.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"452574585","text":"ans = []\n\ndef dfs(path, cnt, tickets, T, use):\n if cnt == T:\n ans.append(path)\n return\n for i in range(T):\n if not use[i] and tickets[i][0] == path[-1]:\n use[i] = True\n dfs(path+[tickets[i][1]], cnt+1, tickets, T, use)\n use[i] = False\n\n\ndef solution(tickets):\n T = len(tickets)\n use = [False]*T\n for i in range(T):\n if tickets[i][0] == 'ICN':\n use[i] = True\n dfs([tickets[i][0], tickets[i][1]], 1, tickets, T, use)\n use[i] = False\n\n ans.sort()\n return ans[0]","sub_path":"programmers/201904/여행경로.py","file_name":"여행경로.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"182377581","text":"from config.dbconfig import pg_config\nimport psycopg2\n\nclass IceDAO:\n\n def __init__(self):\n\n connection_url = \"dbname=%s user=%s password=%s host=127.0.0.1\" % (pg_config['dbname'],\n pg_config['user'],\n pg_config['passwd'])\n self.conn = psycopg2._connect(connection_url)\n\n def getAllIce(self):\n cursor = self.conn.cursor()\n query = \"select ice_id, ice_bagSize from ice;\"\n cursor.execute(query)\n result = []\n for row in cursor:\n result.append(row)\n return result\n\n def getIceById(self, ice_id):\n cursor = self.conn.cursor()\n query = \"select ice_id, ice_bagSize from ice where ice_id = %s;\"\n cursor.execute(query, (ice_id,))\n result = cursor.fetchone()\n return result\n\n def getIceByBagSize(self, ice_bagSize):\n cursor = self.conn.cursor()\n query = \"select * from ice where ice_bagSize = %s;\"\n cursor.execute(query, (ice_bagSize,))\n result = []\n for row in cursor:\n result.append(row)\n return result\n\n def getIceByLocation(self, resr_location):\n cursor = self.conn.cursor()\n query = \"select * from ice natural inner join Resources where resr_location = %s;\"\n cursor.execute(query, (resr_location,))\n result = []\n for row in cursor:\n result.append(row)\n return result\n\n def getIceConfirmed(self, confirmation_status):\n cursor = self.conn.cursor()\n query = \"select * from ice natural inner join Resources natural inner join Confirmation where confirmation_status = %s;\"\n cursor.execute(query, (confirmation_status,))\n result = []\n for row in cursor:\n result.append(row)\n return result\n\n def getIceBySupplier(self, s_id):\n cursor = self.conn.cursor()\n query = \"select * from ice natural inner join Resources natural inner join Provides natural inner join supplier where s_id = %s;\"\n cursor.execute(query, (s_id,))\n result = []\n for row in cursor:\n result.append(row)\n return result\n\n def getIcePurchased(self):\n cursor = self.conn.cursor()\n query = \"select * from ice natural inner join Purchases;\"\n cursor.execute(query, ())\n result = []\n for row in cursor:\n result.append(row)\n return result\n\n def insert(self, ice_bagSize, resr_id):\n cursor = self.conn.cursor()\n query = \"insert into ice(ice_bagSize, resr_id) values (%s, %s) returning ice_id;\"\n cursor.execute(query, (ice_bagSize, resr_id,))\n iceid = cursor.fetchone()[0]\n self.conn.commit()\n return iceid\n\n def delete(self, ice_id):\n cursor = self.conn.cursor()\n query = \"delete from ice where ice_id = %s;\"\n cursor.execute(query, (ice_id,))\n self.conn.commit()\n return ice_id\n\n def update(self, ice_id, ice_bagSize):\n cursor = self.conn.cursor()\n query = \"update ice set ice_bagSize = %s where ice_id = %s;\"\n cursor.execute(query, (ice_id, ice_bagSize,))\n self.conn.commit()\n return ice_id","sub_path":"dao/ice.py","file_name":"ice.py","file_ext":"py","file_size_in_byte":3268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"620670254","text":"\r\nrow1 = [\"⬜️\",\"⬜️\",\"⬜️\"]\r\nrow2 = [\"⬜️\",\"⬜️\",\"⬜️\"]\r\nrow3 = [\"⬜️\",\"⬜️\",\"⬜️\"]\r\nmap = [row1, row2, row3]\r\nprint(f\"{row1}\\n{row2}\\n{row3}\")\r\nposition = input(\"Where do you want to put the treasure? \")\r\n\r\n# print(map) \r\n\r\n\r\ncolumn_position = int(position[0]) - 1\r\nrow_position = int(position[1]) - 1\r\n# row_position[column_position]\r\nmap[column_position][row_position] = \"💰\"\r\n\r\n\r\nprint(f\"{row1}\\n{row2}\\n{row3}\")","sub_path":"treasure_map.py","file_name":"treasure_map.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"636176347","text":"import pickle\r\nimport numpy as np\r\n# Disable GPU if model uses LSTM instead of GPU-optimized CuDNNLSTM\r\n# import os\r\n# os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"-1\"\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Conv1D, MaxPooling1D, Flatten, Dense, Dropout, BatchNormalization, LSTM, TimeDistributed, \\\r\n CuDNNLSTM\r\nfrom keras.callbacks import TensorBoard, EarlyStopping, ModelCheckpoint\r\n\r\n\r\n# Define RNN model for 10-dimensional data of unknown length; three layers; 32-16-2\r\ndef discriminator(dropout=0.2):\r\n model = Sequential()\r\n model.add(LSTM(32, input_shape=(None, 10), return_sequences=True))\r\n # model.add(CuDNNLSTM(32, input_shape=(None, 10), return_sequences=True))\r\n model.add(Dropout(dropout))\r\n model.add(LSTM(16, return_sequences=False))\r\n # model.add(CuDNNLSTM(16, return_sequences=False))\r\n model.add(Dropout(dropout))\r\n model.add(Dense(2, activation='softmax'))\r\n model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\r\n return model\r\n\r\n\r\n# Read in cleaned/encoded data from pickle file\r\npickle_in = open('cleanData', \"rb\")\r\nrealMatches = pickle.load(pickle_in) # real matched sequence pairs\r\nfakeMatches = pickle.load(pickle_in) # fake matched sequence pairs\r\nX = pickle.load(pickle_in) # encoded matched sequence pairs\r\nY = pickle.load(pickle_in) # associated label: 1 for real, 0 for fake\r\npickle_in.close()\r\n\r\n# Initialize model\r\nmodel = discriminator()\r\n\r\n# Print model summary\r\nmodel.summary()\r\n\r\n# Set ratio for portion of data set reserved for training\r\ntrainRatio = 0.9\r\n\r\n# Set number of iterations for validation set\r\nnumVal = int(len(X) * (1 - trainRatio))\r\n\r\n\r\n# Split the encoded data into validation set and training set\r\n# Last numVal elements will be for validation, rest of them are for training\r\n\r\n\r\n# Validation set generator on which losses will be evaluated and metrics given\r\ndef validation_generator():\r\n i = -1\r\n m = numVal\r\n while True:\r\n i = (i + 1) % m\r\n yield X[-numVal + i], Y[-numVal + i]\r\n\r\n\r\n# Training set generator that composes single batch;\r\ndef train_generator():\r\n i = -1\r\n m = len(X) - numVal\r\n while True:\r\n i = (i + 1) % m\r\n yield X[i], Y[i]\r\n\r\n\r\n# Collect logging data during training\r\ntensorboard = TensorBoard(log_dir='logs', histogram_freq=0, write_graph=True, write_images=True)\r\n\r\n# Stop if no improvement in validation_loss between epochs\r\nearlystopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=50, verbose=1, restore_best_weights=True)\r\n\r\n# Save each epoch's model separately\r\nmodelcheckpoint = ModelCheckpoint(\"discriminator-improvement--{epoch:02d}--{val_loss:.2f}.h5\", monitor='val_loss',\r\n save_best_only=True, mode='auto', verbose=0)\r\n\r\n# Train the model with provided data sets\r\nstepsPerEpoch = 100 # batch size\r\nnumEpochs = int(4 * (len(X) - numVal) / (stepsPerEpoch * 5)) # keep numEpochs reasonable, i.e. < 1000\r\n\r\nhistoryObject = model.fit_generator(train_generator(), validation_data=validation_generator(),\r\n steps_per_epoch=stepsPerEpoch, epochs=numEpochs, verbose=1,\r\n validation_steps=numVal, callbacks=[tensorboard, earlystopping, modelcheckpoint],\r\n workers=8)\r\n\r\n# Organize history of discriminator training for later plotting\r\nval_loss = np.array(historyObject.history['val_loss'])\r\nval_acc = np.array(historyObject.history['val_accuracy'])\r\nloss = np.array(historyObject.history['loss'])\r\nacc = np.array(historyObject.history['accuracy'])\r\n\r\nhist = np.vstack((val_loss, val_acc, loss, acc)).T\r\n\r\n# Save the organized history into a txt file\r\nnp.savetxt(str(trainRatio * 100) + \"_history.txt\", hist, delimiter=\",\")\r\n\r\n# Save the fitted model as an h5 file\r\n# Contains model architecture, weights, training configuration (loss, optimizer), state of optimizer\r\nmodel.save('discriminator_model.h5')\r\n","sub_path":"src/discriminator_train.py","file_name":"discriminator_train.py","file_ext":"py","file_size_in_byte":3975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"19820195","text":"# RUN WITH /usr/bin/python3 minet.py (python 3.6)\n\nimport sys\nimport numpy as np\nfrom sklearn.metrics import roc_curve, auc\nimport pandas as pd\n\n\nmatricesdirname = \"/home/user/Sirius/dimasdata\"\ntruematricesdirname = \"/home/user/Sirius/gene_network_sirius_2019/Matrices_1\"\npredictedfilename = matricesdirname + \"/{0}/{0}_{1}.csv\"\ntruefilename = truematricesdirname + \"/{1}_{0}_true.txt\"\ndatalist = ['exps_10', 'exps_10_2', 'exps_10_bgr', 'exps_50', 'exps_50_2', 'exps_50_bgr', 'exps_100', 'exps_100_2', 'exps_100_bgr', 'genes_200_exps_10_bgr', 'genes_400_exps_10_bgr', 'genes_600_exps_10_bgr', 'genes_700_exps_10_bgr', 'genes_1000_exps_10_bgr']\n# algolist = ['BR', 'ET', 'GB', 'Lasso_0.001', 'Lasso_0.0001', 'Lasso_0.00001', 'Lasso_0.000001', 'Lasso_0.0000001', 'RF', 'XGB']\nalgolist = ['BR', 'ET', 'GB', 'Lasso_0.001', 'Lasso_0.0001', 'Lasso_0.00001', 'Lasso_0.000001', 'Lasso_0.0000001', 'RF', 'XGB']\nsaveresultsfile = \"/home/user/Sirius/dimasdata/res2.txt\"\n\n\n\ndef matrix_stringify(m):\n \"\"\"Transform top-triangle matrix to one-dimensional array\n Parameters\n ----------\n m: np.ndarray\n two-dimensional matrix to transform\n Returns\n -------\n one-dimensional np.array\n \"\"\"\n arr = np.array([])\n for i in range(m.shape[0] - 1):\n arr = np.concatenate([arr, m[i, i+1:]])\n return arr\n\n\nif __name__ == \"__main__\":\n results = np.zeros(shape=(len(datalist), len(algolist)))\n\n for i, dataname in enumerate(datalist):\n for j, algo in enumerate(algolist):\n\n true_df = pd.read_csv(truefilename.format(dataname, 'aracne'), index_col=0, sep='\\t')\n predicted_df = pd.read_csv(predictedfilename.format(dataname, algo), index_col=0, sep=',').abs().fillna(0)\n # print(predicted_df)\n # print(1/0)\n # true_df.to_csv(savematricesdirname + \"/{0}_true.txt\".format(dataname), index=True, header=True, sep='\\t')\n # print(true_df)\n\n true_array = true_df.values[np.triu_indices(true_df.values.shape[0], k=1)]\n predicted_array = predicted_df.values[np.triu_indices(predicted_df.values.shape[0], k=1)]\n \n roc_auc = 0\n # try:\n # fpr, tpr, thresholds = roc_curve(true_array, predicted_array)\n # roc_auc = auc(fpr, tpr)\n # except:\n # print(\"error\", dataname, algo)\n fpr, tpr, thresholds = roc_curve(true_array, predicted_array)\n roc_auc = auc(fpr, tpr)\n fpr1, tpr1, thresholds1 = roc_curve(matrix_stringify(true_df.values), matrix_stringify(predicted_df.values))\n roc_auc1 = auc(fpr1, tpr1)\n\n print(\"ME AND DIMA\", roc_auc, roc_auc1)\n results[i][j] = roc_auc\n\n print(\"done\", dataname, algo, results[i][j])\n with open(saveresultsfile, \"a\") as f:\n f.write(\"done \" + dataname + \" \" + algo + \" \" + str(results[i][j]) + '\\n')\n \n # print(\"done\", dataname, algo)\n\n print(results)\n\n\n","sub_path":"RankAggregation/ComputeAucsForExternalData.py","file_name":"ComputeAucsForExternalData.py","file_ext":"py","file_size_in_byte":3009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"368859847","text":"\"\"\"\nExtension of keras ImageDataGenerator for image segmentation data,\nwhere input and label are arrays of the same shape and need to be\ndistorted in the same way.\n\"\"\"\nimport keras.preprocessing.image as _image\nimport numpy as _np\nfrom builtins import super\n\n\nclass ImageDataGenerator(_image.ImageDataGenerator):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n \n def random_transform_covariant(self, x, y, seed=None):\n \"\"\"\n Randomly augment a single image tensor and its label.\n\n # Arguments\n x: 3D tensor, single image.\n y: 3D tensor, single image label.\n seed: random seed.\n\n # Returns\n A randomly transformed version of the inputs (same shape).\n \"\"\"\n # x is a single image, so it doesn't have image number at index 0\n img_row_axis = self.row_axis - 1\n img_col_axis = self.col_axis - 1\n img_channel_axis = self.channel_axis - 1\n\n if seed is not None:\n _np.random.seed(seed)\n\n # use composition of homographies\n # to generate final transform that needs to be applied\n if self.rotation_range:\n theta = _np.pi / 180 * _np.random.uniform(\n -self.rotation_range,\n self.rotation_range\n )\n else:\n theta = 0\n\n if self.height_shift_range:\n tx = _np.random.uniform(\n -self.height_shift_range,\n self.height_shift_range\n ) * x.shape[img_row_axis]\n else:\n tx = 0\n\n if self.width_shift_range:\n ty = _np.random.uniform(\n -self.width_shift_range,\n self.width_shift_range\n ) * x.shape[img_col_axis]\n else:\n ty = 0\n\n if self.shear_range:\n shear = _np.random.uniform(-self.shear_range, self.shear_range)\n else:\n shear = 0\n\n if self.zoom_range[0] == 1 and self.zoom_range[1] == 1:\n zx, zy = 1, 1\n else:\n zx, zy = _np.random.uniform(\n self.zoom_range[0],\n self.zoom_range[1],\n 2\n )\n\n # Initialise transformation matrix with identity matrix (no transformation)\n transform_matrix = _np.eye(3)\n \n if theta != 0:\n rotation_matrix = _np.array([\n [_np.cos(theta), -_np.sin(theta), 0],\n [_np.sin(theta), _np.cos(theta), 0],\n [0, 0, 1]\n ])\n transform_matrix = rotation_matrix\n\n if tx != 0 or ty != 0:\n shift_matrix = _np.array([\n [1, 0, tx],\n [0, 1, ty],\n [0, 0, 1]\n ])\n \n transform_matrix = _np.dot(transform_matrix, shift_matrix)\n\n if shear != 0:\n shear_matrix = _np.array([\n [1, -_np.sin(shear), 0],\n [0, _np.cos(shear), 0],\n [0, 0, 1]\n ])\n transform_matrix = _np.dot(transform_matrix, shear_matrix)\n\n if zx != 1 or zy != 1:\n zoom_matrix = _np.array([\n [zx, 0, 0],\n [0, zy, 0],\n [0, 0, 1]\n ])\n transform_matrix = _np.dot(transform_matrix, zoom_matrix)\n\n height, width = x.shape[img_row_axis], x.shape[img_col_axis]\n transform_matrix = _image.transform_matrix_offset_center(\n transform_matrix,\n height,\n width\n )\n \n x = _image.apply_transform(x, transform_matrix, img_channel_axis,\n fill_mode=self.fill_mode, cval=self.cval)\n y = _image.apply_transform(y, transform_matrix, img_channel_axis,\n fill_mode=self.fill_mode, cval=self.cval)\n\n if self.horizontal_flip and _np.random.random() < 0.5:\n x = _image.flip_axis(x, img_col_axis)\n y = _image.flip_axis(y, img_col_axis)\n\n return x, y\n","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":4040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"136442959","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 license information.\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is regenerated.\n# --------------------------------------------------------------------------\n\nfrom azure.identity import DefaultAzureCredential\nfrom azure.mgmt.eventhub import EventHubManagementClient\n\n\"\"\"\n# PREREQUISITES\n pip install azure-identity\n pip install azure-mgmt-eventhub\n# USAGE\n python eh_event_hub_create.py\n\n Before run the sample, please set the values of the client ID, tenant ID and client secret\n of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,\n AZURE_CLIENT_SECRET. For more info about how to get the value, please see:\n https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal\n\"\"\"\n\n\ndef main():\n client = EventHubManagementClient(\n credential=DefaultAzureCredential(),\n subscription_id=\"5f750a97-50d9-4e36-8081-c9ee4c0210d4\",\n )\n\n response = client.event_hubs.create_or_update(\n resource_group_name=\"Default-NotificationHubs-AustraliaEast\",\n namespace_name=\"sdk-Namespace-5357\",\n event_hub_name=\"sdk-EventHub-6547\",\n parameters={\n \"properties\": {\n \"captureDescription\": {\n \"destination\": {\n \"name\": \"EventHubArchive.AzureBlockBlob\",\n \"properties\": {\n \"archiveNameFormat\": \"{Namespace}/{EventHub}/{PartitionId}/{Year}/{Month}/{Day}/{Hour}/{Minute}/{Second}\",\n \"blobContainer\": \"container\",\n \"storageAccountResourceId\": \"/subscriptions/e2f361f0-3b27-4503-a9cc-21cfba380093/resourceGroups/Default-Storage-SouthCentralUS/providers/Microsoft.ClassicStorage/storageAccounts/arjunteststorage\",\n },\n },\n \"enabled\": True,\n \"encoding\": \"Avro\",\n \"intervalInSeconds\": 120,\n \"sizeLimitInBytes\": 10485763,\n },\n \"messageRetentionInDays\": 4,\n \"partitionCount\": 4,\n \"status\": \"Active\",\n }\n },\n )\n print(response)\n\n\n# x-ms-original-file: specification/eventhub/resource-manager/Microsoft.EventHub/stable/2021-11-01/examples/EventHubs/EHEventHubCreate.json\nif __name__ == \"__main__\":\n main()\n","sub_path":"sdk/eventhub/azure-mgmt-eventhub/generated_samples/eh_event_hub_create.py","file_name":"eh_event_hub_create.py","file_ext":"py","file_size_in_byte":2691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"99411016","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 28 22:42:04 2020\n\n@author: ken\n\nref: https://www.fullstackpython.com/blog/export-pandas-dataframes-sqlite-sqlalchemy.html\n\n\"\"\"\n\nimport argparse\nimport sys\nimport os\nimport tempfile\nimport pandas as pd\nfrom sqlalchemy import create_engine\npd.set_option('display.max_rows', 150)\npd.set_option('display.max_columns', 10)\npd.set_option('display.max_colwidth', 100)\npd.set_option('display.width', 200)\n\n\ndef main():\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n description='Program converts a csv file to a sqlite database ' +\n 'file. The csv file is derived from the database data of ' +\n \"Dekker's original Drawing Log program, or from the \" +\n 'sqlite database from the Drawing Log 2 program. The latter ' +\n 'program is a replacement for the former.')\n parser.add_argument('file_in', help='Name of file to import.')\n parser.add_argument('file_out', help='Name of file to export.')\n \n if len(sys.argv)==1:\n parser.print_help(sys.stderr)\n sys.exit(1)\n args = parser.parse_args() \n dwglog2_convert(args.file_in, args.file_out)\n \n \ndef dwglog2_convert(fn_in, fn_out):\n _, file_extension = os.path.splitext(fn_in)\n if (file_extension.lower() == '.csv' or file_extension.lower() == '.txt' or\n file_extension.lower() == '.xls' or file_extension.lower() == '.xlsx'):\n df = import_excel(fn_in)\n export2db(fn_out, df)\n elif file_extension.lower() == '.db':\n pass\n else:\n print('Invalid file type')\n \n \ndef import_excel(fn_in):\n try:\n _, file_extension = os.path.splitext(fn_in)\n if file_extension.lower() == '.csv' or file_extension.lower() == '.txt':\n data = make_csv_file_stable(fn_in)\n temp = tempfile.TemporaryFile(mode='w+t')\n for d in data:\n temp.write(d)\n temp.seek(0)\n df = pd.read_csv(temp, na_values=[' '], sep='$',\n encoding='iso8859_1', engine='python',\n dtype = str)\n temp.close()\n elif file_extension.lower() == '.xlsx' or file_extension.lower() == '.xls':\n df = pd.read_excel(fn_in, na_values=[' '])\n colnames = []\n for colname in df.columns: # rid colname of '\\n' char if exists\n colnames.append(colname.replace('\\n', ''))\n df.columns = colnames\n print('Data sucessfully imported')\n except:\n printStr = '\\nError processing file: ' + fn_in + '\\nIt has been excluded from the BOM check.\\n'\n print(printStr)\n return df\n \n \n\ndef export2db(fn_out, df):\n pass\n\ndef export2excel():\n pass\n\n\n\ndef make_csv_file_stable(filename):\n ''' Except for any commas in a parts DESCRIPTION, replace all commas\n in a csv file with a $ character. Commas will sometimes exist in a\n DESCRIPTION field, e.g, \"TANK, 60GAL\". But commas are intended to be field\n delimeters; commas in a DESCRIPTION field are not. Excess commas in\n a line from a csv file will cause a program crash. Remedy: change those \n commas meant to be delimiters to a dollor sign character, $.\n \n Parmeters\n =========\n\n filename: string\n Name of SolidWorks csv file to process.\n\n Returns\n =======\n\n out: list\n A list of all the lines (rows) in filename is returned. Commas in each\n line are changed to dollar signs except for any commas in the\n DESCRIPTION field.\n '''\n with open(filename, encoding=\"ISO-8859-1\") as f:\n data1 = f.readlines()\n # n1 = number of commas in 2nd line of filename (i.e. where column header\n # names located). This is the no. of commas that should be in each row.\n n1 = data1[1].count(',')\n n2 = data1[1].upper().find('Description') # locaton of the word DESCRIPTION within the row.\n n3 = data1[1][:n2].count(',') # number of commas before the word DESCRIPTION\n data2 = list(map(lambda x: x.replace(',', '$') , data1)) # replace ALL commas with $\n data = []\n for row in data2:\n n4 = row.count('$')\n if n4 != n1:\n # n5 = location of 1st ; character within the DESCRIPTION field\n # that should be a , character\n n5 = row.replace('$', '?', n3).find('$')\n # replace those ; chars that should be , chars in the DESCRIPTION field:\n data.append(row[:n5] + row[n5:].replace('$', ',', (n4-n1))) # n4-n1: no. commas needed\n else:\n data.append(row)\n return data","sub_path":"dwglog2_convert.py","file_name":"dwglog2_convert.py","file_ext":"py","file_size_in_byte":4734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"68121292","text":"from __future__ import absolute_import\n\nfrom appium import webdriver\nimport time\n\nfrom shishito.runtime.environment.shishito import ShishitoEnvironment\n\n\nclass ControlEnvironment(ShishitoEnvironment):\n \"\"\" Appium control environment. \"\"\"\n\n def call_browser(self, config_section):\n \"\"\" Start webdriver for given config section. Prepare capabilities for the webdriver. If saucelabs setting has value,\n webdriver will be connected to saucelabs. Otherwise appium_url setting will be used.\n\n :param str config_section: section in platform/environment.properties config\n :return: created webdriver\n \"\"\"\n\n # get browser capabilities\n capabilities = self.get_capabilities(config_section)\n browserstack = self.shishito_support.get_opt('browserstack')\n\n if browserstack:\n try:\n bs_user, bs_password = self.shishito_support.get_opt('browserstack').split(':', 1)\n except (AttributeError, ValueError):\n raise ValueError('Browserstack credentials were not specified! Unable to start browser.')\n\n if bs_user:\n #remote_url = 'http://%s@ondemand.saucelabs.com:80/wd/hub' % saucelabs\n remote_url = 'http://{0}:{1}@hub-cloud.browserstack.com/wd/hub'.format(bs_user, bs_password)\n else:\n remote_url = self.shishito_support.get_opt('appium_url')\n\n # get driver\n return self.start_driver(capabilities, remote_url)\n\n def get_capabilities(self, config_section):\n \"\"\" Return dictionary of capabilities for specific config combination.\n\n :param str config_section: section in platform/environment.properties config\n :return: dict with capabilities\n \"\"\"\n\n get_opt = self.shishito_support.get_opt\n\n return {\n 'os': get_opt(config_section, 'os'),\n 'os_version': get_opt(config_section, 'os_version'),\n 'device': get_opt(config_section, 'device'),\n 'app': get_opt('app') or get_opt(config_section, 'app'),\n 'name': self.get_test_name() + time.strftime('_%Y-%m-%d'),\n 'browserstack.debug': get_opt('browserstack_debug').lower() or False,\n 'browserstack.appium_version': get_opt(config_section, 'browserstack.appium_version') or None,\n 'browserstack.chrome.driver': get_opt(config_section, 'browserstack.chrome.driver') or None,\n 'deviceOrientation': get_opt(config_section, 'deviceOrientation') or 'portrait',\n 'autoGrantPermissions': get_opt(config_section, 'autoGrantPermissions') or None,\n 'automationName': get_opt(config_section, 'automationName') or None,\n 'autoAcceptAlerts': get_opt(config_section, 'autoAcceptAlerts') or None,\n 'no-reset': get_opt(config_section, 'no-reset') or True,\n 'full-reset': get_opt(config_section, 'full-reset') or False,\n 'autoWebview': get_opt(config_section, 'autoWebview') or False,\n 'waitForQuiescence': get_opt(config_section, 'waitForQuiescence') or None,\n }\n\n def get_pytest_arguments(self, config_section):\n \"\"\" Get environment specific arguments for pytest.\n\n :param config_section: section in platform/environment.properties config\n :return: dict with arguments for pytest or None\n \"\"\"\n\n pytest_args = {\n '--os_version': '--os_version=%s' % self.shishito_support.get_opt(config_section, 'os_version'),\n '--device': '--device=%s' % self.shishito_support.get_opt(config_section, 'device'),\n '--app': '--app=%s' % (self.shishito_support.get_opt('app') or self.shishito_support.get_opt(config_section, 'app'))\n }\n browserstack = self.shishito_support.get_opt('browserstack')\n if browserstack:\n pytest_args['--browserstack'] = '--browserstack=%s' % browserstack\n\n return pytest_args\n\n def start_driver(self, capabilities, remote_driver_url, **kwargs):\n \"\"\" Prepare selenium webdriver.\n\n :param capabilities: capabilities used for webdriver initialization\n :param remote_driver_url: url to which the driver will be connected\n \"\"\"\n\n driver = webdriver.Remote(\n command_executor=remote_driver_url,\n desired_capabilities=capabilities,\n )\n\n return driver\n","sub_path":"shishito/runtime/environment/appium_bs.py","file_name":"appium_bs.py","file_ext":"py","file_size_in_byte":4374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"641884561","text":"import numpy as np\r\nfrom rpi_d3m_primitives.featSelect.helperFunctions import normalize_array, joint\r\nfrom rpi_d3m_primitives.featSelect.mutualInformation import mi, joint_probability\r\n\"\"\"---------------------------- CONDITIONAL MUTUAL INFORMATION ----------------------------\"\"\"\r\ndef mergeArrays(firstVector, secondVector, length):\r\n \r\n if length == 0:\r\n length = firstVector.size\r\n \r\n results = normalize_array(firstVector, 0)\r\n firstNumStates = results[0]\r\n firstNormalisedVector = results[1]\r\n \r\n results = normalize_array(secondVector, 0)\r\n secondNumStates = results[0]\r\n secondNormalisedVector = results[1]\r\n \r\n stateCount = 1\r\n stateMap = np.zeros(shape = (firstNumStates*secondNumStates,))\r\n merge = np.zeros(shape =(length,))\r\n\r\n joint_states = np.column_stack((firstVector,secondVector))\r\n uniques,merge = np.unique(joint_states,axis=0,return_inverse=True)\r\n stateCount = len(uniques)\r\n results = []\r\n results.append(stateCount)\r\n results.append(merge)\r\n return results\r\n\r\n\r\ndef conditional_entropy(dataVector, conditionVector, length):\r\n condEntropy = 0\r\n jointValue = 0\r\n condValue = 0\r\n if length == 0:\r\n length = dataVector.size\r\n \r\n results = joint_probability(dataVector, conditionVector, 0)\r\n jointProbabilityVector = results[0]\r\n numJointStates = results[1]\r\n numFirstStates = results[3]\r\n secondProbabilityVector = results[4]\r\n \r\n for i in range(0, numJointStates):\r\n jointValue = jointProbabilityVector[i]\r\n condValue = secondProbabilityVector[int(i / numFirstStates)]\r\n if jointValue > 0 and condValue > 0:\r\n condEntropy -= jointValue * np.log2(jointValue / condValue);\r\n\r\n return condEntropy\r\n\r\n\r\ndef cmi(dataVector, targetVector, conditionVector, length = 0):\r\n if (conditionVector.size == 0):\r\n return mi(dataVector,targetVector,0)\r\n if (len(conditionVector.shape)>1 and conditionVector.shape[1]>1):\r\n conditionVector = joint(conditionVector)\r\n cmi = 0;\r\n firstCondition = 0\r\n secondCondition = 0\r\n \r\n if length == 0:\r\n length = dataVector.size\r\n \r\n results = mergeArrays(targetVector, conditionVector, length)\r\n mergedVector = results[1]\r\n \r\n firstCondition = conditional_entropy(dataVector, conditionVector, length)\r\n secondCondition = conditional_entropy(dataVector, mergedVector, length)\r\n cmi = firstCondition - secondCondition\r\n \r\n return cmi","sub_path":"featSelect/conditionalMI.py","file_name":"conditionalMI.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"553268705","text":"import gspread\nimport hmac\nfrom hashlib import sha1\nimport json\nimport logging\nfrom oauth2client.client import SignedJwtAssertionCredentials\n\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.contrib.sites.models import Site\nfrom django.core.exceptions import ValidationError\nfrom django.core.urlresolvers import reverse\nfrom django.utils import timezone\nfrom rest_framework.authtoken.models import Token\n\nfrom api.exceptions import Kromeo2015ValidationError\nfrom api.forms import SpreadsheetUserDataGetForm\nfrom api.models import UserProfile\n\nRANGE_MASK = 'A{}:J{}'\n\nlogger = logging.getLogger(__name__)\n\n\nclass SpreadsheetService(object):\n\n @classmethod\n def _get_worksheet(cls):\n json_key = json.load(open('../serverdeploy/kromeo2015-012bacfe8afc.json'))\n scope = ['https://spreadsheets.google.com/feeds']\n credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], scope)\n google_connection = gspread.authorize(credentials)\n worksheet = google_connection.open_by_key(settings.GDRIVE_DOC_KEY).sheet1\n return worksheet, len(worksheet.get_all_values())\n\n @classmethod\n def update_cells(cls, cells):\n for cell in cells:\n logger.info(cell.__dict__)\n worksheet, num_of_rows = cls._get_worksheet()\n worksheet.update_cells(cells)\n\n # TODO: This needs some significant refactoring as gspread is currently not testable\n @classmethod\n def retrieve_remote_data(cls):\n from api.tasks import initial_guest_creation_task\n\n worksheet, num_of_rows = cls._get_worksheet()\n\n errors = []\n\n for row in range(2, num_of_rows + 1):\n cells = worksheet.range(RANGE_MASK.format(row, row))\n\n form = SpreadsheetUserDataGetForm(\n {\n 'username': cells[0].value,\n 'full_name': cells[1].value,\n 'friendly_name': cells[2].value,\n 'email': cells[3].value,\n 'save_date_url': cells[4].value,\n # 'date_emailed': cells[5].value,\n # 'date_viewed': cells[6].value,\n 'address': cells[7].value,\n 'rsvp_response': cells[8].value,\n 'rsvp_count': cells[9].value,\n }\n )\n\n if not form.is_valid():\n errors.append({\"R{}\".format(row): form.errors})\n continue\n\n is_new = True\n if form.cleaned_data['username']:\n is_new = False\n\n if not is_new:\n user = User.objects.get(username=form.cleaned_data['username'])\n else:\n password = UserService.generate_password()\n\n user = User(\n password=password\n )\n\n user.email = form.cleaned_data['email']\n user.full_name = form.cleaned_data['full_name']\n\n try:\n user.save()\n except ValidationError as e:\n errors.append({\"R{}\".format(row): str(e)})\n continue\n\n if not is_new:\n user_profile = user.userprofile\n else:\n user_profile = UserProfile(user=user)\n\n user_profile.address = form.cleaned_data['address']\n user_profile.friendly_name = form.cleaned_data['friendly_name']\n # user_profile.date_viewed = form.cleaned_data['date_viewed']\n # user_profile.date_emailed = form.cleaned_data['date_emailed']\n\n try:\n user_profile.save()\n except ValidationError as e:\n errors.append({\"R{}\".format(row): str(e)})\n continue\n\n if is_new:\n token = Token(user=user)\n token.key = token.generate_key()\n token.save()\n\n cells[0].value = user.username\n cells[4].value = UserService.get_absolute_save_the_date_url(user)\n initial_guest_creation_task.delay(cells=[cells[0], cells[4]], user=user)\n\n if errors:\n raise Kromeo2015ValidationError(message=str(errors))\n\n @classmethod\n def update_remote_data(cls, user):\n if not settings.ENABLE_SPREADSHEET_UPDATE_SIGNALS:\n return\n\n worksheet, num_of_rows = cls._get_worksheet()\n\n cell = worksheet.find(user.username)\n\n if cell.col != 1:\n raise ValidationError(\"Clash of IDs %s\", user.username)\n\n cells = worksheet.range(RANGE_MASK.format(cell.row, cell.row))\n\n cells[0].value = user.username\n cells[1].value = user.get_full_name()\n cells[2].value = user.userprofile.friendly_name\n cells[3].value = user.email\n cells[4].value = UserService.get_absolute_save_the_date_url(user)\n cells[5].value = user.userprofile.date_emailed.replace(microsecond=0).isoformat() if user.userprofile.date_emailed else None\n cells[6].value = user.userprofile.date_viewed.replace(microsecond=0).isoformat() if user.userprofile.date_viewed else None\n cells[7].value = user.userprofile.address\n cells[8].value = user.userprofile.rsvp_response\n\n cells_for_update = []\n for cell in cells:\n if cell.value:\n cells_for_update.append(cell)\n\n # a null value of 0 is still legit for the RSVP Count\n cells[9].value = user.userprofile.rsvp_count\n cells_for_update.append(cells[9])\n\n worksheet.update_cells(cells_for_update)\n\n\nclass UserService(object):\n @classmethod\n def get_absolute_save_the_date_url(cls, user):\n return 'https://{}{}'.format(\n Site.objects.get_current().domain,\n reverse('web-save-the-date', kwargs={'username': user.username})\n )\n\n @classmethod\n def generate_username(cls):\n hmac_gen = hmac.new(settings.USERNAME_SHA1_KEY, timezone.now().isoformat(), sha1)\n return \"u{}\".format(hmac_gen.digest().encode('hex')[:5])\n\n @classmethod\n def generate_password(cls):\n hmac_gen = hmac.new(settings.USERNAME_SHA1_KEY, timezone.now().isoformat(), sha1)\n return hmac_gen.digest().encode('hex')[:30]\n","sub_path":"kromeo2015/api/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":6258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"263979750","text":"\"\"\"\n\nMisc. helper functions used in Empire.\n\nIncludes:\n\n validate_ip() - validate an IP\n validate_ntlm() - checks if the passed string is an NTLM hash\n random_string() - returns a random string of the specified number of characters\n chunks() - used to split a string into chunks\n strip_python_comments() - strips Python newlines and comments\n enc_powershell() - encodes a PowerShell command into a form usable by powershell.exe -enc ...\n powershell_launcher() - builds a command line powershell.exe launcher\n parse_powershell_script() - parses a raw PowerShell file and return the function names\n strip_powershell_comments() - strips PowerShell newlines and comments\n get_powerview_psreflect_overhead() - extracts some of the psreflect overhead for PowerView\n get_dependent_functions() - extracts function dependenies from a PowerShell script\n find_all_dependent_functions() - takes a PowerShell script and a set of functions, and returns all dependencies\n generate_dynamic_powershell_script() - takes a PowerShell script and set of functions and returns a minimized script\n parse_credentials() - enumerate module output, looking for any parseable credential sections\n parse_mimikatz() - parses the output of Invoke-Mimikatz\n get_config() - pulls config information from the database output of normal menu execution\n get_listener_options() - gets listener options outside of normal menu execution\n get_datetime() - returns the current date time in a standard format\n get_file_datetime() - returns the current date time in a format savable to a file\n get_file_size() - returns a string representing file size\n lhost() - returns the local IP\n color() - used for colorizing output in the Linux terminal\n unique() - uniquifies a list, order preserving\n uniquify_tuples() - uniquifies Mimikatz tuples based on the password\n decode_base64() - tries to base64 decode a string\n encode_base64() - tries to base64 encode a string\n complete_path() - helper to tab-complete file paths\n dict_factory() - helper that returns the SQLite query results as a dictionary\n KThread() - a subclass of threading.Thread, with a kill() method\n slackMessage() - send notifications to the Slack API\n\"\"\"\nimport base64\nimport binascii\nimport ipaddress\nimport json\nimport logging\nimport os\nimport random\nimport re\nimport socket\nimport string\nimport sys\nimport threading\nimport urllib.error\nimport urllib.parse\nimport urllib.request\nfrom builtins import range, str\nfrom datetime import datetime\n\nimport netifaces\n\nfrom empire.server.utils.math_util import old_div\n\nlog = logging.getLogger(__name__)\n\n\n###############################################################\n#\n# Global Variables\n#\n################################################################\n\nglobentropy = random.randint(1, datetime.today().day)\nglobDebug = False\n\n\n###############################################################\n#\n# Validation methods\n#\n###############################################################\n\n\ndef validate_ip(IP):\n \"\"\"\n Validate an IP.\n \"\"\"\n try:\n ipaddress.ip_address(IP)\n return True\n except Exception:\n return False\n\n\ndef validate_ntlm(data):\n \"\"\"\n Checks if the passed string is an NTLM hash.\n \"\"\"\n allowed = re.compile(\"^[0-9a-f]{32}\", re.IGNORECASE)\n if allowed.match(data):\n return True\n else:\n return False\n\n\n####################################################################################\n#\n# Randomizers/obfuscators\n#\n####################################################################################\ndef random_string(length=-1, charset=string.ascii_letters):\n \"\"\"\n Returns a random string of \"length\" characters.\n If no length is specified, resulting string is in between 6 and 15 characters.\n A character set can be specified, defaulting to just alpha letters.\n \"\"\"\n if length == -1:\n length = random.randrange(6, 16)\n random_string = \"\".join(random.choice(charset) for x in range(length))\n return random_string\n\n\ndef obfuscate_call_home_address(data):\n \"\"\"\n Poowershell script to base64 encode variable contents and execute on command as if clear text in powershell\n \"\"\"\n tmp = \"$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('\"\n tmp += (enc_powershell(data)).decode(\"UTF-8\") + \"')))\"\n return tmp\n\n\ndef chunks(s, n):\n \"\"\"\n Generator to split a string s into chunks of size n.\n Used by macro modules.\n \"\"\"\n for i in range(0, len(s), n):\n yield s[i : i + n]\n\n\n####################################################################################\n#\n# Python-specific helpers\n#\n####################################################################################\n\n\ndef strip_python_comments(data):\n \"\"\"\n *** DECEMBER 2017 - DEPRECATED, PLEASE DO NOT USE ***\n\n Strip block comments, line comments, empty lines, verbose statements, docstring,\n and debug statements from a Python source file.\n \"\"\"\n log.warning(\"strip_python_comments is deprecated and should not be used\")\n\n # remove docstrings\n data = re.sub(r'\"(?\", re.DOTALL), \"\\n\", data)\n\n # strip blank lines, lines starting with #, and verbose/debug statements\n strippedCode = \"\\n\".join(\n [\n line\n for line in strippedCode.split(\"\\n\")\n if (\n (line.strip() != \"\")\n and (not line.strip().startswith(\"#\"))\n and (not line.strip().lower().startswith(\"write-verbose \"))\n and (not line.strip().lower().startswith(\"write-debug \"))\n )\n ]\n )\n\n return strippedCode\n\n\n####################################################################################\n#\n# PowerView dynamic generation helpers\n#\n####################################################################################\n\n\ndef get_powerview_psreflect_overhead(script):\n \"\"\"\n Helper to extract some of the psreflect overhead for PowerView/PowerUp.\n \"\"\"\n\n if \"PowerUp\" in script[0:100]:\n pattern = re.compile(r\"\\n\\$Module =.*\\[\\'kernel32\\'\\]\", re.DOTALL)\n else:\n # otherwise extracting from PowerView\n pattern = re.compile(r\"\\n\\$Mod =.*\\[\\'wtsapi32\\'\\]\", re.DOTALL)\n\n try:\n return strip_powershell_comments(pattern.findall(script)[0])\n except Exception:\n log.error(\"Error extracting psreflect overhead from script!\")\n return \"\"\n\n\ndef get_dependent_functions(code, functionNames):\n \"\"\"\n Helper that takes a chunk of PowerShell code and a set of function\n names and returns the unique set of function names within the script block.\n \"\"\"\n\n dependentFunctions = set()\n for functionName in functionNames:\n # find all function names that aren't followed by another alpha character\n if re.search(\"[^A-Za-z']+\" + functionName + \"[^A-Za-z']+\", code, re.IGNORECASE):\n # if \"'AbuseFunction' \\\"%s\" % (functionName) not in code:\n # TODO: fix superflous functions from being added to PowerUp Invoke-AllChecks code...\n dependentFunctions.add(functionName)\n\n if re.search(\"\\$Netapi32|\\$Advapi32|\\$Kernel32|\\$Wtsapi32\", code, re.IGNORECASE):\n dependentFunctions |= set(\n [\"New-InMemoryModule\", \"func\", \"Add-Win32Type\", \"psenum\", \"struct\"]\n )\n\n return dependentFunctions\n\n\ndef find_all_dependent_functions(functions, functionsToProcess, resultFunctions=[]):\n \"\"\"\n Takes a dictionary of \"[functionName] -> functionCode\" and a set of functions\n to process, and recursively returns all nested functions that may be required.\n\n Used to map the dependent functions for nested script dependencies like in\n PowerView.\n \"\"\"\n\n if isinstance(functionsToProcess, str):\n functionsToProcess = [functionsToProcess]\n\n while len(functionsToProcess) != 0:\n # pop the next function to process off the stack\n requiredFunction = functionsToProcess.pop()\n\n if requiredFunction not in resultFunctions:\n resultFunctions.append(requiredFunction)\n\n # get the dependencies for the function we're currently processing\n try:\n functionDependencies = get_dependent_functions(\n functions[requiredFunction], list(functions.keys())\n )\n except Exception:\n functionDependencies = []\n log.error(\n f\"Error in retrieving dependencies for function {requiredFunction} !\"\n )\n\n for functionDependency in functionDependencies:\n if (\n functionDependency not in resultFunctions\n and functionDependency not in functionsToProcess\n ):\n # for each function dependency, if we haven't already seen it\n # add it to the stack for processing\n functionsToProcess.append(functionDependency)\n resultFunctions.append(functionDependency)\n\n resultFunctions = find_all_dependent_functions(\n functions, functionsToProcess, resultFunctions\n )\n\n return resultFunctions\n\n\ndef generate_dynamic_powershell_script(script, function_names):\n \"\"\"\n Takes a PowerShell script and a function name (or array of function names,\n generates a dictionary of \"[functionNames] -> functionCode\", and recursively\n maps all dependent functions for the specified function name.\n\n A script is returned with only the code necessary for the given\n functionName, stripped of comments and whitespace.\n\n Note: for PowerView, it will also dynamically detect if psreflect\n overhead is needed and add it to the result script.\n \"\"\"\n\n new_script = \"\"\n psreflect_functions = [\n \"New-InMemoryModule\",\n \"func\",\n \"Add-Win32Type\",\n \"psenum\",\n \"struct\",\n ]\n\n if type(function_names) is not list:\n function_names = [function_names]\n\n # build a mapping of functionNames -> stripped function code\n functions = {}\n pattern = re.compile(r\"\\n(?:function|filter).*?{.*?\\n}\\n\", re.DOTALL)\n\n script = re.sub(re.compile(\"<#.*?#>\", re.DOTALL), \"\", script)\n for func_match in pattern.findall(script):\n name = func_match[:40].split()[1]\n functions[name] = func_match\n\n # recursively enumerate all possible function dependencies and\n # start building the new result script\n function_dependencies = []\n\n for functionName in function_names:\n function_dependencies += find_all_dependent_functions(\n functions, functionName, []\n )\n function_dependencies = unique(function_dependencies)\n\n for function_dependency in function_dependencies:\n try:\n new_script += functions[function_dependency] + \"\\n\"\n except Exception:\n log.error(f\"Key error with function {function_dependency} !\")\n\n # if any psreflect methods are needed, add in the overhead at the end\n if any(el in set(psreflect_functions) for el in function_dependencies):\n new_script += get_powerview_psreflect_overhead(script)\n\n new_script = strip_powershell_comments(new_script)\n\n return new_script + \"\\n\"\n\n\n###############################################################\n#\n# Parsers\n#\n###############################################################\n\n\ndef parse_credentials(data):\n \"\"\"\n Enumerate module output, looking for any parseable credential sections.\n \"\"\"\n if isinstance(data, str):\n data = data.encode(\"UTF-8\")\n parts = data.split(b\"\\n\")\n\n # tag for Invoke-Mimikatz output\n if parts[0].startswith(b\"Hostname:\"):\n return parse_mimikatz(data)\n\n # powershell/collection/prompt output\n elif parts[0].startswith(b\"[+] Prompted credentials:\"):\n parts = parts[0].split(b\"->\")\n if len(parts) == 2:\n username = parts[1].split(b\":\", 1)[0].strip()\n password = parts[1].split(b\":\", 1)[1].strip()\n\n if \"\\\\\" in username:\n domain = username.split(\"\\\\\")[0].strip()\n username = username.split(\"\\\\\")[1].strip()\n else:\n domain = \"\"\n\n return [(\"plaintext\", domain, username, password, \"\", \"\")]\n\n else:\n log.error(\"Error in parsing prompted credential output.\")\n return None\n\n # python/collection/prompt (Mac OS)\n elif b\"text returned:\" in parts[0]:\n parts2 = parts[0].split(b\"text returned:\")\n if len(parts2) >= 2:\n password = parts2[-1]\n return [(\"plaintext\", \"\", \"\", password, \"\", \"\")]\n\n else:\n return None\n\n\ndef parse_mimikatz(data):\n \"\"\"\n Parse the output from Invoke-Mimikatz to return credential sets.\n \"\"\"\n\n # cred format:\n # credType, domain, username, password, hostname, sid\n creds = []\n\n # regexes for \"sekurlsa::logonpasswords\" Mimikatz output\n regexes = [\n \"(?s)(?<=msv :).*?(?=tspkg :)\",\n \"(?s)(?<=tspkg :).*?(?=wdigest :)\",\n \"(?s)(?<=wdigest :).*?(?=kerberos :)\",\n \"(?s)(?<=kerberos :).*?(?=ssp :)\",\n \"(?s)(?<=ssp :).*?(?=credman :)\",\n \"(?s)(?<=credman :).*?(?=Authentication Id :)\",\n \"(?s)(?<=credman :).*?(?=mimikatz)\",\n ]\n\n hostDomain = \"\"\n domainSid = \"\"\n hostName = \"\"\n if isinstance(data, str):\n data = data.encode(\"UTF-8\")\n lines = data.split(b\"\\n\")\n for line in lines[0:2]:\n if line.startswith(b\"Hostname:\"):\n try:\n domain = line.split(b\":\")[1].strip()\n temp = domain.split(b\"/\")[0].strip()\n domainSid = domain.split(b\"/\")[1].strip()\n\n hostName = temp.split(b\".\")[0]\n hostDomain = b\".\".join(temp.split(\".\")[1:])\n except Exception:\n pass\n\n for regex in regexes:\n p = re.compile(regex)\n for match in p.findall(data.decode(\"UTF-8\")):\n lines2 = match.split(\"\\n\")\n username, domain, password = \"\", \"\", \"\"\n\n for line in lines2:\n try:\n if \"Username\" in line:\n username = line.split(\":\", 1)[1].strip()\n elif \"Domain\" in line:\n domain = line.split(\":\", 1)[1].strip()\n elif \"NTLM\" in line or \"Password\" in line:\n password = line.split(\":\", 1)[1].strip()\n except Exception:\n pass\n\n if username != \"\" and password != \"\" and password != \"(null)\":\n sid = \"\"\n\n # substitute the FQDN in if it matches\n if hostDomain.startswith(domain.lower()):\n domain = hostDomain\n sid = domainSid\n\n if validate_ntlm(password):\n credType = \"hash\"\n\n else:\n credType = \"plaintext\"\n\n # ignore machine account plaintexts\n if not (credType == \"plaintext\" and username.endswith(\"$\")):\n creds.append((credType, domain, username, password, hostName, sid))\n\n if len(creds) == 0 and len(lines) >= 13:\n # check if we have lsadump output to check for krbtgt\n # happens on domain controller hashdumps\n for x in range(8, 13):\n if lines[x].startswith(b\"Domain :\"):\n domain, sid, krbtgtHash = b\"\", b\"\", b\"\"\n\n try:\n domainParts = lines[x].split(b\":\")[1]\n domain = domainParts.split(b\"/\")[0].strip()\n sid = domainParts.split(b\"/\")[1].strip()\n\n # substitute the FQDN in if it matches\n if hostDomain.startswith(domain.decode(\"UTF-8\").lower()):\n domain = hostDomain\n sid = domainSid\n\n for x in range(0, len(lines)):\n if lines[x].startswith(b\"User : krbtgt\"):\n krbtgtHash = lines[x + 2].split(b\":\")[1].strip()\n break\n\n if krbtgtHash != b\"\":\n creds.append(\n (\n \"hash\",\n domain.decode(\"UTF-8\"),\n \"krbtgt\",\n krbtgtHash.decode(\"UTF-8\"),\n hostName.decode(\"UTF-8\"),\n sid.decode(\"UTF-8\"),\n )\n )\n except Exception:\n pass\n\n if len(creds) == 0:\n # check if we get lsadump::dcsync output\n if b\"** SAM ACCOUNT **\" in lines:\n domain, user, userHash, dcName, sid = \"\", \"\", \"\", \"\", \"\"\n for line in lines:\n if line.strip().endswith(b\"will be the domain\"):\n domain = line.split(b\"'\")[1]\n elif line.strip().endswith(b\"will be the DC server\"):\n dcName = line.split(b\"'\")[1].split(b\".\")[0]\n elif line.strip().startswith(b\"SAM Username\"):\n user = line.split(b\":\")[1].strip()\n elif line.strip().startswith(b\"Object Security ID\"):\n parts = line.split(b\":\")[1].strip().split(b\"-\")\n sid = b\"-\".join(parts[0:-1])\n elif line.strip().startswith(b\"Hash NTLM:\"):\n userHash = line.split(b\":\")[1].strip()\n\n if domain != \"\" and userHash != \"\":\n creds.append(\n (\n \"hash\",\n domain.decode(\"UTF-8\"),\n user.decode(\"UTF-8\"),\n userHash.decode(\"UTF-8\"),\n dcName.decode(\"UTF-8\"),\n sid.decode(\"UTF-8\"),\n )\n )\n\n return uniquify_tuples(creds)\n\n\n###############################################################\n#\n# Miscellaneous methods (formatting, sorting, etc.)\n#\n###############################################################\n\n\ndef get_datetime():\n \"\"\"\n Return the local current date/time\n \"\"\"\n return datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\n\ndef get_file_datetime():\n \"\"\"\n Return the current date/time in a format workable for a file name.\n \"\"\"\n return datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")\n\n\ndef get_file_size(file):\n \"\"\"\n Returns a string with the file size and highest rating.\n \"\"\"\n byte_size = sys.getsizeof(file)\n kb_size = old_div(byte_size, 1024)\n if kb_size == 0:\n byte_size = \"%s Bytes\" % (byte_size)\n return byte_size\n mb_size = old_div(kb_size, 1024)\n if mb_size == 0:\n kb_size = \"%s KB\" % (kb_size)\n return kb_size\n gb_size = old_div(mb_size, 1024) % (mb_size)\n if gb_size == 0:\n mb_size = \"%s MB\" % (mb_size)\n return mb_size\n return \"%s GB\" % (gb_size)\n\n\ndef lhost():\n \"\"\"\n Return the local IP.\n \"\"\"\n\n if os.name != \"nt\":\n import fcntl\n import struct\n\n def get_interface_ip(ifname):\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n return socket.inet_ntoa(\n fcntl.ioctl(\n s.fileno(),\n 0x8915, # SIOCGIFADDR\n struct.pack(\"256s\", ifname[:15].encode(\"UTF-8\")),\n )[20:24]\n )\n except IOError:\n return \"\"\n\n ip = \"\"\n try:\n ip = socket.gethostbyname(socket.gethostname())\n except socket.gaierror:\n pass\n except Exception:\n log.error(\"Unexpected error:\", exc_info=True)\n return ip\n\n if (ip == \"\" or ip.startswith(\"127.\")) and os.name != \"nt\":\n interfaces = netifaces.interfaces()\n for ifname in interfaces:\n if \"lo\" not in ifname:\n try:\n ip = get_interface_ip(ifname)\n if ip != \"\":\n break\n except Exception:\n log.error(\"Unexpected error:\", exc_info=True)\n pass\n return ip\n\n\ndef color(string, color=None):\n \"\"\"\n Change text color for the Linux terminal.\n \"\"\"\n\n attr = []\n # bold\n attr.append(\"1\")\n\n if color:\n if color.lower() == \"red\":\n attr.append(\"31\")\n elif color.lower() == \"green\":\n attr.append(\"32\")\n elif color.lower() == \"yellow\":\n attr.append(\"33\")\n elif color.lower() == \"blue\":\n attr.append(\"34\")\n return \"\\x1b[%sm%s\\x1b[0m\" % (\";\".join(attr), string)\n\n else:\n if string.strip().startswith(\"[!]\"):\n attr.append(\"31\")\n return \"\\x1b[%sm%s\\x1b[0m\" % (\";\".join(attr), string)\n elif string.strip().startswith(\"[+]\"):\n attr.append(\"32\")\n return \"\\x1b[%sm%s\\x1b[0m\" % (\";\".join(attr), string)\n elif string.strip().startswith(\"[*]\"):\n attr.append(\"34\")\n return \"\\x1b[%sm%s\\x1b[0m\" % (\";\".join(attr), string)\n elif string.strip().startswith(\"[>]\"):\n attr.append(\"33\")\n return \"\\x1b[%sm%s\\x1b[0m\" % (\";\".join(attr), string)\n else:\n return string\n\n\ndef unique(seq, idfun=None):\n \"\"\"\n Uniquifies a list, order preserving.\n\n from http://www.peterbe.com/plog/uniqifiers-benchmark\n \"\"\"\n if idfun is None:\n\n def idfun(x):\n return x\n\n seen = {}\n result = []\n for item in seq:\n marker = idfun(item)\n # in old Python versions:\n # if seen.has_key(marker)\n # but in new ones:\n if marker in seen:\n continue\n seen[marker] = 1\n result.append(item)\n return result\n\n\ndef uniquify_tuples(tuples):\n \"\"\"\n Uniquifies Mimikatz tuples based on the password.\n\n cred format- (credType, domain, username, password, hostname, sid)\n \"\"\"\n seen = set()\n return [\n item\n for item in tuples\n if \"%s%s%s%s\" % (item[0], item[1], item[2], item[3]) not in seen\n and not seen.add(\"%s%s%s%s\" % (item[0], item[1], item[2], item[3]))\n ]\n\n\ndef decode_base64(data):\n \"\"\"\n Try to decode a base64 string.\n From http://stackoverflow.com/questions/2941995/python-ignore-incorrect-padding-error-when-base64-decoding\n \"\"\"\n missing_padding = 4 - len(data) % 4\n if isinstance(data, str):\n data = data.encode(\"UTF-8\")\n\n if missing_padding:\n data += b\"=\" * missing_padding\n\n try:\n result = base64.decodebytes(data)\n return result\n except binascii.Error:\n # if there's a decoding error, just return the data\n return data\n\n\ndef encode_base64(data):\n \"\"\"\n Encode data as a base64 string.\n \"\"\"\n return base64.encodebytes(data).strip()\n\n\nclass KThread(threading.Thread):\n \"\"\"\n A subclass of threading.Thread, with a kill() method.\n From https://web.archive.org/web/20130503082442/http://mail.python.org/pipermail/python-list/2004-May/281943.html\n \"\"\"\n\n def __init__(self, *args, **keywords):\n threading.Thread.__init__(self, *args, **keywords)\n self.killed = False\n\n def start(self):\n \"\"\"Start the thread.\"\"\"\n self.__run_backup = self.run\n self.run = self.__run # Force the Thread toinstall our trace.\n threading.Thread.start(self)\n\n def __run(self):\n \"\"\"Hacked run function, which installs the trace.\"\"\"\n sys.settrace(self.globaltrace)\n self.__run_backup()\n self.run = self.__run_backup\n\n def globaltrace(self, frame, why, arg):\n if why == \"call\":\n return self.localtrace\n else:\n return None\n\n def localtrace(self, frame, why, arg):\n if self.killed:\n if why == \"line\":\n raise SystemExit()\n return self.localtrace\n\n def kill(self):\n self.killed = True\n\n\ndef slackMessage(slack_webhook_url, slack_text):\n message = {\"text\": slack_text}\n req = urllib.request.Request(slack_webhook_url, json.dumps(message).encode(\"UTF-8\"))\n urllib.request.urlopen(req)\n","sub_path":"empire/server/common/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":25787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"292319443","text":"import discord\nimport asyncio\nimport requests\nimport time\nimport string\nimport random\n\nDISCORD_BOT_TOKEN = 'NDM0MjM2MjI2NTczNDM0ODkx.DbIc-w.ufvbmB_MSVQqd7kIHrUFMQxdxnc'\n\nBTC_PRICE_URL_coinmarketcap = 'https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=RUB'\n\nclient = discord.Client()\n#http = discord.http\n\nsave_channel = 0\nadmin_list = ['265474107666202634', '282660110545846272']\nadmin_channel_list = ['434056729362169857', '433267590937444364', '43568779755939430']\n\nprefix = '!'\nstops = 0\n#lock = 0\n\nquiz_channel = 0\nquiz = 0\nquiz_number = -1\nquiz_numbers = -1\nset_answer = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']\n\nquestion = ['1) https://sun9-6.userapi.com/c840724/v840724591/74499/x8hB5rkgIkU.jpg',\n\t\t\t'2) https://pp.userapi.com/c846320/v846320591/23582/SClHqmmWE0Y.jpg',\n\t\t\t'3) https://pp.userapi.com/c834100/v834100591/116733/OuwBfc0GKwc.jpg',\n\t\t\t'4) https://pp.userapi.com/c841639/v841639591/7ee08/UC7dluXRGgI.jpg',\n\t\t\t'5) https://pp.userapi.com/c834202/v834202591/d6b84/AnYJtA--lE0.jpg',\n\t\t\t'6) https://pp.userapi.com/c824411/v824411591/1164c1/5mZIEYsbHAI.jpg',\n\t\t\t'7) https://pp.userapi.com/c846017/v846017591/24701/Bh25snWBCl8.jpg',\n\t\t\t'8) https://pp.userapi.com/c846219/v846219591/23a84/EV5tVSseGj4.jpg',\n\t\t\t'9) https://pp.userapi.com/c847020/v847020591/2557b/K21NUu_G_ec.jpg',\n\t\t\t'10) https://pp.userapi.com/c834203/v834203591/117502/4NYjkoSAtnU.jpg',\n\t\t\t'11) https://pp.userapi.com/c831508/v831508591/d3c68/qtlwIGrbvwc.jpg',\n\t\t\t'12) https://pp.userapi.com/c830609/v830609591/cf56e/NIfBShi_EGM.jpg',\n\t\t\t'13) https://pp.userapi.com/c834104/v834104533/112c65/A2mmg_mLiK4.jpg',\n\t\t\t'14) https://pp.userapi.com/c845019/v845019533/2c064/t6Z4_1yxetE.jpg',\n\t\t\t'15) https://pp.userapi.com/c844720/v844720523/28eed/Im1kZS1WoKI.jpg',\n\t\t\t'16) https://pp.userapi.com/c834100/v834100897/114102/qeXr4eut2oU.jpg',\n\t\t\t'17) https://pp.userapi.com/c847123/v847123209/2630f/QZKvAWreGN4.jpg',\n\t\t\t'18) https://pp.userapi.com/c830108/v830108944/d1c82/ZnnQbYyVA-g.jpg',\n\t\t\t'19) https://pp.userapi.com/c841221/v841221058/74759/2qj4ClVx0GQ.jpg',\n\t\t\t'20) https://pp.userapi.com/c831309/v831309589/ca39f/_2ATdwnWZVE.jpg',\n\t\t\t'21) http://animeru.tv/assets/images/resources/1575/1791ca9d6eb0fa2c28e5f15000d518258641d54a.jpg',\n\t\t\t'22) https://scontent-arn2-1.cdninstagram.com/vp/ae79ff0ec82053fc68d40dae663466c8/5B2FD62C/t51.2885-15/e35/23164144_587504724707054_4524634221112721408_n.jpg',\n\t\t\t'23) https://awesomereviews.ru/wp-content/uploads/2017/09/%D0%91%D0%BB%D0%B8%D1%82%D1%86-%D0%A2%D0%BE%D0%BB%D0%BA%D0%B5%D1%80.jpg',\n\t\t\t'24) http://i.imgur.com/QYr2C7c.jpg',\n\t\t\t'25) https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQYVb09iGL5Fe63aMQx8hXnsECcuqpxupUciSbXnHf2j10Ue_4dTg',\n\t\t\t'26) https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQIuyzrQBascnms3B1vOeTJF6NHfQYIw4HlJZMdt9KsHtKVe64Jfw',\n\t\t\t'27) http://nisamerica.com/lovelive/images/screenshots/9.jpg',\n\t\t\t'28) https://pbs.twimg.com/media/C9xjyVFXkAIiyhs.jpg']\n\nquiz_answer = [['врата штейна', 'врата штайнера'],\n\t\t ['сегодняшний ужин для эмии', 'сегодняшнее меню для эмии'],\n\t\t ['проект воспитания девочек-волшебниц'],\n\t\t ['кейон!', 'кейон', 'легкая музыка!', 'легкая музыка', 'клуб легкой музыки'],\n\t\t ['созданный в бездне'],\n\t\t ['невероятные приключения джоджо', 'джоджо', 'жожо'],\n\t\t ['девочка-волшебница мадока магика', 'девочка-волшебница мадока', 'девочка волшебница мадока'],\n\t\t ['загадочная история коноханы', 'сказания о конохане', 'история коноханы'],\n\t\t ['садистская смесь'],\n\t\t ['любовь и тьма неприятностей'],\n\t\t ['судный день', 'день гнева'],\n\t\t ['ведьмина магия в деле', 'ведьма за работой'],\n\t\t ['бтууум!', 'взрыв', 'взрыв!', 'бтууум'],\n\t\t ['сердцу хочеться кричать', 'сердцу хочеться петь'],\n\t\t ['шарлотта'],\n\t\t ['связанные'],\n\t\t ['город, в котором меня нет', 'город в котором меня нет', 'город, в котором пропал лишь я', 'город в котором пропал лишь я'],\n\t\t ['слуга вампир', 'сервамп'],\n\t\t ['проклятие мультивыбора превратило мою жизнь в ад', 'проклятие мультивыбора', 'проклятье мультивыбора превратило мою жизнь в ад', 'проклятье мультивыбора'],\n\t\t ['полулюди', 'получеловек', 'аджин'],\n\t\t ['скучный мир в котором не существует понятия грязные шуточки', 'скучный мир, в котором не существует понятия грязные шуточки', 'скучный мир, в котором не существует самой концепции похабных шуток', 'скучный мир в котором не существует самой идеи похабных шуток', 'трусонюх'],\n\t\t ['повар-боец сома: в поисках божественного рецепта', 'повар боец сома', 'боевой повар сома', 'в поисках божественного рецепта', 'повар-боец сома'],\n\t\t ['возрождающие'],\n\t\t ['притворная любовь'],\n\t\t ['кейджо', 'кэйджо!!!!!!!!', 'кейджо!!!!!!!!', 'кэйджо'],\n\t\t ['баскетбол куроко'],\n\t\t ['живая любовь'],\n\t\t ['эроманга-сенсей', 'эроманга сенсей']]\n\nmat_list = []\n\n#------------------------------------------------------------------------------------------------------------------------------\n# Economics\n#------------------------------------------------------------------------------------------------------------------------------\ndaily_id = []\nnames = []\ncookie = []\n\n\nreport = 0\n\nchannel_list = []\nf = open('channel_list', 'r')\nline1 = f.readline()\nline2 = f.readline()\nc = 0\nwhile line1:\n\tchannel_list.append(line1)\n\tchannel_list.append(line2)\n\tline1 = f.readline()\n\tline2 = str(f.readline())\n\tprint(str((c // 2) + 1) + ')' + channel_list[c][:-1] + ' ' + channel_list[c + 1][:-1])\n\tc = c + 2\nf.close()\n\nprint('------')\n\nf = open('daily', 'r')\nline1 = f.readline()\nc = 0\nwhile line1:\n\tdaily_id.append(line1[:-1])\n\tline1 = f.readline()\n\tprint(str(c + 1) + ')' + daily_id[c])\n\tc = c + 1\nf.close()\n\nf = open('cookie', 'r')\nline1 = f.readline()\nline2 = f.readline()\nwhile line1:\n\tnames.append(line1[:-1])\n\tcookie.append(line2[:-1])\n\tline1 = f.readline()\n\tline2 = f.readline()\nf.close()\n\nf = open('mat', 'r')\nline1 = f.readline()\nwhile line1:\n\tmat_list.append(line1[:-1])\n\tline1 = f.readline()\nprint('mat_list is ready.')\nf.close()\n\nprint('------')\n\nrandom.seed()\n\n\nasync def daily_cookie():\n\tglobal daily_id\n\tawait client.wait_until_ready()\n\twhile not client.is_closed:\n\t\tdaily_id = []\n\t\tf = open('daily', 'w')\n\t\tfor s in daily_id:\n\t\t\tf.write(s + \"\\n\")\n\t\tf.close()\n\t\tprint('---------[command]:daily_cookie')\n\t\tawait asyncio.sleep(3600)\n\nclient.loop.create_task(daily_cookie())\n\n\n@client.event\nasync def on_ready():\n\tprint('Logged in as')\n\tprint(client.user.name)\n\tprint(client.user.id)\n\tprint('------')\n\tawait client.change_presence(game=discord.Game(name='My Code Is Dead'))\n\n@client.event\nasync def on_message(message):\n\n\tprint('<' + message.channel.name+ '>'+ '[' + message.author.name + '|' + message.author.id + ']' + message.content)\n\n\tglobal stops\n\tglobal save_channel\n\tglobal question\n\tglobal quiz_channel\n\tglobal quiz\n\tglobal quiz_number\n\tglobal quiz_numbers\n\tglobal set_answer\n\tglobal quiz_answer\n\tglobal daily_id\n\tglobal mat_list\n\tglobal cookie\n\tglobal names\n\tglobal report\n\n\tif message.content.startswith(prefix + 'btcprice'):\n\t\tprint('---------[command]: btcprice ')\n\t\tf = open('config', 'w')\n\t\tf.write(message.author)\n\t\tf.close()\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]: btcprice\\n```')\n\t\tbtc_price_usd, btc_price_rub = get_btc_price()\n\t\tawait client.send_message(message.channel, 'USD: ' + str(btc_price_usd) + ' | RUB: ' + str(btc_price_rub))\n\t\tawait client.delete_message(message)\n\n\tif strcmp(message.content, prefix + 'login') and message.author.id == '282660110545846272':\n\t\tprint('---------[command]:!login')\n\t\treport = message.author\n\t\tawait client.delete_message(message)\n\n\t#if '<@282660110545846272>' in message.content and message.author.id != '282660110545846272' and message.author.id != '434785638840008738':\n\t# print('---------[command]:mention cookie')\n\t# #await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:mention cookie\\n```')\n\t# await client.send_message(message.channel, 'Хватит ддосить моего Создателя!!!')\n\t# await client.delete_message(message)\n\n\t#if '<@175571075931963393>' in message.content:\n\t# print('---------[command]:mention soya')\n\t# #await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:mention soya\\n```')\n\t# await client.send_message(message.channel, ':sparkles::regional_indicator_s: :regional_indicator_o: :regional_indicator_y: :regional_indicator_a: :regional_indicator_j: :regional_indicator_o: :regional_indicator_n: :regional_indicator_e: :regional_indicator_s::sparkles:')\n\t# #await client.delete_message(message)\n\n\tif message.content.startswith(prefix + 'ddos'):\n\t\tif message.author.id in admin_list:\n\t\t\tprint('---------[command]:!ddos ' + message.content[6:])\n\t\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!ddos ' + message.content[6:] + '\\n```')\n\t\t\ti = 0\n\t\t\tstops = 0\n\t\t\twhile i < 30:\n\t\t\t\ti = i + 1\n\t\t\t\tif(stops == 1):\n\t\t\t\t\tbreak\n\t\t\t\tawait client.send_message(message.channel, message.content[6:])\n\t\t\t\ttime.sleep(0.5)\n\t\t\tstops = 0\n\t\tawait client.delete_message(message)\n\n\tif (strcmp(message.content, prefix + 'stop') == 1):\n\t\tprint('---------[command]:!stop')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!stop\\n```')\n\t\tstops = 1\n\t\tawait client.delete_message(message)\n\n\tif strcmp(message.content.lower(), 'печенюха') or strcmp(message.content.lower(), 'печенька'):\n\t\tprint('---------[command]:!cookie')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!cookie\\n```')\n\t\tawait client.send_message(message.channel, \"О, я тоже хочу, поделитесь?:cookie:\")\n\n\tif strcmp(message.content, prefix + 'hi'):\n\t\tprint('---------[command]:!hi')\n\t #await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!hi')\n\t\tawait client.send_message(message.channel, ':sparkles:' + message.author.name + ' приветствует всех:sparkles:\\n')\n\t\tawait client.delete_message(message)\n\n\tif strcmp(message.content, prefix + 'pic'):\n\t\tprint('---------[command]:!pic')\n\t\tawait client.send_message(message.channel, 'Держи арт!')\n\t\tawait client.send_file(message.channel, 'pic/konachan.jpg')\n\t\tawait client.delete_message(message)\n\n\tif strcmp(message.content, prefix + 'gm'):\n\t\tprint('---------[command]:!gm')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!gm\\n```')\n\t\tawait client.send_message(message.channel, ':hugging:С добрым утречком:hugging:')\n\t\tawait client.delete_message(message)\n\n\tif strcmp(message.content, prefix + 'help'):\n\t\tprint('---------[command]:!help')\n\t\tawait client.send_message(message.channel, '```css\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t '[Pineapple Cookie help]\\n\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t '\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'daily - Получить часовую порцию печенюх.\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'cookie / ' + prefix +'me - Узнать свой баланс печенюх.\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'roll <ставка> - Поставить печенюхи на рулетке.\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'give <кому> <сколько> - Поделиться печенюхами с другом.\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'rang - Посмотреть на обжор.\\n\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t '\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t 'Печенюха/печенька - Попросит вкуснях. Это две команды. Буквы могут быть любого размера.\\nПишется без префикса.\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t 'Меншн Сони выдаст интересный набор смайликов))). Но не стоит слишком часто юзать эту функцию.\\nГрозит перманентным баном по айди на доступ к этой команде.\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'say <текст> - Напишет ваше сообщение.\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'hi - Поприветствует всех от вашего имени.\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'gm - Охайё, т.е доброе утро)).\\n\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t '\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'help - Вызов этой справки.\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'report <текст> - Отправить сообщение разработчику. Баги, пожелания, предложения руки и сердца кидать сюда-ня.\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t '```')\n\t\tawait client.delete_message(message)\n\n\tif strcmp(message.content, prefix + 'oldhelp') == 1 and message.author.id in admin_list:\n\t\tprint('---------[command]:!oldhelp')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!help\\n```')\n\t\tawait client.send_message(message.channel, '```css\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t '[cookie help]\\n\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t 'Печенюха/печенька - Попросит вкуснях. Это две команды. Буквы могут быть любого размера.\\nПишется без префикса.\\n\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t 'Меншн Сони выдаст интересный набор смайликов))). Но не стоит слишком часто юзать эту функцию.\\nГрозит перманентным баном по айди на доступ к этой команде.\\n\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'say <текст> - Напишет ваше сообщение.\\n\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'hi - Поприветствует всех от вашего имени.\\n\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'gm - Охайё, т.е доброе утро)).\\n\\n' +\n\t\t\t\t\t\t\t\t\t\t\t\t prefix + 'help - Вызов этой справки.' +\n\t\t\t\t\t\t\t\t\t\t\t\t '```')\n\t\tawait client.delete_message(message)\n\n\tif strcmp(message.content, prefix + 'save') == 1 and message.author.id in admin_list:\n\t\tprint('---------[command]:!save')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!save```')\n\t\tsave_channel = message.channel\n\t\tf = open('channel_list', 'a')\n\t\tf.write(save_channel.name + '\\n' + save_channel.id)\n\t\tf.close\n\t\tawait client.delete_message(message)\n\n\tif message.content.startswith(prefix + 'say '):\n\t\tprint('---------[command]:!say')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!say```')\n\t\tawait client.send_message(message.channel, message.content[5:])\n\t\tawait client.delete_message(message)\n\n\tif message.content.startswith(prefix + 'report '):\n\t\tprint('---------[command]:!report')\n\t\tawait client.send_message(report, '<' + message.author.name + '|' + message.author.id+ '>'+ ' ' + message.content[8:])\n\t\tawait client.delete_message(message)\n\n\tif message.content.startswith(prefix + 'sayhim') and message.author.id in admin_list:\n\t\tprint('---------[command]:!sayhim')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!sayhim```')\n\t\tawait client.send_message(client.get_channel(channel_list[int(message.content[8]) * 2 - 1][:-1]), message.content[10:])\n\t\tawait client.delete_message(message)\n\n\tif strcmp(message.content, prefix + 'start quiz') == 1 and message.author.id in admin_list:\n\t\tprint('---------[command]:!start quiz')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!start quiz\\n```')\n\t\tquiz_channel = message.channel\n\t\tquiz = 1\n\t\tawait client.send_message(message.channel, 'Викторина началась!')\n\t\tawait client.delete_message(message)\n\n\tif strcmp(message.content, prefix + 'stop quiz') == 1 and message.author.id in admin_list:\n\t\tprint('---------[command]:!stop quiz')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!stop quiz\\n```')\n\t\tquiz_channel = 0\n\t\tquiz = 0\n\t\tawait client.send_message(message.channel, 'Викторина окончена))\\n\\nОгромное спасибо спонсорам сегодняшней викторины - Rumata и <@265474107666202634>')\n\t\tawait client.delete_message(message)\n\n\tif message.content.startswith(prefix + 'quiz ') and message.author.id in admin_list and quiz == 1 and message.channel != quiz_channel:\n\t\tquiz_number = int(message.content[6:]) - 1\n\t\tquiz_numbers = quiz_number\n\t\tprint('---------[command]:!quiz ' + str(quiz_number))\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!quiz ' + str(quiz_number) + '\\n```')\n\t\tawait client.send_message(quiz_channel, question[quiz_number])\n\t\tawait client.delete_message(message)\n\n\tif message.content.startswith(prefix + 'quizans') and message.author.id in admin_list:\n\t\tprint('---------[command]:!quizans ' + message.content[9:])\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!quizans ' + message.content[9:] + '\\n```')\n\t\tif quiz_number == -1:\n\t\t\tawait client.send_message(quiz_channel, 'А что же произошло? Грац, вы нашли недоработку с нашей стороны, а раз так, то победил челик ниже:')\n\t\tset_answer[quiz_numbers] = str(quiz_numbers + 1) + ')' + message.content[9:]\n\t\tawait client.send_message(quiz_channel, message.content[9:] + ', верно!')\n\t\tawait client.delete_message(message)\n\n\tif message.channel == quiz_channel and quiz:\n\t\tprint('---------[command]:!quiz answer - ' + message.content)\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!quiz answer - ' + message.content + '\\n```')\n\t\tif quiz_number != -1:\n\t\t\tif message.content.lower() in quiz_answer[quiz_number]:\n\t\t\t\tif quiz_number != -1:\n\t\t\t\t\tquiz_number = -1\n\t\t\t\t\tset_answer[quiz_number] = str(quiz_number + 1) + ')' + message.author.id + ' ' + message.author.name\n\t\t\t\t\tawait client.send_message(quiz_channel, '<@' + message.author.id+ '>'+ ', верно!')\n\n\tif strcmp(message.content, prefix + 'quizstat') == 1 and message.author.id in admin_list:\n\t\tprint('---------[command]:!quiz stat')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!quiz stat\\n```')\n\t\tret = '```css'\n\t\tfor s in set_answer:\n\t\t\tret = ret + '\\n' + s\n\t\tret = ret + '\\n```'\n\t\tawait client.send_message(message.channel, ret)\n\t\tawait client.delete_message(message)\n\n\tif strcmp(message.content, prefix + 'quizquestions') == 1 and message.author.id in admin_list:\n\t\tprint('---------[command]:!quizquestions')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!quizquestions\\n```')\n\t\tret = '```css'\n\t\tfor s in question:\n\t\t\tret = ret + '\\n' + s\n\t\tret = ret + '\\n```'\n\t\tawait client.send_message(message.channel, ret)\n\t\tawait client.delete_message(message)\n\n\tif strcmp(message.content, prefix + 'quizanswers') == 1 and message.author.id in admin_list:\n\t\tprint('---------[command]:!quizanswers')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!quizanswers\\n```')\n\t\tret = '```css'\n\t\tfor s in quiz_answer:\n\t\t\tret = ret + '\\n' + s\n\t\tret = ret + '\\n```'\n\t\tawait client.send_message(message.channel, ret)\n\t\tawait client.delete_message(message)\n\n\tif strcmp(message.content.lower(), 'соня'):\n\t\tprint('---------[command]:!sonya')\n\t\t#await client.send_message(client.get_channel('43569861995842766'), '```css\\n[command]:!sonya\\n```')\n\t\tawait client.send_message(message.channel, 'Соня лучшая!!!')\n\t\tawait client.delete_message(message)\n\n\n\tif message.content.lower() in mat_list:\n\t\tprint('---------[command]:!sukablyat')\n\t\tawait client.send_message(message.author, 'Не матерись, пожалуйста)) ')\n\t\tawait client.delete_message(message)\n\n\n#------------------------------------------------------------------------------------------------------------------------------\n# Economics\n#------------------------------------------------------------------------------------------------------------------------------\n\tif strcmp(message.content.lower(), prefix + 'daily reset') == 1 and message.author.id in admin_list and message.channel.id in admin_channel_list:\n\t\tprint('---------[command]:!daily reset')\n\t\tdaily_id = []\n\t\tf = open('daily', 'w')\n\t\tfor s in daily_id:\n\t\t\tf.write(s + \"\\n\")\n\t\tf.close()\n\t\tawait client.send_message(message.channel, 'Ежедневка сброшена.')\n\t\tawait client.delete_message(message)\n#--------------------------------------------------------------------------------------------------------------------------------------------------------\n\tif strcmp(message.content.lower(), prefix + 'daily'):\n\t\tprint('---------[command]:!daily')\n\t\tif message.author.id in daily_id:\n\t\t\tawait client.send_message(message.channel, '<@' + message.author.id+ '>'+ ', вы уже получили печенюхи)')\n\t\telse:\n\t\t\tdaily_id.append(str(message.author.id))\n\t\t\tf = open('daily', 'w')\n\t\t\tc = 0\n\t\t\tfor s in daily_id:\n\t\t\t\tf.write(s + \"\\n\")\n\t\t\t\tc = c + 1\n\t\t\tf.close()\n\t\t\tcookie_count = 100\n\t\t\tif message.author.id in names:\n\t\t\t\tc = 0\n\t\t\t\twhile(names[c] != message.author.id):\n\t\t\t\t\tc = c + 1\n\t\t\t\tcookie[c] = str(int(cookie[c]) + cookie_count)\n\t\t\t\tf = open('cookie', 'w')\n\t\t\t\tc = 0\n\t\t\t\tfor s in cookie:\n\t\t\t\t\tf.write(names[c] + '\\n' + s + \"\\n\")\n\t\t\t\t\tc = c + 1\n\t\t\t\tf.close()\n\t\t\telse:\n\t\t\t\tnames.append(message.author.id)\n\t\t\t\tcookie.append(str(cookie_count))\n\t\t\tawait client.send_message(message.channel, '<@' + message.author.id+ '>'+ '' + ', держи ' + str(cookie_count) + ':cookie:!')\n\t\tawait client.delete_message(message)\n#--------------------------------------------------------------------------------------------------------------------------------------------------------\n\tif (strcmp(message.content.lower(), prefix + 'cookie') == 1 or strcmp(message.content.lower(), prefix + 'me') == 1):\n\t\tprint('---------[command]:!cookie')\n\t\tif message.author.id in names:\n\t\t\tc = 0\n\t\t\twhile(names[c] != message.author.id):\n\t\t\t\tc = c + 1\n\t\t\tawait client.send_message(message.channel, '<@' + message.author.id+ '>'+ '' + ', у тебя ' + cookie[c] + ':cookie:!')\n\t\telse:\n\t\t\tawait client.send_message(message.channel, '<@' + message.author.id+ '>'+ '' + ', у тебя нет:cookie: :(')\n\t\tawait client.delete_message(message)\n#--------------------------------------------------------------------------------------------------------------------------------------------------------\n\tif message.content.startswith(prefix + 'roll '):\n\t\tprint('---------[command]:!roll')\n\t\tif not message.content[6:].isdigit():\n\t\t\tawait client.send_message(message.channel, '```css\\nError!!! Введенное значение не является числом\\nExample: ' + prefix + 'roll 20\\n```')\n\t\telif message.author.id in names:\n\t\t\tc = 0\n\t\t\twhile(names[c] != message.author.id):\n\t\t\t\tc = c + 1\n\t\t\tif (int(message.content[6:]) > int(cookie[c])):\n\t\t\t\tawait client.send_message(message.channel, '<@' + message.author.id+ '>'+ '' + ', у тебя нет столько:cookie: :(')\n\t\t\telse:\n\t\t\t\tif (random.randint(0, 100) + 7) > 50:\n\t\t\t\t#if (random.random() == 1):\n\t\t\t\t\tcookie[c] = str(int(cookie[c]) + int(message.content[6:]))\n\t\t\t\t\tf = open('cookie', 'w')\n\t\t\t\t\tc = 0\n\t\t\t\t\tfor s in cookie:\n\t\t\t\t\t\tf.write(names[c] + '\\n' + s + \"\\n\")\n\t\t\t\t\t\tc = c + 1\n\t\t\t\t\tf.close()\n\t\t\t\t\tawait client.send_message(message.channel, '<@' + message.author.id+ '>, ты выиграл ' + str(int(message.content[6:])) + ':cookie:')\n\t\t\t\telse:\n\t\t\t\t\tcookie[c] = str(int(cookie[c]) - int(message.content[6:]))\n\t\t\t\t\tf = open('cookie', 'w')\n\t\t\t\t\tc = 0\n\t\t\t\t\tfor s in cookie:\n\t\t\t\t\t\tf.write(names[c] + '\\n' + s + \"\\n\")\n\t\t\t\t\t\tc = c + 1\n\t\t\t\t\tf.close()\n\t\t\t\t\tawait client.send_message(message.channel, '<@' + message.author.id+ '>, ты проиграл ' + (message.content[6:]) + ':cookie:')\n\t\telse:\n\t\t\tawait client.send_message(message.channel, '<@' + message.author.id+ '>, у тебя нет:cookie: :(')\n\t\tawait client.delete_message(message)\n#--------------------------------------------------------------------------------------------------------------------------------------------------------\n\tif strcmp(message.content.lower(), prefix + 'cookie update'):\n\t\tprint('---------[command]:!cookie update')\n\t\tf = open('cookie', 'r')\n\t\tnames = []\n\t\tcookie = []\n\t\tline1 = f.readline()\n\t\tline2 = f.readline()\n\t\tc = 0\n\t\twhile line1:\n\t\t\tnames.append(line1[:-1])\n\t\t\tcookie.append(line2[:-1])\n\t\t\tline1 = f.readline()\n\t\t\tline2 = f.readline()\n\t\tf.close()\n\t\tawait client.send_message(message.channel, 'Обновлено из файла.')\n\t\tawait client.delete_message(message)\n#--------------------------------------------------------------------------------------------------------------------------------------------------------\n\tif message.content.startswith(prefix + 'give '):\n\t\tprint('---------[command]:!give')\n\t\tparams = message.content.lower().split(' ')\n\t\tif not message.author.id in names:\n\t\t\tawait client.send_message(message.channel, '<@' + message.author.id+ '>'+ '' + ', у тебя нет:cookie: :(')\n\t\telif params[1][2:-1] in names:\n\t\t\tc = 0\n\t\t\twhile(names[c] != params[1][2:-1]):\n\t\t\t\tc = c + 1\n\t\t\tk = 0\n\t\t\twhile(names[k] != message.author.id):\n\t\t\t\tk = k + 1\n\t\t\tif not params[2].isdigit():\n\t\t\t\tawait client.send_message(message.channel, '```css\\nError!!! Введенное значение не является числом\\nExample: ' + prefix + 'give 500\\n```')\n\t\t\telif (int(params[2]) > int(cookie[k])):\n\t\t\t\tawait client.send_message(message.channel, '<@' + message.author.id+ '>, у тебя нет столько:cookie: :(')\n\t\t\telse:\n\t\t\t\tcookie[c] = str(int(cookie[c]) + int(params[2]))\n\t\t\t\tcookie[k] = str(int(cookie[k]) - int(params[2]))\n\t\t\t\tf = open('cookie', 'w')\n\t\t\t\tc = 0\n\t\t\t\tfor s in cookie:\n\t\t\t\t\tf.write(names[c] + '\\n' + s + \"\\n\")\n\t\t\t\t\tc = c + 1\n\t\t\t\tf.close()\n\t\t\t\tawait client.send_message(message.channel, '<@' + message.author.id+ '>, подарил ' + params[1] + ' ' + params[2] + ':cookie:')\n\t\telse:\n\t\t\tawait client.send_message(message.channel, 'Нет такого пользователя :(')\n\t\tawait client.delete_message(message)\n#--------------------------------------------------------------------------------------------------------------------------------------------------------\n\tif strcmp(message.content.lower(), prefix + 'rang'):\n\t\tprint('---------[command]:!rang')\n\t\tnam = names\n\t\tcoo = cookie\n\t\tc = 0\n\t\tp = 0\n\t\tret = 'Leaderboards:\\n'\t\n\t\twhile c < 10:\n\t\t\tif len(nam) > 0:\n\t\t\t\tp = max(cookie)\n\t\t\t\tret = ret + str(c + 1) + ') <@' + nam.pop(p) + '> - ' + coo.pop(p) + ':cookie:\\n'\n\t\t\telse:\n\t\t\t\tbreak\n\t\t\tc = c + 1\n\t\tem = discord.Embed(description=ret, colour=0xC5934B)\n\t\tawait client.send_message(message.channel, embed=em)\n\t\tawait client.delete_message(message)\n\n\n\tif strcmp(message.content.lower(), prefix + 'embed'):\n\t\tem = discord.Embed(title='Крутим пальчиками.', colour=0xC5934B)\n\t\tem.set_image(url='http://i0.kym-cdn.com/photos/images/original/000/448/492/bfa.gif')\n\t\tawait client.send_message(message.channel, embed=em)\n\t\tawait client.delete_message(message)\n\n\n\n#if message.content.lower() in mat_list:\n# print('Удаляю мат!')\n# await client.send_message(message.channel, 'Извени но я вырезала твой мат \\nhttps://iichan.hk/a/arch/src/1331445120492.gif%27')\n# msg = await client.send_message(message.author, 'Не матерись, пожалуста)) ')\n# await client.edit_message(msg,'Извени но я вырезала твой мат')\n\n\ndef max(list):\n maximum = 0\n p = 0\n for s in range(len(list)):\n if int(list[s]) > maximum:\n maximum = int(list[s])\n p = s\n return p\n\n\ndef strcmp(s1, s2):\n\ti1 = 0\n\ti2 = 0\n\ts1 = s1 + '\\0'\n\ts2 = s2 + '\\0'\n\twhile ((s1[i1] != '\\0') & (s2[i2] != '\\0')):\n\t\tif(s1[i1] != s2[i2]):\n\t\t\treturn 0\n\t\ti1 = i1 + 1\n\t\ti2 = i2 + 1\n\tif(s1[i1] != s2[i2]):\n\t\treturn 0\n\telse:\n\t\treturn 1\n\n\ndef get_btc_price():\n\tr = requests.get(BTC_PRICE_URL_coinmarketcap)\n\tresponse_json = r.json()\n\tusd_price = response_json[0]['price_usd']\n\trub_rpice = response_json[0]['price_rub']\n\treturn usd_price, rub_rpice\n\nclient.run(DISCORD_BOT_TOKEN)\n","sub_path":"Pineapple_Cookie/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":29335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"190758472","text":"from ordenacoes.lista_gen.ListGen import ListGen\n\nif __name__ == '__main__':\n lg = ListGen()\n\n str = \"[aa, [bb,cc], [dd,[ee], ff,gg], hh]\"\n\n lg.insertStr(str)\n lg.showString()\n\n\n\"\"\"\n[aa, [bb,cc], [dd,[ee], ff,gg], hh]\n[aa, [bb,cc], hh]\n[aa, [bb]]\n[[dd, [ee],ff, []], [hh]]\n[aa, [[bb]], [[[dd,lll]]]]\n[aaaaaaaaaaaaa,ccccccccccccc,[a],[dd,[dd],[aa]]]\n[[[[cc]]]]\n[[[]]]\n\n\"\"\"","sub_path":"ordenacoes/lista_gen/App.py","file_name":"App.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"581387236","text":"# Ref: https://jakevdp.github.io/PythonDataScienceHandbook/04.04-density-and-contour-plots.html\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nProblem1='capacitor'\nProblem2='mirror_charge'\nProblem3='charge_plate'\n\nFile1=Problem1+\".dat\"\nFile2=Problem2+\".dat\"\nFile3=Problem3+\".dat\"\n\nX1,Y1,Charge1,P1 = np.loadtxt(File1, unpack=True)\nX2,Y2,Charge2,P2 = np.loadtxt(File2, unpack=True)\nX3,Y3,Charge3,P3 = np.loadtxt(File3, unpack=True)\n\nX1 = X1.reshape(128,128)\nY1 = Y1.reshape(128,128)\nP1 = P1.reshape(128,128)\n\nX2 = X2.reshape(128,128)\nY2 = Y2.reshape(128,128)\nP2 = P2.reshape(128,128)\n\nX3 = X3.reshape(128,128)\nY3 = Y3.reshape(128,128)\nP3 = P3.reshape(128,128)\n\n\nx1 = X1[0::5,0::5]\ny1 = Y1[0::5,0::5]\nx2 = X2[0::5,0::5]\ny2 = Y2[0::5,0::5]\nx3 = X3[0::5,0::5]\ny3 = Y3[0::5,0::5]\n\n\n\n# Plots direction of the electrical vector field\ndX1, dY1 = np.gradient( P1 )\ndX2, dY2 = np.gradient( P2 )\ndX3, dY3 = np.gradient( P3 )\n\nfig,ax=plt.subplots(3,2, figsize=(12,18))\n\n\n\ndx1 = dX1[0::5,0::5]\ndy1 = dY1[0::5,0::5]\ndx2 = dX2[0::5,0::5]\ndy2 = dY2[0::5,0::5]\ndx3 = dX3[0::5,0::5]\ndy3 = dY3[0::5,0::5]\n\n\n#ax[0][0].quiver(x1, y1, dx1, dy1, color='r', zorder=1, width=0.007, headwidth=3., headlength=4., units='x')\nax[0][0].quiver(x1, y1, dx1, dy1, color='r')\nax[0][1].contourf(X1, Y1, P1, 100, cmap='RdGy')\n\nax[0][0].set_title(Problem1+\": E lines\")\nax[0][1].set_title(Problem1+\": potential\")\n\nax[0][0].set_xlim(0.0,1.0)\nax[0][0].set_ylim(0.0,1.0)\nax[0][1].set_xlim(0.0,1.0)\nax[0][1].set_ylim(0.0,1.0)\n\n#ax[1][0].quiver(x2, y2, dx2, dy2, color='r', zorder=1, width=0.007, headwidth=3., headlength=4., units='x')\nax[1][0].quiver(x2, y2, dx2, dy2, color='r')\nax[1][1].contourf(X2, Y2, P2, 100, cmap='RdGy')\n\nax[1][0].set_title(Problem2+\": E lines\")\nax[1][1].set_title(Problem2+\": potential\")\n\nax[1][0].set_xlim(0.0,1.0)\nax[1][0].set_ylim(0.0,1.0)\nax[1][1].set_xlim(0.0,1.0)\nax[1][1].set_ylim(0.0,1.0)\n\n\n#ax[2][0].quiver(x3, y3, dx3, dy3, color='r', units='xy', zorder=1, width=0.007, headwidth=3., headlength=4.)\nax[2][0].quiver(x3, y3, dx3, dy3, color='r')\nax[2][1].contourf(X3, Y3, P3, 100, cmap='RdGy')\n\nax[2][0].set_title(Problem3+\": E lines\")\nax[2][1].set_title(Problem3+\": potential\")\n\nax[2][0].set_xlim(0.0,1.0)\nax[2][0].set_ylim(0.0,1.0)\nax[2][1].set_xlim(0.0,1.0)\nax[2][1].set_ylim(0.0,1.0)\n\n\n\n#plt.show()\nplt.savefig('fff.png')\n","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":2326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"571201791","text":"from abc import ABC\nimport pandas as pd\nfrom .base import BaseFactor\nfrom collections import defaultdict\nfrom ccbacktest.utils.pandas_utils import concat_dataframes, concat_series, add_parent_level\n\n\nclass Factor(BaseFactor, ABC):\n \"\"\"\n Base class for all factors, it supports arithmetic operations with a scaler or another factor, creating\n a Lambda Factor (a class to represent factors created from a function)\n \"\"\"\n\n def __init__(self):\n self.name = None\n self._history = None\n self._periods = None\n\n def rename(self, name):\n \"\"\"\n Rename the factor to another name\n :arg name: the new name for the factor\"\"\"\n # TODO : raise Exception when the factor has already been applied to a dataset (renaming it would\n # result in creating two different pandas columns with different names)\n self.name = name\n return self\n\n @property\n def history(self) -> dict:\n \"\"\"\n :return: return the relevant history for the factor in order for it to compute futur values of the factor,\n it's sentinel value is None\n \"\"\"\n if not hasattr(self, '_history'):\n self._history = None\n return self._history\n\n @history.setter\n def history(self, d):\n self._history = d\n\n @property\n def periods(self):\n \"\"\" returns the number of periods necessary to compute next value\n \"\"\"\n return self._periods\n\n @periods.setter\n def periods(self, value):\n self._periods = value\n\n def update_history(self, series, new_value):\n \"\"\" Update the history when a new value is computed,\n :arg series: the new observation (ohlcv current value if ohlcv is used)\n :arg new_value: new computed factor value\n \"\"\"\n\n self.history['data_history'] = self.history['data_history'].append(series).iloc[1:]\n self.history['factor_history'] = self.history['factor_history'].append(new_value).iloc[1:]\n\n def apply(self, df: pd.DataFrame) -> pd.DataFrame:\n \"\"\" apply the factor to a historical dataset at once\n :arg df: historical data to which we apply the factor\n :return factor values for each timestamp\n \"\"\"\n\n values = self.func(df)\n if self.periods is not None:\n self.history = {\"data_history\": df.iloc[-self.periods:],\n 'factor_history': values.iloc[-self.periods:]}\n if not isinstance(values, pd.DataFrame):\n values = values.rename(self.name).to_frame()\n return values\n\n def step(self, series: pd.Series) -> pd.Series:\n \"\"\" compute the factor value for the next timestamp\n :arg series: new observation\n :return computed factor value for the observation\n \"\"\"\n\n df = self.history['data_history']\n updated = df.append(series)\n value = self.func(updated).iat[-1]\n to_return = pd.Series([value], name=series.name, index=[self.name])\n self.update_history(series, to_return)\n return series\n\n def __add__(self, other):\n if isinstance(other, Factor):\n # compute a default name for the su factor\n name = f'({self.name} + {other.name})'\n # the necessary history is the max of both histories\n # TODO: raise exception if the two factors have different timeframes\n periods = max(self.periods, other.periods)\n\n def func(df):\n return self.func(df) + other.func(df)\n\n return LambdaFactor(func, name, periods)\n elif isinstance(other, int) or isinstance(other, float):\n name = f\"({self.name} + {other})\"\n periods = self.periods\n\n def func(df):\n return other + self.func(df)\n\n return LambdaFactor(func, name, periods)\n else:\n raise TypeError(f\"Type {type(other)} not supported\")\n\n def __radd__(self, other):\n if isinstance(other, Factor):\n return other.__add__(self)\n elif isinstance(other, int) or isinstance(other, float):\n name = f\"({other} + {self.name})\"\n\n def func(df):\n return other + self.func(df)\n\n return LambdaFactor(func, name, self.periods)\n else:\n raise TypeError(f\"Type {type(other)} not supported\")\n\n def __sub__(self, other):\n if isinstance(other, Factor):\n name = f'({self.name} - {other.name})'\n periods = max(self.periods, other.periods)\n\n def func(df):\n return self.func(df) - other.func(df)\n\n return LambdaFactor(func, name, periods)\n elif isinstance(other, int) or isinstance(other, float):\n name = f\"({self.name} - {other})\"\n\n def func(df):\n return self.func(df) - other\n\n return LambdaFactor(func, name, self.periods)\n else:\n raise TypeError(f\"Type {type(other)} not supported\")\n\n def __rsub__(self, other):\n\n if isinstance(other, int) or isinstance(other, float):\n name = f\"({other} - {self.name})\"\n\n def func(df):\n return other - self.func(df)\n\n return LambdaFactor(func, name, self.periods)\n else:\n raise TypeError(f\"Type {type(other)} not supported\")\n\n def __mul__(self, other):\n if isinstance(other, Factor):\n name = f'({self.name} x {other.name})'\n\n def func(df):\n return self.func(df) * other.func(df)\n\n return LambdaFactor(func, name, max(self.periods, other.periods))\n elif isinstance(other, int) or isinstance(other, float):\n name = f\"({self.name} x {other})\"\n\n def func(df):\n return other * self.func(df)\n\n return LambdaFactor(func, name, self.periods)\n else:\n raise TypeError(f\"Type {type(other)} not supported\")\n\n def __rmul__(self, other):\n if isinstance(other, Factor):\n name = f'({other.name} x {self.name})'\n\n def func(df):\n return self.func(df) * other.func(df)\n\n return LambdaFactor(func, name, max(self.periods, other.periods))\n elif isinstance(other, int) or isinstance(other, float):\n name = f\"({other} + {self.name})\"\n\n def func(df):\n return other * self.func(df)\n\n return LambdaFactor(func, name, self.periods)\n else:\n raise TypeError(f\"Type {type(other)} not supported\")\n\n def __truediv__(self, other):\n if isinstance(other, Factor):\n name = f'({self.name} / {other.name})'\n\n def func(df):\n return self.func(df) / other.func(df)\n\n return LambdaFactor(func, name, max(self.periods, other.periods))\n elif isinstance(other, int) or isinstance(other, float):\n name = f\"({self.name} / {other})\"\n\n def func(df):\n return self.func(df) / other\n\n return LambdaFactor(func, name, self.periods)\n else:\n raise TypeError(f\"Type {type(other)} not supported\")\n\n def __rtruediv__(self, other):\n if isinstance(other, Factor):\n name = f'({other.name} / {self.name})'\n\n def func(df):\n return other.func(df) / self.func(df)\n\n return LambdaFactor(func, name, max(self.periods, other.periods))\n elif isinstance(other, int) or isinstance(other, float):\n name = f\"({other} / {self.name})\"\n\n def func(df):\n return other / self.func(df)\n\n return LambdaFactor(func, name, self.periods)\n else:\n raise TypeError(f\"Type {type(other)} not supported\")\n\n\nclass LambdaFactor(Factor):\n __slots__ = ['name', '_func']\n \"\"\" A class used to create a factor from a function, a history depth and a name, the \n rest of the factor operation is inherited from the Factor class, it's used mainly to create arithmetic operations\n between other factors. \n \"\"\"\n def __init__(self, func, name, periods):\n super(Factor, self).__init__()\n self.name = name\n self._func = func\n self.periods = periods\n\n def func(self, df):\n return self._func(df)\n\n\nclass MovingAverage(Factor):\n __slots__ = ['periods', '_on', 'name', '_history']\n \"\"\" Moving averge on price data\n \"\"\"\n def __init__(self, periods, on=\"close\"):\n assert isinstance(periods, int), \"Periods parameter should be an integer\"\n assert (on in ['close', 'open']), 'Only open and close are supported'\n super(Factor, self).__init__()\n self.periods = periods\n self._on = on\n self._history = None\n self.name = f'MA_{self.periods}'\n\n def func(self, df):\n return df.rolling(self.periods)[self._on].mean()\n\n def step(self, series: pd.Series):\n df = self.history['data_history']\n factor = self.history['factor_history']\n s = factor.iat[-1]\n r = df[self._on].iat[-self.periods]\n value = (self.periods * s - r + series[self._on]) / self.periods\n to_return = pd.Series([value], index=[self.name], name=series.name)\n self.update_history(series, to_return)\n return to_return\n\n\nclass RelativeStrengthIndex(Factor):\n def __init__(self, periods=14):\n self.periods = periods\n self.name = f'RSI_{periods}'\n super(Factor, self).__init__()\n\n def func(self, df):\n if df.shape[0] <= self.periods:\n raise TooSmallHistoryError('History data frame is too small to compute the moving average with '\n f'{self.periods} periods, on {df.shape[0]} time steps')\n diff = df.close - df.open\n pos = diff >= 0\n pos_mean = diff.where(pos, 0).rolling(self.periods).mean()\n neg_mean = -diff.where(~pos, 0).rolling(self.periods).mean()\n factor = (100 - (100 / (1 + (pos_mean / neg_mean)).abs()))\n return factor\n\n\nclass VolumeWeightedAveragePrice(Factor):\n def __init__(self, periods):\n super(Factor, self).__init__()\n self.periods = periods\n self.name = f'VWAP_{self.periods}'\n\n def func(self, df: pd.DataFrame) -> pd.Series:\n product = df['open'] * df['volume']\n product_sum = product.rolling(self.periods).sum()\n vol_sum = df['volume'].rolling(self.periods).sum()\n return product_sum / vol_sum\n\n\nclass MovingAverageConvergenceDivergence(Factor):\n def __init__(self, fast_period, slow_period, on='close'):\n self.fast_period = fast_period\n self.slow_period = slow_period\n self.periods = self.slow_period\n self._on = on\n self.name = f'MACD_{fast_period}_{slow_period}'\n\n def func(self, df):\n fast_series = df.rolling(self.fast_period)[self._on].mean().rename('fast')\n slow_series = df.rolling(self.slow_period)[self._on].mean().rename('slow')\n return_df = pd.concat([fast_series, slow_series], axis=1)\n return_df.columns = pd.MultiIndex.from_product([[self.name], return_df.columns])\n return return_df\n\n def step(self, series: pd.Series) -> pd.Series:\n df = self.history['data_history']\n updated = df.append(series)\n value = self.func(updated).iloc[-1, :]\n self.update_history(series, value)\n return value\n\n def update_history(self, series, new_value):\n self.history['data_history'] = self.history['data_history'].append(series).iloc[1:]\n self.history['factor_history'] = self.history['factor_history'].append(new_value).iloc[1:]\n\n\nMACD = MovingAverageConvergenceDivergence\nMA = MovingAverage\nRSI = RelativeStrengthIndex\nVWAP = VolumeWeightedAveragePrice\n\n\nclass TooSmallHistoryError(Exception):\n pass\n","sub_path":"build/lib/ccbacktest/factors/factors.py","file_name":"factors.py","file_ext":"py","file_size_in_byte":11780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"404702767","text":"#\n# @lc app=leetcode id=92 lang=python3\n#\n# [92] Reverse Linked List II\n#\n# https://leetcode.com/problems/reverse-linked-list-ii/description/\n#\n# algorithms\n# Medium (37.74%)\n# Total Accepted: 253.8K\n# Total Submissions: 671.8K\n# Testcase Example: '[1,2,3,4,5]\\n2\\n4'\n#\n# Reverse a linked list from position m to n. Do it in one-pass.\n# \n# Note: 1 ≤ m ≤ n ≤ length of list.\n# \n# Example:\n# \n# \n# Input: 1->2->3->4->5->NULL, m = 2, n = 4\n# Output: 1->4->3->2->5->NULL\n# \n# \n#\n# Definition for singly-linked list.\n\n\nclass ListNode:\n # https://zhuanlan.zhihu.com/p/86745433?utm_source=\n\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution:\n def __init__(self):\n self.successor = None\n\n def reverseN(self, head, n):\n \"\"\"\n 反转链表的前n个节点\n \"\"\"\n if n == 1:\n self.successor = head.next\n return head\n\n last = head.next\n new_head = self.reverseN(head.next, n - 1)\n last.next = head\n head.next = self.successor\n\n return new_head\n\n def reverseBetween(self, head, m, n):\n \"\"\"\n 递归,代码简洁\n 时间复杂度:o(n)\n 空间复杂度:o(n)\n \"\"\"\n if m == 1:\n return self.reverseN(head, n)\n head.next = self.reverseBetween(head.next, m - 1, n - 1)\n return head\n\n # def reverseBetween(self, head, m, n):\n # dummy = ListNode(-1)\n # dummy.next = head\n # pre = dummy\n # # 找到翻转链表部分的前一个节点, 1->2->3->4->5->NULL, m = 2, n = 4 指的是 节点值为1\n # for _ in range(m - 1):\n # pre = pre.next\n # # 用双指针,进行链表翻转(原地翻转)\n # node = None # 翻转后链表的表头\n # cur = pre.next # 链表前进的指针\n # for _ in range(n - m + 1):\n # tmp = cur.next # 把下一个结点先保存起来\n # cur.next = node\n # node = cur\n # cur = tmp # cur指针继续前进\n # # 将翻转部分 和 原链表拼接\n # pre.next.next = cur\n # pre.next = node\n # return dummy.next\n\n\nif __name__ == '__main__':\n head = ListNode(None) # head指针指向链表表头\n pos = head\n for i in [1, 2, 3, 4, 5, 6]:\n node = ListNode(i)\n pos.next = node # 链表插入结点\n pos = pos.next # pos指针向前移动\n\n s = Solution()\n result = s.reverseBetween(head.next, 2, 4)\n while result:\n print(result.val)\n result = result.next\n","sub_path":"linked_list/recursively/92.reverse-linked-list-ii.py","file_name":"92.reverse-linked-list-ii.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"268080786","text":"import numpy as np\n\nclass DecisionTree:\n\n def __init__(self, labels, mode, prune_thr):\n np.set_printoptions(threshold = np.inf, suppress = True)\n self.class_labels = np.unique(labels)\n self.num_labels = len(self.class_labels)\n self.mode = mode\n self.prune_thr = prune_thr\n\n\n # Nodes used for the tree returned\n class TreeNode:\n # attr is the index of a row in data\n # thresh is the value to split on\n # less than goes left\n # greater than or equal to goes right\n def __init__(self, attr, thresh, node_id, gain = 0.0, dist = None):\n self.id = node_id\n self.attr = attr\n self.thresh = thresh\n self.distr = dist\n self.gain = gain\n self.left = None\n self.right = None\n\n #\n # end TreeNode class\n #\n\n # default is a distribution over the labels\n # returns a TreeNode\n def dtl(self, ex, labels, default, node_id) -> TreeNode:\n if len(ex) < self.prune_thr:\n newNode = self.TreeNode(-1, -1, node_id, dist = default)\n return newNode\n\n if len(np.unique(labels)) == 1:\n dist = self.distribution(labels)\n newNode = self.TreeNode(-1, -1, node_id, dist = dist)\n return newNode\n\n if self.mode == 'optimized':\n thresh, attr, gain = self.choose_optimized(ex, labels)\n else:\n thresh, attr, gain = self.choose_random(ex, labels)\n\n root = self.TreeNode(attr, thresh, node_id, gain = gain)\n\n left_cond = np.where(ex[:,attr] < thresh)\n right_cond = np.where(ex[:,attr] >= thresh)\n\n new_default = self.distribution(labels)\n\n root.left = self.dtl(ex[left_cond], labels[left_cond], new_default, 2 * node_id)\n root.right = self.dtl(ex[right_cond], labels[right_cond], new_default, 2 * node_id + 1)\n \n return root\n\n\n def choose_random(self, ex, labels):\n max_gain = -1\n best_thresh = -1\n\n random_attr = np.random.randint(len(ex[0]))\n l = np.amin(ex[:,random_attr])\n m = np.amax(ex[:,random_attr])\n for i in range(1, 51):\n thresh = l + i * (m - l) / 51\n gain = self.information_gain(ex, labels, random_attr, thresh)\n\n if gain > max_gain:\n max_gain = gain\n best_thresh = thresh\n\n return best_thresh, random_attr, max_gain\n\n\n def choose_optimized(self, ex, labels):\n max_gain = -1\n best_attr = -1\n best_thresh = -1\n\n for i in range(0, len(ex[0])):\n l = np.amin(ex[:,i])\n m = np.amax(ex[:,i])\n \n for k in range(1, 51):\n thresh = l + k * (m - l) / 51\n gain = self.information_gain(ex, labels, i, thresh)\n \n if gain > max_gain:\n max_gain = gain\n best_thresh = thresh\n best_attr = i\n\n return best_thresh, best_attr, max_gain\n\n\n # attr is an index of the attribute \n def information_gain(self, ex, labels, attr, thresh):\n parent_entropy = self.entropy(labels)\n\n left_labels = labels[np.where(ex[:,attr] < thresh)]\n right_labels = labels[np.where(ex[:,attr] >= thresh)]\n left_entropy = self.entropy(left_labels)\n right_entropy = self.entropy(right_labels)\n\n info_gain = parent_entropy - (\n len(left_labels) * left_entropy / len(labels) +\n len(right_labels) * right_entropy / len(labels)\n )\n return info_gain\n\n\n def entropy(self, labels):\n k = len(labels)\n uniq, counts = np.unique(labels, return_counts = True)\n interim = np.multiply(np.divide(counts, k), np.log2(np.divide(counts, k)))\n entropy = np.negative(np.sum(interim))\n return entropy\n\n\n def distribution(self, labels):\n k = len(labels)\n uniq, counts = np.unique(labels, return_counts = True)\n distr = np.zeros(self.num_labels)\n for i in range(0, len(uniq)):\n index = np.argwhere(self.class_labels == uniq[i])\n distr[index] = counts[i]\n \n return np.divide(distr, k)\n\n\n def test(self, tree, test_data):\n while tree.attr != -1:\n if test_data[tree.attr] < tree.thresh:\n tree = tree.left\n else:\n tree = tree.right\n return tree.distr\n","sub_path":"fall2018/4309/hw4/dectree.py","file_name":"dectree.py","file_ext":"py","file_size_in_byte":4493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"378064004","text":"import cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\n# from skimage import data\n# from skimage.morphology import skeletonize, thin\n# from skimage.util import invert \nfrom mpl_toolkits.mplot3d import Axes3D\n\ndef find_color(img,x,y):\n\treturn img[y,x]\n\ndef find_gradient(img,x,y):\n\treturn 255 - img[y,x]\n\ndef remove_duplicates(x):\n return list(dict.fromkeys(x))\n\ndef find_middle(x1, y1, x2, y2):\n\tif x1 >= x2:\n\t\tmax_x = x1\n\t\tmin_x = x2\n\telse:\n\t\tmax_x = x2\n\t\tmin_x = x1\n\n\tif y1 >= y2:\n\t\tmax_y = y1\n\t\tmin_y = y2\n\telse:\n\t\tmax_y = y2\n\t\tmin_y = y1\n\txx = int(min_x + ((max_x-min_x)/2))\n\tyy = int(min_y + ((max_y-min_y)/2))\n\treturn (xx,yy)\n\ndef top_to_bot(list_is):\n ans = list_is[1:len(list_is)]\n ans.append(list_is[0])\n return ans\n\t\ndef find_num_point(x1,y1,x2,y2):\n if abs( x1 - x2 ) >= abs( y1 - y2 ):\n return int(abs( x1 - x2 ))\n else:\n return int(abs( y1 - y2 ))\n\ndef sampling(x1,y1,x2,y2):\n dx = x2-x1\n dy = y2-y1\n if abs( x1 - x2 ) >= abs( y1 - y2 ):\n n = int(abs( x1 - x2 ) /2)\n else:\n n = int(abs( y1 - y2 ) /2)\n dxn = dx/n\n dyn = dy/n \n output = []\n for i in range(n):\n output.append((int(x1+(i*dxn)),int(y1+(i*dyn))))\n return output\n\nimage = cv2.imread(r'C:\\Users\\aminb\\Desktop\\FIBO\\Image\\Moduel_image\\test_field.jpg')\nimage1 = cv2.imread(r'C:\\Users\\aminb\\Desktop\\FIBO\\Image\\Moduel_image\\test_field.jpg')\npop = image.copy()\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\nblur = cv2.GaussianBlur(gray, (5,5), 0)\n# blur = cv2.GaussianBlur(gray, (101,101), -10)\n# blur = cv2.threshold(blur1,0,255,cv2.THRESH_BINARY)\n# highboost = cv2.subtract(blur,gray)\n# cv2.imshow(\"Contour\", highboost)\n# cv2.waitKey(0)\n# black_image = np.zeros((738, 778, 1),np.uint8)\n# black_image = np.zeros((image1.shape[0], image1.shape[1], 1), np.uint8)\n\n# Find Canny edges \nedge = cv2.Canny(blur,40,100) \n\n# bi = cv2.cvtColor(edge,cv2.THRESH_BINARY)\nkernel = np.ones((3,3))\n# closing = cv2.dilate(edge,kernel,iterations = 1)\ndilation = cv2.dilate(edge,kernel,iterations = 1)\nclosing = cv2.morphologyEx(dilation, cv2.MORPH_CLOSE, kernel)\ncontours, hierarchy = cv2.findContours(closing , cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) \n# cv2.imshow(\"Contour\",closing)\n# cv2.waitKey(0)\n\n# cv2.drawContours(image,contours, -1, (0, 0, 255), 3)\n\n# filled_contour = cv2.fillPoly(black_image, conc, color=(255,255,255))\n# ret3,filled_contour_binary = cv2.threshold(filled_contour,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n\nprint(\"Number of Contours found = \" + str(len(contours))) \n# cv2.imshow('thresh', filled_contour_binary )\n# cv2.waitKey(0)\n# Draw all contours \n# -1 signifies drawing all contours\n\nlist_all_point_path = []\nlist_contours_symbol = []\nlist_contours_box_symbol_inside = []\nlist_contours_path = []\n# cv2.approxPolyDP()\nfor i in hierarchy.tolist()[0]: #ADD list_contours\n\tParent_check = (i[3] == 0) # check in case\n\tChild_check_symbol = (i[2] != -1) # Symbol\n\tChild_check_path = (i[2] == -1) # PATH\n\tif Parent_check:\n\t\tif Child_check_symbol:\n\t\t\tlist_contours_box_symbol_inside.append(hierarchy.tolist()[0].index(i))\n\t\tif Child_check_path:\n\t\t\tlist_contours_path.append(hierarchy.tolist()[0].index(i))\n\t\nfor j in list_contours_box_symbol_inside:\n\tcont = 20\n\tlist_x = []\n\tlist_y = []\n\tfor i in contours[j]:\n\t\tlist_x.append(i.tolist()[0][0])\n\t\tlist_y.append(i.tolist()[0][1])\n\tdiff_x = int((max(list_x)-min(list_x))/2)\n\tdiff_y = int((max(list_y)-min(list_y))/2)\n\tX = int(min(list_x) + diff_x)\n\tY = int(min(list_y) + diff_y)\n\tconst_x = diff_x + cont\n\tconst_y = diff_y + cont\n\t\n\t# cv2.circle(image,(center_x,center_y), 3, (0,0,255), -1)\n\toffset_right = X + const_x\n\toffset_left = X - const_x\n\toffset_up = Y + const_y\n\toffset_down = Y - const_y\n\n\tif find_color( gray,offset_right,Y) != 255:\n\t\tfor i in sampling(*(X,Y),*(offset_right , Y)):\n\t\t\tcv2.circle(image,i,2,(0,0,255),-1)\n\t\t\tlist_all_point_path.append(i+(128,))\n\t\t# cv2.line(image,(center_x,center_y),(center_x + cont_x , center_y),(0,0,255),3)\n\n\tif find_color(\tgray,offset_left,Y) != 255:\n\t\tfor i in sampling(*(X,Y),*(offset_left , Y)):\n\t\t\tcv2.circle(image,i,2,(0,0,255),-1)\n\t\t\tlist_all_point_path.append(i+(128,))\n\t\t# cv2.line(image,(center_x,center_y),(center_x - cont_x , center_y),(0,0,255),3)\n\n\tif find_color(\tgray,\tX,\toffset_up) != 255:\n\t\tfor i in sampling(*(X,Y),*(X , offset_up)):\n\t\t\tcv2.circle(image,i,2,(0,0,255),-1)\n\t\t\tlist_all_point_path.append(i+(128,))\n\t\t\t\n\t\t# cv2.line(image,(center_x,center_y),(center_x , center_y + cont_y),(0,0,255),3)\n\n\tif find_color(\tgray,\tX,\toffset_down) != 255:\n\t\tfor i in sampling(*(X,Y),*(X , offset_down)):\n\t\t\tcv2.circle(image,i,2,(0,0,255),-1)\n\t\t\tlist_all_point_path.append(i+(128,))\n\t\t# cv2.line(image,(center_x,center_y),(center_x , center_y - cont_y),(0,0,255),3)\n\t\n\t# cv2.circle(image,Centor, 3, (0,0,255), -1)\n\t\n\nprint(list_contours_box_symbol_inside)\n# print(list_contours_symbol)\n# print(list_contours_path)\nfor k in list_contours_path:\n\tepsilon = 0.003 * cv2.arcLength(contours[k], True)\n\tapprox = cv2.approxPolyDP(contours[k], epsilon, True)\n\tlist_approx = []\n\tfor j in approx.tolist():\n\t\tlist_approx.append(j[0])\n\t\n\tif len(list_approx) >= 7:\n\t\ta = 0\n\t\tb = -1\n\t\tlist_line = []\n\t\tfor _ in range(int(len(list_approx)/2)):\n\t\t\tpoint_xy_midle = find_middle(*tuple(list_approx[a]), *tuple(list_approx[b]))\n\t\t\t# cv2.circle(image, point_xy_midle , 3, (0, 255, 0), -1)\n\t\t\tlist_line.append(point_xy_midle)\n\t\t\ta += 1\n\t\t\tb -= 1\n\t\tfor i in range(1,len(list_line)):\n\t\t\tfor j in sampling(*list_line[i-1],*list_line[i]):\n\t\t\t\tcv2.circle(image,j,2,(0,0,255),-1)\n\t\t\t\tlist_all_point_path.append(j+(find_gradient(gray,*j),))\n\t\n\telse:\n\t\tlist_approx = top_to_bot(list_approx)\n\t\ta = 0\n\t\tb = -1\n\t\tlist_line = []\n\t\tfor _ in range(int(len(list_approx)/2)):\n\t\t\tpoint_xy_midle = find_middle(*tuple(list_approx[a]), *tuple(list_approx[b]))\n\t\t\t# cv2.circle(image, point_xy_midle , 3, (0, 255, 0), -1)\n\t\t\tlist_line.append(point_xy_midle)\n\t\t\ta += 1\n\t\t\tb -= 1\n\t\t\n\t\tfor i in range(1,len(list_line)):\n\t\t\tfor j in sampling(*list_line[i-1],*list_line[i]):\n\t\t\t\tcv2.circle(image,j,2,(0,0,255),-1)\n\t\t\t\tlist_all_point_path.append(j+(find_gradient(gray,*j),))\n\n\n# cv2.imshow(\"kkkk\",image) \n# cv2.waitKey(0)\n\n\n# skeleton = skeletonize(filled_contour)\n# cv2.imshow('skeleton',skeleton)\n# cv2.waitKey(0)\n# skeleton_lee = skeletonize(filled_contour, method='lee')\n# cv2.imshow('skeleton_lee', skeleton_lee)\n# cv2.waitKey(0)\n\n# thinned = thin(filled_contour_binary)\n# cv2.imwrite(\"000.png\",filled_contour_binary)\n# # display results\n\n\n# fig, axes = plt.subplots(2, 2, figsize=(8, 8), sharex=True, sharey=True)\n# ax = axes.ravel()\n\n# ax[0].imshow(thinned, cmap=plt.cm.gray)\n# ax[0].set_title('thinned')\n# ax[0].axis('off')\n\n# ax[1].imshow(skeleton_lee, cmap=plt.cm.gray)\n# ax[1].axis('off')\n# ax[1].set_title('skeleton_lee', fontsize=20)\n\n# ax[2].imshow(skeleton, cmap=plt.cm.gray)\n# ax[2].axis('off')\n# ax[2].set_title('skeleton', fontsize=20)\n\n\n# fig.tight_layout()\n# plt.show()\n\n# f = open(\"pointcloud.txt\", \"w\")\n# f.write(repr(list_all_point_path))\n# f.close()\n\n# fig = plt.figure()\n# ax = fig.add_subplot(111, projection='3d')\n# for i in list_all_point_path:\n# ax.scatter(i[1],i[0],i[2])\n# plt.show()\n# cv2.waitKey(0)\n\n# print(list_contours_box_symbol_inside)\nfrom math import copysign, log10\nfor j in list_contours_box_symbol_inside:\n\t# cv2.drawContours(pop,contours,i,(255,0,0),2)\n\tcont = 0\n\tlist_x = []\n\tlist_y = []\n\tfor i in contours[j]:\n\t\tlist_x.append(i.tolist()[0][0])\n\t\tlist_y.append(i.tolist()[0][1])\n\tdiff_x = int((max(list_x)-min(list_x))/2)\n\tdiff_y = int((max(list_y)-min(list_y))/2)\n\tX = int(min(list_x) + diff_x)\n\tY = int(min(list_y) + diff_y)\n\tconst_x = diff_x + cont\n\tconst_y = diff_y + cont\n\toffset_right = X + const_x\n\toffset_left = X - const_x\n\toffset_up = Y + const_y\n\toffset_down = Y - const_y\n\tim = cv2.cvtColor(pop[offset_down:offset_up,offset_left:offset_right], cv2.COLOR_BGR2GRAY)\n\tcv2.imwrite(str(offset_down)+\".png\",pop[offset_down:offset_up,offset_left:offset_right])\n\t# cv2.imshow(\"222kkkk\",pop[offset_down:offset_up,offset_left:offset_right]) \n\t# cv2.waitKey(0)\n\t_,im = cv2.threshold(im, 128, 255, cv2.THRESH_BINARY)\n\tmoments = cv2.moments(im)\n\thuMoments = cv2.HuMoments(moments)\n\tfor q in range(0,7):\n\t\thuMoments[q] = (-1* copysign(1.0, huMoments[q]) * log10(abs(huMoments[q])))\n\tprint(huMoments)\n\tcv2.imshow(\"kkkk\",pop[offset_down:offset_up,offset_left:offset_right]) \n\tcv2.waitKey(0)\n\ncv2.destroyAllWindows() \n\n\n\n\n","sub_path":"Old_Version/Flush_Image/Detect_edge/Useful.py","file_name":"Useful.py","file_ext":"py","file_size_in_byte":8376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"375635626","text":"#!/usr/bin/env python3\n\nimport math\nimport random\n\nSMALL_NUMBER_LIMIT = pow(2,24)\n\ndef small_units(n):\n return [x for x in range(1, min(SMALL_NUMBER_LIMIT, n-1)) if math.gcd(x,n) == 1]\n\ndef multiply_mod(a, b, mod):\n result = 0\n a %= mod\n b %= mod\n while a > 0:\n if a%2 == 1:\n result = (b + result) % mod\n b = (2 * b) % mod\n a = a//2\n return result\n\n\ndef xgcd(a,b):\n prevx, x = 1, 0; prevy, y = 0, 1\n while b:\n q = a//b\n x, prevx = prevx - q*x, x\n y, prevy = prevy - q*y, y\n a, b = b, a % b\n return a, prevx, prevy\n \ndef modinv(a, n):\n factor, a, b = xgcd(a, n)\n if factor == 1:\n return a\n return None\n\n# doesn't catch carmichaels\ndef fermat_test(p):\n return pow(2, p-1, p) == 1 and pow(3, p-1, p) == 1\n\n# next fermat pseudoprime/prime\ndef next_fermat(n):\n while not fermat_test(n):\n n += 1\n return n\n\ndef small_factor(n):\n for x in range(2, min(SMALL_NUMBER_LIMIT, round(math.sqrt(n) + 1))):\n # print(n, x)\n if n%x == 0:\n result = small_factor(n//x)\n result.insert(0, x)\n return result\n return [n]\n\nprint(small_factor(277777788888899))\n\n# use a random walk multiplying by fibonacci powers a^1 a^2 a^3 a^5 to try to find a a^x = a^y collision. \ndef search_unit_order(elem, n, accumulator = None, recurrence = lambda x, n, a: (2*x + 1) % n**2, limit = pow(2,19)):\n # map of exponent expression, to values.\n seen = {}\n a = 1\n test_count = 0\n for i in range(2, limit):\n test_count += 1\n a, accumulator = recurrence(a, n, accumulator)\n if a in seen or a == 0:\n continue\n value = pow(elem, a, n)\n seen[a] = value\n #if random.random() < 0.0001:\n #print(\" testing %s ^ %s\" % (elem, a))\n if value == 1:\n return a, test_count\n if value in seen:\n old_a = seen[value]\n #print(\"%s^%s = %s^%s\" % (elem, a, elem, old_a))\n return abs(a - old_a), test_count\n \"\"\"\n \"\"\"\n return None, test_count\n\n\ndef main():\n digits = 16 \n #TODO a better prime test that excludes carmichaels.\n p = next_fermat(pow(2,digits//2 + 1))\n q = next_fermat(pow(2,digits//2 - 2))\n n = p * q\n print(\"p, q, n: \", p, q, n)\n print(\"totient(n) = %s * %s = %s\" % (p-1, q-1, (p-1)*(q-1)))\n\n\n tests = range(2,30)\n # TODO are there easy ways to determine whether two elements have the same order, without actually finding that value?\n recurrences = [\n lambda a, n, accumulator: ((2 * a + 1) % (n), None),\n lambda a, n, accumulator: ((3 * a + 1) % (n*n), None),\n lambda a, n, accumulator: ((2 * a + 1), None),\n ]\n\n for recurrence in recurrences:\n search_steps = []\n order_multiples = []\n for elem in tests:\n result, test_count = search_unit_order(elem, n, recurrence=recurrence)\n search_steps.append(test_count)\n order_multiples.append(result)\n #print('|%s| mod %s divides %s'% (elem, n, result))\n #print(' tests: %s' % (test_count,))\n print()\n print('search steps', search_steps)\n print('order multiples', order_multiples)\n\nif __name__ == \"__main__\":\n main()\n\n\"\"\"\nprint(small_units(pow(2,100))[-1])\nprint(modinv(2039, 2**100))\n#print(units(100))\n#print(xgcd(29, 35))\nn = 2390204820439820942390482390\n#n = 1012300\nl = factor(n)\nprint(l)\nresult = 1\nfor x in l:\n result *= x\nprint(result)\n\"\"\"\n\n","sub_path":"semiprimes.py","file_name":"semiprimes.py","file_ext":"py","file_size_in_byte":3527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"452385552","text":"#! /usr/bin/python\n\n# Copyright 2019 Extreme Networks, 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\nimport errno\nimport subprocess\nimport random\nimport re\n\nfrom st2common.runners.base_action import Action\n\n\nclass DigAction(Action):\n\n def run(self, rand, count, nameserver, hostname, queryopts):\n opt_list = []\n output = []\n\n cmd_args = ['dig']\n if nameserver:\n nameserver = '@' + nameserver\n cmd_args.append(nameserver)\n\n if re.search(',', queryopts):\n opt_list = queryopts.split(',')\n else:\n opt_list.append(queryopts)\n for k, v in enumerate(opt_list):\n cmd_args.append('+' + v)\n\n cmd_args.append(hostname)\n\n try:\n result_list = filter(None, subprocess.Popen(cmd_args,\n stderr=subprocess.PIPE,\n stdout=subprocess.PIPE)\n .communicate()[0]\n .split('\\n'))\n\n # NOTE: Python3 supports the FileNotFoundError, the errono.ENOENT is for py2 compat\n # for Python3:\n # except FileNotFoundError as e:\n\n except OSError as e:\n if e.errno == errno.ENOENT:\n return False, \"Can't find dig installed in the path (usually /usr/bin/dig). If \" \\\n \"dig isn't installed, you can install it with 'sudo yum install \" \\\n \"bind-utils' or 'sudo apt install dnsutils'\"\n else:\n raise e\n\n if int(count) > len(result_list) or count <= 0:\n count = len(result_list)\n\n output = result_list[0:count]\n if rand is True:\n random.shuffle(output)\n return output\n","sub_path":"contrib/linux/actions/dig.py","file_name":"dig.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"516362745","text":"import matplotlib\nmatplotlib.use('Agg')\n\nimport coreapi\nimport numpy as np\nimport astropy\nimport astropy.table as at\nimport sys\nimport matplotlib.pyplot as plt\nimport os\nimport csv\nfrom jumpssh import SSHSession\nimport sqlite3\nfrom datetime import datetime as dt\nimport requests, re\nimport texas\nfrom astropy.io import ascii\nfrom config import lc_cfg\nfrom astropy.time import Time\nfrom candidate_generator import Save_space\n\ndef tess_obs(ra, dec):\n\n tess_date = lc_cfg['tess_date']\n\n url = 'https://heasarc.gsfc.nasa.gov/cgi-bin/tess/webtess/'\n url += 'wtv.py?Entry={ra}%2C{dec}'\n r = requests.get(url.format(ra=str(ra), dec=str(dec)))\n if r.status_code!=200:\n print('status message:',r.text)\n error = 'ERROR: could not get {url}, status code {code}'\n raise RuntimeError(error.format(url=url, code=r.status_code))\n return(None)\n\n reg = r\"observed in camera \\w+.\\nSector \\w+\"\n info = re.findall(reg, r.content.decode())\n sectors=[]\n for k in info:\n sectors.append(int(re.split(r'\\s', k)[5])-1)\n \n time = []\n if len(sectors)>0:\n for sector in sectors:\n time.append([tess_date[int(sector)-1], tess_date[int(sector)]])\n \n return(time)\n\n\ndef to_array(somelist, column, start = 1):\n array_raw = np.asarray(somelist[start:])[:,column]\n array = [float(i) for i in array_raw]\n return array\n\ndef search_atlas(ra, dec):\n atlas_info = lc_cfg['atlas_info']\n gateway_session1 = SSHSession(atlas_info[0]['address'],atlas_info[0]['username'], password=atlas_info[0]['password']).open()\n if len(atlas_info)==3:\n gateway_session2 = gateway_session1.get_remote_session(atlas_info[1]['address'],atlas_info[1]['username'], password=atlas_info[2]['password'])\n remote_session = gateway_session2.get_remote_session(atlas_info[2]['address'], password=atlas_info[2]['password'])\n elif len(atlas_info)==2:\n remote_session = gateway_session1.get_remote_session(atlas_info[1]['address'], password=atlas_info[1]['password'])\n else: \n print('wrong format for atlas_params: too many jump connection')\n\n today = dt.today()\n con = sqlite3.connect(\":memory:\")\n tdate = ' '+str(list(con.execute(\"select julianday('\"+today.strftime(\"%Y-%m-%d\")+\"')\"))[0][0]-lc_cfg['lookback_days']-2400000)\n\n result=remote_session.get_cmd_output('./mod_force.sh '+str(ra)+' '+ str(dec)+tdate)\n\n atlas_lc = at.Table(names=('jd','mag', 'mag_err','flux', 'fluxerr', 'filter','maj', 'min', 'apfit', 'sky', 'zp', 'zpsys'), dtype=('f8', 'f8', 'f8', 'f8', 'f8', 'S1' , 'f8', 'f8', 'f8', 'f8','f8', 'U8'))\n\n split = result.split('\\r\\n')\n\n for i in split[1:]:\n k = i.split()\n# if int(k[3])>int(k[4]):\n atlas_lc.add_row([float(k[0]), float(k[1]), float(k[2]), float(k[3]), float(k[4]), k[5], float(k[12]), float(k[13]), float(k[15]), float(k[16]), float(k[17]), 'ab'])\n\n return atlas_lc\n\n\ndef get_ztf(ra, dec):\n ztfurl = 'https://mars.lco.global/?format=json&sort_value=jd&sort_order=desc&cone=%.7f%%2C%.7f%%2C0.0014'%(ra, dec)\n client = coreapi.Client()\n schema = client.get(ztfurl)\n return schema\n \ndef ztf2lc(ztf_obj):\n\n lc = at.Table(names=('jd','mag', 'mag_err', 'filter'), dtype=('f8', 'f8', 'f8', 'S1'))\n for i in range(len(ztf_obj['results'])):\n phot = ztf_obj['results'][i]['candidate']\n if phot['isdiffpos'] == 'f':\n continue\n lc.add_row([phot['jd'], phot['magap'], phot['sigmagap'], phot['filter']])\n return lc\n \ndef plot(ax,lc, survey):\n if survey =='atlas':\n limit =lc['flux']0\n for i in set(lc['filter']):\n index = lc['filter']==i\n jd = lc['jd'][index]\n if jd[0] > 2400000:\n jd = jd -2400000\n mag = abs(lc['mag'][index])\n err = lc['mag_err'][index]\n if survey =='atlas':\n flux = lc['flux'][index]\n fluxerr = lc['fluxerr'][index]\n limit =flux 2400000:\n jd = jd -2400000\n flux = lc['flux'][lc['filter']==i]\n err = lc['fluxerr'][lc['filter']==i]\n ax.errorbar(jd, flux, err, label = survey +' '+ i, fmt='o',color = lc_cfg['color'][i])\n\n# ax = plt.gca()\n\n #ax.grid(True)\n return ax\n\n\n \ndef lc(ra, dec, out_fig, atlas_data_file, disc_t):\n ztf_obj = get_ztf(ra, dec)\n\n lc = ztf2lc(ztf_obj)\n \n fig, (ax1, ax2)=plt.subplots(2, figsize = (6,10), sharex = True)\n\n try:\n atlas_lc = search_atlas(ra, dec)\n print('got lc')\n mask = (abs(atlas_lc['mag'])>10)\n atlas_lc = atlas_lc[mask]\n# print(atlas_lc)\n if len(atlas_lc)>0:\n print(atlas_data_file)\n ascii.write(atlas_lc, atlas_data_file, overwrite=True)\n# print(3)\n ax1 = plot(ax1,atlas_lc, 'atlas')\n ax2 = plot_atflux(ax2, atlas_lc, 'atlas')\n ax2.set_ylim(-0.1*max(atlas_lc['flux']), 1.2*max(atlas_lc['flux']))\n if len(lc)>0: \n ax1 = plot(ax1,lc, 'ztf')\n ymin = min(max([max(abs(lc['mag'])), max(abs(atlas_lc['mag']))])+0.5, 21)\n ax1.set_ylim(ymin, min([min(abs(lc['mag'])), min(abs(atlas_lc['mag']))]) -0.5)\n else:\n ymin = min(max(abs(atlas_lc['mag']))+0.5,21)\n ax1.set_ylim(ymin, min(abs(atlas_lc['mag']))-0.5)\n ax1.plot(disc_t, ymin, marker = \"^\")\n except:\n print('unable to get atlas lc')\n if len(lc)>0:\n ax1 = plot(ax1,lc, 'ztf')\n ax1.set_ylim(min(max(abs(lc['mag']))+0.5, 21), min(abs(lc['mag']))-0.5)\n \n tess_ob = tess_obs(ra, dec)\n# print(tess_ob)\n tess_cover = False\n \n today = dt.today()\n con = sqlite3.connect(\":memory:\")\n tdate = list(con.execute(\"select julianday('\"+today.strftime(\"%Y-%m-%d\")+\"')\"))[0][0]-2400000\n \n for [t1, t2] in tess_ob:\n x1= np.arange(t1-2400000, (t1+t2)/2-2400000-1., 0.1)\n x2= np.arange((t1+t2)/2-2400000+1, t2-2400000, 0.1)\n# print(t2,tdate + lc_cfg['xlim'][0] , t1,tdate+lc_cfg['xlim'][1])\n if x2[-1]> tdate + lc_cfg['xlim'][0] and x1[0]< tdate+lc_cfg['xlim'][1]:\n ax1.fill_between(x1, 10, 22, facecolor='grey', alpha=0.5, label = 'TESS')\n ax1.fill_between(x2, 10, 22, facecolor='grey', alpha=0.5)\n ax2.fill_between(x1, 0, 10000, facecolor='grey', alpha=0.5, label = 'TESS')\n ax2.fill_between(x2, 0, 10000, facecolor='grey', alpha=0.5)\n if disc_t>t1 and disc_t0:\n flux = 10**(-0.4*(k['mag']-27.5))\n fluxerr= k['mag_err']*10**(-0.4*(k['mag']-27.5))\n else:\n flux = -10**(-0.4*(-k['mag']-27.5))\n fluxerr= k['mag_err']*10**(-0.4*(-k['mag']-27.5))\n mag = k['mag']\n magerr = k['mag_err']\n f.write('OBS: ' + str(k['jd']) +' '+ flt+' '+ str(flux)+ ' '+str(fluxerr)+' '+ str(mag)+' '+ str(magerr)+' 0 \\n')\n\n os.system('python ./yse/uploadTransientData.py -e -s ./yse/settings.ini -i '+outname+' --instrument ACAM1 --fluxzpt 27.5')\n\n\n\n#if __name__ == \"__main__\":\ndef main(argv):\n# print(argv)\n# ra, dec, name, date= argv[0:]\n ra = float(argv[0])\n dec = float(argv[1])\n date = argv[3]\n name = argv[2]\n disc_t = 0.\n\n \n home_dir = lc_cfg['home_dir']+name+'/'\n Save_space(home_dir)\n\n out_fig = home_dir + name + date + '_lc.'+lc_cfg['img_suffix'] \n atlas_data_file = home_dir+name+date+'_atlas.csv'\n\n# print([ra, dec, '3', name + date+'_texas'])\n# if os.path.exists(home_dir+name+'_texas.txt'):\n# galcan = ascii.read(home_dir+name+'_texas.txt')\n# else:\n# try:\n# galcan = texas.main([argv[0], argv[1], '3', home_dir + name + '_texas'])\n# ascii.write(galcan, home_dir+name+'_texas.txt', overwrite=True) \n# except:\n# print('unable to access PanSTARRS')\n \n ra = float(ra)\n dec = float(dec) \n# tess_cover = False \n if len(argv)>4: \n disc_t = argv[4]\n else:\n disc_t = Time.now().jd\n \n if not os.path.exists(out_fig): # changed when server down.. will be back\n tess_cover = lc(ra, dec, out_fig, atlas_data_file, disc_t)\n else: \n tess_ob = tess_obs(ra, dec)\n tess_cover = False\n for [t1, t2] in tess_ob:\n if disc_t>t1 and disc_t0:\n# return tess_cover\n # else:\n return tess_cover\n \n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n\n","sub_path":"website/lc_ex.py","file_name":"lc_ex.py","file_ext":"py","file_size_in_byte":10429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"412524883","text":"import copy\nimport json\nimport os\n\nimport discord\nfrom unidecode import unidecode\n\nfrom chatbot import libchatbot\n\ntry: # Unicode patch for Windows\n import win_unicode_console\n\n win_unicode_console.enable()\nexcept:\n if os.name == 'nt':\n import sys\n\n if sys.version_info < (3, 6):\n print(\"Please install the 'win_unicode_console' module.\")\n\ndo_logging = True\nlog_name = \"Discord-Chatbot.log\"\n\nmodel = \"reddit\"\nsave_dir = \"models/\" + model\n\ndef_max_input_length = 1000\ndef_max_length = 125\n\ndef_beam_width = 2\ndef_relevance = -1\ndef_temperature = 1.0\ndef_topn = -1\n\nmax_input_length = def_max_input_length\nmax_length = def_max_length\n\nbeam_width = def_beam_width\nrelevance = def_relevance\ntemperature = def_temperature\ntopn = def_topn\n\nstates_main = \"states\" + \"_\" + model\n\nstates_folder = states_main + \"/\" + \"server_states\"\nstates_folder_dm = states_main + \"/\" + \"dm_states\"\n\nstates_saves = states_main + \"/\" + \"saves\"\n\nuser_settings_folder = \"user_settings\"\nult_operators_file = user_settings_folder + \"/\" + \"ult_operators.cfg\"\noperators_file = user_settings_folder + \"/\" + \"operators.cfg\"\nbanned_users_file = user_settings_folder + \"/\" + \"banned_users.cfg\"\n\nprocessing_users = []\n\nmention_in_message = True\nmention_message_separator = \" - \"\n\nmessage_prefix = \">\"\ncommand_prefix = \"--\" # Basically treated as message_prefix + command_prefix\n\nult_operators = []\noperators = []\nbanned_users = []\n\nstates_queue = {}\n\nprint('Loading Chatbot-RNN...')\nlib_save_states, lib_get_states, consumer = libchatbot(\n save_dir=save_dir, max_length=max_length)\nprint('Chatbot-RNN has been loaded.')\n\nprint('Preparing Discord Bot...')\nclient = discord.Client()\n\n\n@client.event\nasync def on_ready():\n print()\n print('Logged in as')\n print(client.user.name)\n print(client.user.id)\n print()\n print('Discord Bot ready!')\n\n\ndef log(message):\n if do_logging:\n with open(log_name, \"a\", encoding=\"utf-8\") as log_file:\n log_file.write(message)\n\n\ndef load_states(states_id):\n global states_folder, states_folder_dm\n\n make_folders()\n\n states_file = get_states_file(states_id)\n\n if os.path.exists(states_file + \".pkl\") and os.path.isfile(states_file + \".pkl\"):\n return lib_get_states(states_file)\n else:\n return lib_get_states()\n\n\ndef make_folders():\n if not os.path.exists(states_folder):\n os.makedirs(states_folder)\n\n if not os.path.exists(states_folder_dm):\n os.makedirs(states_folder_dm)\n\n if not os.path.exists(user_settings_folder):\n os.makedirs(user_settings_folder)\n\n if not os.path.exists(states_saves):\n os.makedirs(states_saves)\n\n\ndef get_states_file(states_id):\n if states_id.endswith(\"p\"):\n states_file = states_folder_dm + \"/\" + states_id\n else:\n states_file = states_folder + \"/\" + states_id\n\n return states_file\n\n\ndef save_states(states_id, states=None): # Saves directly to the file, recommended to use states queue\n make_folders()\n\n states_file = get_states_file(states_id)\n\n lib_save_states(states_file, states=states)\n\n\ndef add_states_to_queue(states_id, states_diffs):\n current_states_diffs = None\n\n if states_id in states_queue:\n current_states_diffs = states_queue[states_id]\n\n for num in range(len(states_diffs)):\n if current_states_diffs is not None and current_states_diffs[num] is not None:\n states_diffs[num] += current_states_diffs[num]\n\n states_queue.update({states_id: states_diffs})\n\n\ndef get_states_id(message):\n if message.guild is None or isinstance(message.channel, discord.abc.PrivateChannel):\n return str(message.channel.id) + \"p\"\n else:\n return str(message.guild.id) + \"s\"\n\n\ndef write_state_queue():\n for states_id in states_queue:\n states = load_states(states_id)\n\n states_diff = states_queue[states_id]\n if get_states_size(states) > len(states_diff):\n states = states[0]\n\n elif get_states_size(states) < len(states_diff):\n states = [copy.deepcopy(states), copy.deepcopy(states)]\n\n new_states = copy.deepcopy(states)\n\n total_num = 0\n for num in range(len(states)):\n for num_two in range(len(states[num])):\n for num_three in range(len(states[num][num_two])):\n for num_four in range(len(states[num][num_two][num_three])):\n new_states[num][num_two][num_three][num_four] = states[num][num_two][num_three][num_four] - \\\n states_diff[total_num]\n total_num += 1\n\n lib_save_states(get_states_file(states_id), states=new_states)\n states_queue.clear()\n\n\ndef get_states_size(states):\n total_num = 0\n if states is not None:\n for num in range(len(states)):\n for num_two in range(len(states[num])):\n for num_three in range(len(states[num][num_two])):\n for num_four in range(len(states[num][num_two][num_three])):\n total_num += 1\n return total_num\n\n\ndef is_discord_id(user_id):\n # Quick general check to see if it matches the ID formatting\n return (isinstance(user_id, int) or user_id.isdigit) and len(str(user_id)) == 18\n\n\ndef remove_invalid_ids(id_list):\n for user in id_list:\n if not is_discord_id(user):\n id_list.remove(user)\n\n\ndef save_ops_bans():\n global ult_operators, operators, banned_users\n\n make_folders()\n\n # Sort and remove duplicate entries\n ult_operators = list(set(ult_operators))\n operators = list(set(operators))\n banned_users = list(set(banned_users))\n\n # Remove from list if ID is invalid\n remove_invalid_ids(ult_operators)\n\n # Remove them from the ban list if they were added\n # Op them if they were removed\n for user in ult_operators:\n operators.append(user)\n if user in banned_users:\n banned_users.remove(user)\n\n # Remove from list if ID is invalid\n remove_invalid_ids(operators)\n\n # Remove from list if ID is invalid\n remove_invalid_ids(banned_users)\n\n # Sort and remove duplicate entries\n ult_operators = list(set(ult_operators))\n operators = list(set(operators))\n banned_users = list(set(banned_users))\n\n with open(ult_operators_file, 'w') as f:\n f.write(json.dumps(ult_operators))\n with open(operators_file, 'w') as f:\n f.write(json.dumps(operators))\n with open(banned_users_file, 'w') as f:\n f.write(json.dumps(banned_users))\n\n\ndef load_ops_bans():\n global ult_operators, operators, banned_users\n\n make_folders()\n\n if os.path.exists(ult_operators_file) and os.path.isfile(ult_operators_file):\n with open(ult_operators_file, 'r') as f:\n try:\n ult_operators = json.loads(f.read())\n except json.decoder.JSONDecodeError:\n ult_operators = []\n\n if os.path.exists(operators_file) and os.path.isfile(operators_file):\n with open(operators_file, 'r') as f:\n try:\n operators = json.loads(f.read())\n except json.decoder.JSONDecodeError:\n operators = []\n\n if os.path.exists(banned_users_file) and os.path.isfile(banned_users_file):\n with open(banned_users_file, 'r') as f:\n try:\n banned_users = json.loads(f.read())\n except json.decoder.JSONDecodeError:\n banned_users = []\n\n save_ops_bans()\n\n\n# Prepare the operators and ban lists\nload_ops_bans()\n\n\ndef matches_command(content, command):\n try:\n content = content[:content.index(\" \")]\n except ValueError:\n pass\n\n return content.lower() == command_prefix.lower() + command.lower()\n\n\ndef remove_command(content):\n try:\n content = content[content.index(\" \") + 1:]\n except ValueError:\n content = \"\"\n\n return content\n\n\ndef user_id_cleanup(uid):\n return uid.replace(\"<@\", \"\").replace(\"!\", \"\").replace(\">\", \"\")\n\n\ndef get_args(content):\n return split_args(remove_command(content))\n\n\ndef split_args(full_args):\n return [] if full_args == \"\" else full_args.split(\" \")\n\n\ndef get_user_perms(message):\n load_ops_bans()\n\n user_perms = {\n \"banned\": message.author.id in banned_users,\n \"op\": message.author.id in operators,\n \"ult_op\": message.author.id in ult_operators,\n \"server_admin\": message.guild is None or message.author.guild_permissions.administrator,\n \"private\": message.channel is discord.abc.PrivateChannel,\n }\n\n return user_perms\n\n\ndef process_response(response, result):\n # 0 = OK\n # 1 = Generic error in arguments\n # 2 = Too many arguments\n # 3 = Not enough arguments\n # 4 = Generic error\n # 5 = No permissions error\n # 6 = User not found error\n # 7 = Command not found error\n\n error_code_print = False\n\n if result == 0:\n if response == \"\":\n response = \"Command successful\"\n\n response = \"System: \" + response\n elif result == 1:\n if response == \"\":\n response = \"Invalid argument(s)\"\n\n response = \"Error: \" + response\n elif result == 2:\n if response == \"\":\n response = \"Too many arguments\"\n\n response = \"Error: \" + response\n elif result == 3:\n if response == \"\":\n response = \"Not enough arguments\"\n\n response = \"Error: \" + response\n elif result == 4:\n if response == \"\":\n response = \"Generic error\"\n error_code_print = True\n\n response = \"Error: \" + response\n elif result == 5:\n if response == \"\":\n response = \"Insufficient permissions\"\n\n response = \"Error: \" + response\n elif result == 6:\n if response == \"\":\n response = \"User not found\"\n\n response = \"Error: \" + response\n elif result == 7:\n if response == \"\":\n response = \"Command not found\"\n\n response = \"Error: \" + response\n\n if error_code_print:\n response += \" (Error Code \" + str(result) + \")\"\n\n return response\n\n\nasync def process_command(msg_content, message):\n global max_input_length, max_length, beam_width, relevance, temperature, topn\n\n result = 0\n\n response = \"\"\n\n load_ops_bans()\n user_perms = get_user_perms(message)\n\n cmd_args = get_args(msg_content)\n\n if matches_command(msg_content, \"help\"):\n response = \"Available Commands:\\n\" \\\n \"```\\n\" \\\n \"help, restart, reset, save, load, op, deop, ban, unban, param_reset, \" \\\n \"max_input_length, max_length, beam_width, temperature, relevance, topn\\n\" \\\n \"```\"\n\n elif matches_command(msg_content, \"restart\"):\n if user_perms[\"ult_op\"]:\n print()\n print(\"[Restarting...]\")\n response = \"System: Restarting...\"\n await send_message(message, response)\n await client.close()\n exit()\n else:\n result = 5\n\n elif matches_command(msg_content, \"reset\"):\n if user_perms[\"op\"] or user_perms[\"private\"] or user_perms[\"server_admin\"]:\n reset_states = lib_get_states()\n\n save_states(get_states_id(message), states=reset_states)\n\n print()\n print(\"[Model state reset]\")\n response = \"Model state reset\"\n else:\n result = 5\n\n elif matches_command(msg_content, \"save\"):\n if user_perms[\"ult_op\"]:\n if len(cmd_args) >= 1:\n input_text = cmd_args[0]\n\n if input_text.endswith(\".pkl\"):\n input_text = input_text[:len(input_text) - len(\".pkl\")]\n\n make_folders()\n\n lib_save_states(states_saves + \"/\" + input_text,\n states=lib_get_states(get_states_file(get_states_id(message))))\n\n print()\n print(\"[Saved states to \\\"{}.pkl\\\"]\".format(input_text))\n response = \"Saved model state to \\\"{}.pkl\\\"\".format(input_text)\n else:\n result = 3\n else:\n result = 5\n\n elif matches_command(msg_content, \"load\"):\n if user_perms[\"ult_op\"]:\n if len(cmd_args) >= 1:\n input_text = cmd_args[0]\n\n if input_text.endswith(\".pkl\"):\n input_text = input_text[:len(input_text) - len(\".pkl\")]\n\n make_folders()\n\n save_states(get_states_id(message), states=lib_get_states(states_saves + \"/\" + input_text))\n\n print()\n print(\"[Loaded saved states from \\\"{}.pkl\\\"]\".format(\n input_text))\n response = \"Loaded saved model state from \\\"{}.pkl\\\"\".format(\n input_text)\n else:\n result = 3\n else:\n result = 5\n\n elif matches_command(msg_content, \"op\"):\n if user_perms[\"ult_op\"]:\n if len(cmd_args) >= 1:\n # Replacements are to support mentioned users\n input_text = user_id_cleanup(remove_command(msg_content))\n user_exists = True\n\n # Check if user actually exists\n try:\n await client.fetch_user(input_text)\n except discord.NotFound:\n user_exists = False\n except discord.HTTPException:\n user_exists = False\n\n if not input_text == str(message.author.id):\n if user_exists:\n if not int(input_text) in ult_operators and not int(input_text) == client.user.id:\n if not int(input_text) in operators:\n if not int(input_text) in banned_users:\n load_ops_bans()\n operators.append(int(input_text))\n save_ops_bans()\n print()\n print(\"[Opped \\\"{}\\\"]\".format(input_text))\n response = \"Opped \\\"{}\\\".\".format(input_text)\n else:\n response = \"Unable to op user \\\"{}\\\", they're banned\".format(input_text)\n result = 4\n else:\n response = \"Unable to op user \\\"{}\\\", they're already OP\".format(input_text)\n result = 4\n else:\n response = \"Unable to op user \\\"{}\\\", you do not have permission to do so\".format(\n input_text)\n result = 3\n else:\n response = \"Unable to op user \\\"{}\\\", they don't exist\".format(input_text)\n result = 6\n else:\n response = \"Unable to op user \\\"{}\\\", __that's yourself__...\".format(input_text)\n result = 4\n else:\n result = 3\n else:\n result = 5\n\n elif matches_command(msg_content, \"deop\"):\n if user_perms[\"ult_op\"]:\n if len(cmd_args) >= 1:\n # Replacements are to support mentioned users\n input_text = user_id_cleanup(remove_command(msg_content))\n user_exists = True\n\n # Check if user actually exists\n try:\n await client.fetch_user(input_text)\n except discord.NotFound:\n user_exists = False\n except discord.HTTPException:\n user_exists = False\n\n if not input_text == str(message.author.id):\n if user_exists:\n if not int(input_text) in ult_operators and not int(input_text) == client.user.id:\n if int(input_text) in operators:\n load_ops_bans()\n if int(input_text) in operators:\n operators.remove(int(input_text))\n save_ops_bans()\n print()\n print(\"[De-opped \\\"{}\\\"]\".format(input_text))\n response = \"De-opped \\\"{}\\\".\".format(input_text)\n else:\n response = \"Unable to de-op user \\\"{}\\\", they're not OP\".format(input_text)\n result = 4\n else:\n response = \"Unable to de-op user \\\"{}\\\", you do not have permission to do so\".format(\n input_text)\n result = 3\n else:\n response = \"Unable to de-op user \\\"{}\\\", they don't exist\".format(input_text)\n result = 6\n else:\n response = \"Unable to de-op user \\\"{}\\\", __that's yourself__...\".format(input_text)\n result = 4\n else:\n result = 3\n else:\n result = 5\n\n elif matches_command(msg_content, \"ban\"):\n if user_perms[\"op\"]:\n if len(cmd_args) >= 1:\n # Replacements are to support mentioned users\n input_text = user_id_cleanup(remove_command(msg_content))\n user_exists = True\n\n # Check if user actually exists\n try:\n await client.fetch_user(input_text)\n except discord.NotFound:\n user_exists = False\n except discord.HTTPException:\n user_exists = False\n\n if not input_text == str(message.author.id):\n if user_exists:\n if not int(input_text) in ult_operators and not int(input_text) == client.user.id:\n if not int(input_text) in banned_users:\n load_ops_bans()\n banned_users.append(int(input_text))\n save_ops_bans()\n print()\n print(\"[Banned \\\"{}\\\"]\".format(input_text))\n response = \"Banned \\\"{}\\\".\".format(input_text)\n else:\n response = \"Unable to ban user \\\"{}\\\", they're already banned\".format(input_text)\n result = 4\n else:\n response = \"Unable to ban user \\\"{}\\\", you do not have permission to do so\".format(\n input_text)\n result = 3\n else:\n response = \"Unable to ban user \\\"{}\\\", they don't exist\".format(input_text)\n result = 6\n else:\n response = \"Unable to ban user \\\"{}\\\", __that's yourself__...\".format(input_text)\n result = 4\n else:\n result = 3\n else:\n result = 5\n\n elif matches_command(msg_content, \"unban\"):\n if user_perms[\"op\"]:\n if len(cmd_args) >= 1:\n # Replacements are to support mentioned users\n input_text = user_id_cleanup(remove_command(msg_content))\n user_exists = True\n\n # Check if user actually exists\n try:\n await client.fetch_user(input_text)\n except discord.NotFound:\n user_exists = False\n except discord.HTTPException:\n user_exists = False\n\n if not input_text == str(message.author.id):\n if user_exists:\n if not int(input_text) in ult_operators and not int(input_text) == client.user.id:\n if int(input_text) in banned_users:\n load_ops_bans()\n if int(input_text) in banned_users:\n banned_users.remove(int(input_text))\n save_ops_bans()\n print()\n print(\"[Un-banned \\\"{}\\\"]\".format(input_text))\n response = \"Un-banned \\\"{}\\\".\".format(input_text)\n else:\n response = \"Unable to un-ban user \\\"{}\\\", they're not banned\".format(input_text)\n result = 4\n else:\n response = \"Unable to un-ban user \\\"{}\\\", you do not have permission to do so\".format(\n input_text)\n result = 3\n else:\n response = \"Unable to un-ban user \\\"{}\\\", they don't exist\".format(input_text)\n result = 6\n else:\n response = \"Unable to un-ban user \\\"{}\\\", __that's yourself__...\".format(input_text)\n result = 4\n else:\n result = 3\n else:\n result = 5\n\n elif matches_command(msg_content, \"param_reset\"):\n if user_perms[\"ult_op\"]:\n max_input_length = def_max_input_length\n max_length = def_max_length\n\n beam_width = def_beam_width\n relevance = def_relevance\n temperature = def_temperature\n topn = def_topn\n\n print()\n print(\"[User \\\"{}\\\" reset all params]\".format(message.author.id))\n response = \"All parameters have been reset.\"\n else:\n result = 5\n\n elif matches_command(msg_content, \"max_input_length\"):\n if user_perms[\"ult_op\"]:\n if len(cmd_args) >= 1:\n input_text = cmd_args[0]\n\n max_input_length = int(input_text)\n print()\n print(\"[User \\\"{}\\\" changed the max input length to {}]\".format(message.author.id, max_input_length))\n response = \"Max input length changed to {}.\".format(max_input_length)\n else:\n result = 3\n else:\n result = 5\n\n elif matches_command(msg_content, \"max_length\"):\n if user_perms[\"ult_op\"]:\n if len(cmd_args) >= 1:\n input_text = cmd_args[0]\n\n max_length = int(input_text)\n print()\n print(\"[User \\\"{}\\\" changed the max response length to {}]\".format(message.author.id, max_length))\n response = \"Max response length changed to {}.\".format(max_length)\n else:\n result = 3\n else:\n result = 5\n\n elif matches_command(msg_content, \"beam_width\"):\n if user_perms[\"op\"] or user_perms[\"private\"] or user_perms[\"server_admin\"]:\n if len(cmd_args) >= 1:\n input_text = cmd_args[0]\n\n beam_width = int(input_text)\n print()\n print(\"[User \\\"{}\\\" changed the beam width to {}]\".format(message.author.id, beam_width))\n response = \"Beam width changed to {}.\".format(beam_width)\n else:\n result = 3\n else:\n result = 5\n\n elif matches_command(msg_content, \"temperature\"):\n if user_perms[\"op\"] or user_perms[\"private\"] or user_perms[\"server_admin\"]:\n if len(cmd_args) >= 1:\n input_text = cmd_args[0]\n\n temperature = float(input_text)\n print()\n print(\"[User \\\"{}\\\" changed the temperature to {}]\".format(message.author.id, temperature))\n response = \"Temperature changed to {}.\".format(temperature)\n else:\n result = 3\n else:\n result = 5\n\n elif matches_command(msg_content, \"relevance\"):\n if user_perms[\"op\"] or user_perms[\"private\"] or user_perms[\"server_admin\"]:\n if len(cmd_args) >= 1:\n input_text = cmd_args[0]\n\n relevance = float(input_text)\n print()\n print(\"[User \\\"{}\\\" changed the relevance to {}]\".format(message.author.id, relevance))\n response = \"Relevance changed to {}.\".format(relevance)\n else:\n result = 3\n else:\n result = 5\n\n elif matches_command(msg_content, \"topn\"):\n if user_perms[\"op\"] or user_perms[\"private\"] or user_perms[\"server_admin\"]:\n if len(cmd_args) >= 1:\n input_text = cmd_args[0]\n\n topn = int(input_text)\n print()\n print(\"[User \\\"{}\\\" changed the topn to {}]\".format(message.author.id, topn))\n response = \"TopN filter changed to {}.\".format(topn)\n else:\n result = 3\n else:\n result = 5\n\n else:\n result = 7\n\n return process_response(response, result)\n\n\ndef has_channel_perms(message):\n return message.guild is None or message.channel.permissions_for(\n message.guild.get_member(client.user.id)).send_messages;\n\n\nasync def send_message(message, text):\n if (mention_in_message or (not mention_in_message and not text == \"\")) and has_channel_perms(message):\n user_mention = \"\"\n\n if mention_in_message:\n user_mention = \"<@\" + str(message.author.id) + \">\" + mention_message_separator\n\n await message.channel.send(user_mention + text)\n\n\n@client.event\nasync def on_message(message):\n global max_input_length, max_length, beam_width, relevance, temperature, topn, lib_save_states, lib_get_states, consumer\n\n if message.content.lower().startswith(message_prefix.lower()) or message.channel is discord.abc.PrivateChannel and not message.author.bot and has_channel_perms(message):\n msg_content = message.content\n\n if msg_content.startswith(message_prefix):\n msg_content = msg_content[len(message_prefix):]\n if msg_content.startswith(\" \"):\n msg_content = msg_content[len(\" \"):]\n\n response = \"Error: Unknown error...\"\n\n async with message.channel.typing():\n user_perms = get_user_perms(message)\n if user_perms[\"banned\"] and not user_perms[\"private\"]:\n response = process_response(\"You have been banned and can only use this bot in DMs\", 5)\n\n elif msg_content.lower().startswith(command_prefix.lower()):\n response = await process_command(msg_content, message)\n\n else:\n if not (message.author.id in processing_users):\n if not msg_content == \"\":\n if not len(msg_content) > max_input_length:\n # Possibly problematic: if something goes wrong,\n # then the user couldn't send messages anymore\n processing_users.append(message.author.id)\n\n states = load_states(get_states_id(message))\n\n old_states = copy.deepcopy(states)\n\n clean_msg_content = unidecode(message.clean_content)\n\n if clean_msg_content.startswith(message_prefix):\n clean_msg_content = clean_msg_content[len(message_prefix):]\n if clean_msg_content.startswith(\" \"):\n clean_msg_content = clean_msg_content[len(\" \"):]\n\n print() # Print out new line for formatting\n print(\"> \" + clean_msg_content) # Print out user message\n\n # Automatically prints out response as it's written\n result, states = await consumer(clean_msg_content, states=states, beam_width=beam_width, relevance=relevance, temperature=temperature, topn=topn, max_length=max_length)\n\n # Purely debug\n # print(states[0][0][0]) Prints out the lowest level array\n # for state in states[0][0][0]: Prints out every entry in the lowest level array\n # print(state)\n\n # Remove whitespace before the message\n while result.startswith(\" \"):\n result = result[1:]\n\n if not mention_in_message and result == \"\":\n result = \"...\"\n\n response = result\n\n print() # Move cursor to next line after response\n\n log(\"\\n> \" + msg_content + \"\\n\" + result + \"\\n\") # Log entire interaction\n if len(old_states) == len(states):\n # Get the difference in the states\n\n states_diff = []\n for num in range(len(states)):\n for num_two in range(len(states[num])):\n for num_three in range(len(states[num][num_two])):\n for num_four in range(len(states[num][num_two][num_three])):\n states_diff.append(old_states[num][num_two][num_three][num_four] -\n states[num][num_two][num_three][num_four])\n\n add_states_to_queue(get_states_id(message), states_diff)\n write_state_queue()\n # save_states(get_states_id(message)) Old saving\n else:\n # Revert to old saving to directly write new array dimensions\n save_states(get_states_id(message))\n\n processing_users.remove(message.author.id)\n else:\n response = \"Error: Your message is too long (\" + str(len(msg_content)) + \"/\" + str(\n max_input_length) + \" characters)\"\n else:\n response = \"Error: Your message is empty\"\n else:\n response = \"Error: Please wait for your response to be generated before sending more messages\"\n\n await send_message(message, response)\n\n\nclient.run(\"Token Goes Here\", reconnect=True)\n","sub_path":"discord_bot.py","file_name":"discord_bot.py","file_ext":"py","file_size_in_byte":30759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"11272830","text":"\"\"\"\nName: Erel Shtossel\nID: 316297696\n\"\"\"\n\nimport random\nimport threading\nimport my_utils\nimport breadcrumbs\nimport copy\nfrom igraph import *\n\n\nclass learner(object):\n def __init__(self, q_table, last_state=None, last_action=None):\n self.table = q_table.table\n self.time_running = q_table.time_running\n self.meta_data = q_table\n self.last_state = last_state\n self.last_action = last_action\n self.last_valid_actions = []\n self.list_of_actions_with_no_impact = q_table.list_of_actions_with_no_impact\n self.save_format_for_graph = \"graphml\"\n\n self.track_finished_goals = list()\n self.num_of_finished_subgoals = 0\n self.points_of_interest = None\n\n self.time_from_last_save = 100\n self.save_q_table_func = lambda x: x.save_to_file(q_table.path)\n\n self.learning_rate = 0.8\n self.discount_factor = 0.8\n self.explore_level = 1 - q_table.time_running * 0.09\n\n def initialize(self, services):\n self.services = services\n self.meta_data.goal_states[\"start\"] = my_utils.to_state(\n self.services.parser.copy_state(self.services.perception.get_state()))\n try:\n file_name = self.services.parser.domain_name + my_utils.to_state(\n self.services.parser.objects) + \".\" + self.save_format_for_graph\n self.states_graph = Graph.Read(file_name.replace('/', '#'), self.save_format_for_graph)\n except:\n self.states_graph = Graph(directed=True)\n if self.time_running > 0 and len(self.meta_data.goal_states) > 0:\n graph_actions = breadcrumbs.graph_actions(self.states_graph, copy.deepcopy(self.meta_data.goal_states))\n self.breadcrumbs, self.sub_goals_order = graph_actions.calculate_best_path()\n\n all_actions = list()\n all_goal_actions = list()\n for i in range(len(self.breadcrumbs) - 1):\n action = \\\n self.states_graph.es.find(self.states_graph.get_eid(self.breadcrumbs[i], self.breadcrumbs[i + 1]))[\n \"name\"]\n all_actions.append(action)\n if self.breadcrumbs[i + 1] in self.sub_goals_order[0]:\n all_goal_actions.append(action)\n\n # Extract a list of actions that we want to do before other actions based on knowledge from the state graph\n self.points_of_interest = dict()\n index_of_last_sub_goal = 0\n place_in_permutation = 0\n for sub_goals in all_goal_actions:\n index_of_sub_goal = all_actions.index(sub_goals)\n path_to_sub_goal = all_actions[index_of_last_sub_goal:index_of_sub_goal + 1]\n path_to_sub_goal.reverse()\n # Remove actions with no impact on the way:\n # i = 1\n # while i < len(path_to_sub_goal):\n # # Not touching the first element because it is the sub-goal\n # if path_to_sub_goal[i] in self.list_of_actions_with_no_impact:\n # path_to_sub_goal.remove(path_to_sub_goal[i])\n # continue\n # i += 1\n # goal_words = path_to_sub_goal[0].strip(\")\").strip(\"(\").split()[1:]\n # i = 1\n # while i in range(len(path_to_sub_goal)):\n # if not any(x in path_to_sub_goal[i] for x in goal_words):\n # path_to_sub_goal.remove(path_to_sub_goal[i])\n # continue\n # i += 1\n self.points_of_interest[self.sub_goals_order[2][place_in_permutation]] = path_to_sub_goal\n place_in_permutation += 1\n index_of_last_sub_goal = index_of_sub_goal\n\n self.way_to_groups_of_same_action_dict = dict()\n for task in self.sub_goals_order[2]:\n self.way_to_groups_of_same_action_dict[task] = self.way_to_groups_of_same_action(task)\n\n if self.breadcrumbs is not None:\n for i in range(len(self.breadcrumbs) - 1):\n source = self.breadcrumbs[i]\n target = self.breadcrumbs[i + 1]\n edge_id = self.states_graph.get_eid(source, target)\n action = self.states_graph.es.find(edge_id)[\"name\"].strip(source).strip(target)\n # Every run- the data from the graph is better\n self.table[source][action] += 1.0 / (pow(2, 6 - self.time_running))\n\n def save_graph(self):\n file_name = self.services.parser.domain_name + my_utils.to_state(\n self.services.parser.objects) + \".\" + self.save_format_for_graph\n self.states_graph.save(file_name.replace('/', '#'), format=self.save_format_for_graph)\n\n def __del__(self):\n curr_state = my_utils.to_state(self.services.parser.copy_state(self.services.perception.get_state()))\n self.update_states_graph(curr_state)\n\n finished_goals = my_utils.done_subgoals(self.services.goal_tracking.completed_goals,\n self.services.perception.get_state())\n\n if len(self.services.goal_tracking.uncompleted_goals) == 0:\n # We won- find the last sub_goal\n try:\n self.meta_data.goal_states[curr_state] = self.track_finished_goals.index(False)\n except:\n 0 # Only one goal\n self.update_table(1000)\n else:\n self.update_table(-1000)\n\n self.save_q_table_func(self.meta_data)\n self.save_graph()\n\n def reward_function(self, state, action, new_state):\n # walking is a waist of time\n reward = -1\n if self.time_running > 0 and self.breadcrumbs is not None:\n if self.states_graph.vs.find(state).index in self.breadcrumbs and self.states_graph.vs.find(\n new_state).index in self.breadcrumbs:\n if self.breadcrumbs.index(self.states_graph.vs.find(state).index) + 1 == self.breadcrumbs.index(\n self.states_graph.vs.find(new_state).index):\n reward = 0\n if state == new_state:\n # the last action failed - maybe a better probability can be achieved with an other action\n reward -= 0.1\n # the final reward is given when the simulation ends- so it is in the goal check\n # the final reward is 1000\n return reward\n\n def update_table(self, reward=None, curr_state=None, curr_seen_best_option_value=None):\n # This function updates the q table\n if reward == None:\n reward = self.reward_function(self.last_state, self.last_action, curr_state)\n else:\n curr_seen_best_option_value = reward\n\n if not self.table[self.last_state].has_key(self.last_action):\n self.table[self.last_state][self.last_action] = 0\n self.table[self.last_state][self.last_action] = self.table[self.last_state][\n self.last_action] + self.learning_rate * (\n reward + self.discount_factor * curr_seen_best_option_value -\n self.table[self.last_state][self.last_action])\n\n def explore(self, curr_state, curr_valid_actions):\n action_grades = dict()\n high_graded_action = None\n choose_from = list()\n for iter in curr_valid_actions:\n if (iter not in self.table[curr_state]):\n # This is a new option opened because of our actions\n self.table[curr_state][iter] = 0\n if (self.table[curr_state][iter]) == 0:\n # Go to a place never evaluated\n choose_from.append(iter)\n\n # Goal analyze\n goal_keywords = self.extract_goal_keywords(self.services.goal_tracking.uncompleted_goals)\n for action in curr_valid_actions:\n for keyword_tuple in goal_keywords:\n update_val = 1\n for keyword in keyword_tuple:\n if action.find(keyword) != -1:\n if action_grades.has_key(action):\n action_grades[action] = update_val\n else:\n action_grades[action] = update_val\n update_val += 1\n if (len(action_grades) > 1):\n high_graded_action = max(random.sample(action_grades.keys(), len(action_grades)), key=action_grades.get)\n\n if high_graded_action != None:\n if random.random() > math.pow(0.5, action_grades[high_graded_action]):\n return high_graded_action\n\n if len(curr_valid_actions) > 0:\n try:\n # Choose the least walked in vertex\n vertex = self.states_graph.vs.find(curr_state)\n neighbors = vertex.neighbors()\n y = min(random.sample(neighbors, len(neighbors)), key=lambda x: x[\"count\"])\n for edge in vertex.out_edges():\n if edge.source == vertex.index and edge.target == y.index:\n return edge[\"name\"].strip(vertex[\"name\"]).strip(y[\"name\"])\n except:\n 0\n return random.choice(curr_valid_actions)\n\n if len(curr_valid_actions) == 0:\n # Dead end\n return None\n\n def extract_goal_keywords(self, uncompleted_goals):\n keywords = set()\n for sub_condition in uncompleted_goals:\n for part in sub_condition.parts:\n keywords.add(part.args)\n return keywords\n\n def next_action(self):\n # find current state\n raw_state_info = self.services.parser.copy_state(self.services.perception.get_state())\n curr_state = my_utils.to_state(raw_state_info)\n curr_valid_actions = self.services.valid_actions.get()\n\n self.register_new_state(curr_state, curr_valid_actions)\n # Dead end checking\n curr_seen_best_option = my_utils.key_max_value_from_actions(self.table[curr_state])\n if curr_seen_best_option == -1:\n # This is the end - no path from here\n self.update_table(reward=-1500)\n self.update_states_graph(curr_state)\n self.save_graph()\n return None\n\n list_of_opened_options = list(set(curr_valid_actions).difference(set(self.last_valid_actions)))\n if len(list_of_opened_options) == 0:\n # last action didn't change nothing\n self.list_of_actions_with_no_impact.add(self.last_action)\n\n if self.last_state != None:\n self.update_states_graph(curr_state)\n\n finished_goals = my_utils.done_subgoals(self.services.goal_tracking.uncompleted_goals,\n raw_state_info)\n curr_subgoals_finished = my_utils.num_of_done_subgoals(finished_goals)\n\n if curr_subgoals_finished > self.num_of_finished_subgoals or len(\n self.services.goal_tracking.uncompleted_goals) == 0:\n # We got a sub goal!\n if len(self.services.goal_tracking.uncompleted_goals) != 0:\n self.meta_data.goal_states[curr_state] = my_utils.diff(self.track_finished_goals, finished_goals)\n else:\n self.meta_data.goal_states[curr_state] = 0\n if len(finished_goals) != 0:\n self.track_finished_goals = finished_goals\n if self.points_of_interest is not None and self.points_of_interest.has_key(\n self.meta_data.goal_states[curr_state]):\n del self.points_of_interest[self.meta_data.goal_states[curr_state]]\n\n self.update_table(1000)\n self.num_of_finished_subgoals = curr_subgoals_finished\n if self.services.goal_tracking.reached_all_goals():\n # We got all goals!\n self.save_graph()\n return None\n elif curr_subgoals_finished < self.num_of_finished_subgoals:\n # We lost a sub goal\n self.update_table(-1100)\n\n self.track_finished_goals = finished_goals\n\n # observe and update the q table\n self.update_table(reward=None, curr_state=curr_state,\n curr_seen_best_option_value=self.table[curr_state][curr_seen_best_option])\n\n try_action = self.choose_explore_or_exploit(curr_seen_best_option, curr_state, curr_valid_actions)\n\n # save this state as the last one done:\n self.last_state = curr_state\n self.last_action = try_action\n self.last_valid_actions = curr_valid_actions\n\n self.time_from_last_save -= 1\n if self.time_from_last_save == 0:\n threading.Thread(target=self.save_q_table_func(deepcopy(self.meta_data))).start()\n # threading.Thread(target=self.save_graph).start()\n self.save_graph()\n self.time_from_last_save = 5000\n\n # Keep the q_table as clean as possible\n for iter in curr_valid_actions:\n if self.table[curr_state][iter] == 0:\n del self.table[curr_state][iter]\n if len(self.table[curr_state]) == 0:\n self.table[curr_state][try_action] = 0\n\n return try_action\n\n def update_states_graph(self, curr_state):\n try:\n vertex = self.states_graph.vs.find(name=str(curr_state))\n vertex[\"count\"] += 1\n except:\n vertex = self.states_graph.add_vertex(str(curr_state))\n vertex[\"count\"] = 1\n try:\n vertex = self.states_graph.vs.find(name=str(self.last_state))\n vertex[\"count\"] += 1\n except:\n vertex = self.states_graph.add_vertex(str(self.last_state))\n vertex[\"count\"] = 1\n try:\n edge = self.states_graph.es.find(name=str(self.last_state) + self.last_action + str(curr_state))\n except:\n edge = self.states_graph.add_edge(str(self.last_state), str(curr_state))\n edge[\"name\"] = self.last_action # str(self.last_state) + self.last_action + str(curr_state)\n\n def exploit_graph(self, curr_valid_actions,curr_seen_best_option):\n task = [x for x in self.sub_goals_order[2] if x in self.points_of_interest.keys()][0]\n if not hasattr(self, 'last_task'):\n self.last_task = task\n if not hasattr(self, 'place_on_way') or self.last_task != task:\n if self.meta_data.has_keys == False:\n self.place_on_way = len(self.points_of_interest[task])\n else:\n self.place_on_way = 0\n # TODO: try it once- if it does not work- leave this system (we have keys in this problem)\n if self.meta_data.has_keys == False:\n i = 0\n for action_in_best_path in self.points_of_interest[task]:\n if action_in_best_path in curr_valid_actions:\n if self.place_on_way != None and self.place_on_way >= i:\n self.place_on_way = i\n return action_in_best_path\n else:\n # Don't return to this system anymore\n self.place_on_way = 0\n self.meta_data.has_keys = True\n return random.choice(curr_valid_actions)\n i += 1\n else:\n # TODO: if they are 2 actions of the same kind one after one - try not doing the second one\n\n way_as_groups = self.way_to_groups_of_same_action_dict[task]\n for group_of_actions in way_as_groups[self.place_on_way:]:\n group_of_possible_actions = set(curr_valid_actions).intersection(group_of_actions)\n if len(group_of_possible_actions) > 0:\n self.place_on_way += 1\n if curr_seen_best_option in group_of_possible_actions:\n return curr_seen_best_option\n return random.choice(list(group_of_possible_actions))\n else:\n # We can't do what we wanted\n return curr_seen_best_option\n\n return None\n\n def way_to_groups_of_same_action(self, task):\n # Can be calculated only once\n way_as_group = []\n\n for action in self.points_of_interest[task]:\n if len(way_as_group) > 0:\n last_node = way_as_group.pop()\n else:\n way_as_group.append([action])\n continue\n if last_node is not None and last_node[0].strip(\"(\").split()[0] == action.strip(\"(\").split()[0]:\n # This is the same kind of action\n last_node.append(action)\n way_as_group.append(last_node)\n else:\n way_as_group.append(last_node)\n way_as_group.append([action])\n way_as_group.reverse()\n return way_as_group\n\n def choose_explore_or_exploit(self, curr_seen_best_option, curr_state, curr_valid_actions):\n x = random.random()\n if x < self.explore_level:\n # time to explore:\n try_action = self.explore(curr_state, curr_valid_actions)\n else:\n # time to exploite:\n if self.breadcrumbs is not None:\n try_action = self.exploit_graph(curr_valid_actions,curr_seen_best_option)\n if try_action is None:\n try_action = curr_seen_best_option\n return try_action\n\n def register_new_state(self, curr_state, curr_valid_actions):\n if self.table.get(curr_state) is None:\n # this is a new state that we need to evaluate and add to the table\n self.table[curr_state] = dict()\n for iter in curr_valid_actions:\n self.table[curr_state][iter] = 0\n else:\n for iter in curr_valid_actions:\n if not self.table[curr_state].has_key(iter):\n self.table[curr_state][iter] = 0\n","sub_path":"learner.py","file_name":"learner.py","file_ext":"py","file_size_in_byte":18153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"445874619","text":"from abc import ABC\n\nfrom Mesh.System.SpaceFactor import MatterType\nfrom Mesh.util import Logger\n\n\nclass Entity(ABC):\n identifier = 'entity'\n\n def __init__(self, uuid):\n self.uuid = uuid\n self.dimension = (0, 0, 0)\n self.matter_type = MatterType.ETHER\n\n self.context = None\n self.preference = None\n self.action = None\n self.intent = None\n\n self.runnable = False\n\n self.logger = Logger.get_logger(self.__class__.__name__)\n\n def get_shape(self):\n return None\n\n def run(self, mp_space_factors, mp_task_pipe):\n pass\n\n def __str__(self):\n return '%s(uuid=.%s)' % (type(self).__class__.__name__, str(self.uuid)[-8:])\n","sub_path":"Mesh/System/Entity/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"588477183","text":"# Copyright 2012 OpenStack Foundation\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport glob\nimport os\n\nimport lxml.etree\n\nfrom nova import test\n\nSCHEMAS = \"nova/api/openstack/compute/schemas\"\n\n\nclass RelaxNGSchemaTestCase(test.NoDBTestCase):\n \"\"\"various validation tasks for the RelaxNG schemas\n\n lxml.etree has no built-in way to validate an entire namespace\n (i.e., multiple RelaxNG schema files defining elements in the same\n namespace), so we define a few tests that should hopefully reduce\n the risk of an inconsistent namespace\n \"\"\"\n\n def _load_schema(self, schemafile):\n return lxml.etree.RelaxNG(lxml.etree.parse(schemafile))\n\n def _load_test_cases(self, path):\n \"\"\"load test cases from the given path.\"\"\"\n rv = dict(valid=[], invalid=[])\n path = os.path.join(os.path.dirname(__file__), path)\n for ctype in rv.keys():\n for cfile in glob.glob(os.path.join(path, ctype, \"*.xml\")):\n rv[ctype].append(lxml.etree.parse(cfile))\n return rv\n\n def _validate_schema(self, schemafile):\n \"\"\"validate a single RelaxNG schema file.\"\"\"\n try:\n self._load_schema(schemafile)\n except lxml.etree.RelaxNGParseError as err:\n self.fail(\"%s is not a valid RelaxNG schema: %s\" %\n (schemafile, err))\n\n def _api_versions(self):\n \"\"\"get a list of API versions.\"\"\"\n return [''] + [os.path.basename(v)\n for v in glob.glob(os.path.join(SCHEMAS, \"v*\"))]\n\n def _schema_files(self, api_version):\n return glob.glob(os.path.join(SCHEMAS, api_version, \"*.rng\"))\n\n def test_schema_validity(self):\n for api_version in self._api_versions():\n for schema in self._schema_files(api_version):\n self._validate_schema(schema)\n\n def test_schema_duplicate_elements(self):\n for api_version in self._api_versions():\n elements = dict()\n duplicates = dict()\n for schemafile in self._schema_files(api_version):\n schema = lxml.etree.parse(schemafile)\n fname = os.path.basename(schemafile)\n if schema.getroot().tag != \"element\":\n # we don't do any sort of validation on grammars\n # yet\n continue\n el_name = schema.getroot().get(\"name\")\n if el_name in elements:\n duplicates.setdefault(el_name,\n [elements[el_name]]).append(fname)\n else:\n elements[el_name] = fname\n self.assertEqual(len(duplicates), 0,\n \"Duplicate element definitions found: %s\" %\n \"; \".join(\"%s in %s\" % dup\n for dup in duplicates.items()))\n\n def test_schema_explicit_cases(self):\n cases = {'v1.1/flavors.rng': self._load_test_cases(\"v1.1/flavors\"),\n 'v1.1/images.rng': self._load_test_cases(\"v1.1/images\"),\n 'v1.1/servers.rng': self._load_test_cases(\"v1.1/servers\")}\n\n for schemafile, caselists in cases.items():\n schema = self._load_schema(os.path.join(SCHEMAS, schemafile))\n for case in caselists['valid']:\n self.assertTrue(schema.validate(case),\n \"Schema validation failed against %s: %s\\n%s\" %\n (schemafile, schema.error_log, case))\n\n for case in caselists['invalid']:\n self.assertFalse(\n schema.validate(case),\n \"Schema validation succeeded unexpectedly against %s: %s\"\n \"\\n%s\" % (schemafile, schema.error_log, case))\n","sub_path":"nova/tests/unit/api/openstack/compute/schemas/test_schemas.py","file_name":"test_schemas.py","file_ext":"py","file_size_in_byte":4349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"413906199","text":"import pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n\ndata = []\nfor i in range(140, 149):\n data += pickle.load(open('data/local/experiment/hopper_restfoot_seed6_seg_target1/mp_rew_' + str(i) + '.pkl', 'rb'))\n\n\nx = []\ny = []\nfor d in data:\n x.append(d[0])\n y.append(d[1])\n\nx = np.array(x)\n\nplt.scatter(x[:,0], x[:, 1], c = y, alpha=0.3)\nplt.colorbar()\nplt.show()\n","sub_path":"examples/test_datacollection.py","file_name":"test_datacollection.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"295629994","text":"import os\r\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see issue #152\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\r\n\r\nimport sys\r\n\r\nfrom keras import backend as K\r\nfrom keras.applications import vgg16\r\nfrom keras.layers import Input, merge, BatchNormalization\r\nfrom keras.layers.convolutional import Conv2D, MaxPooling2D\r\nfrom keras.layers.core import Activation, Dense, Dropout, Flatten, Lambda\r\nfrom keras.models import Sequential, Model\r\nfrom keras.utils import np_utils\r\nfrom keras.callbacks import CSVLogger, ModelCheckpoint\r\n\r\nfrom sklearn.model_selection import train_test_split\r\nfrom random import shuffle\r\nfrom scipy.misc import imresize\r\nimport itertools\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\nimport logging\r\nfrom sklearn.utils import shuffle\r\n\r\nDATA_DIR = \"/home/rsilva/datasets/vqa/\"\r\nIMAGE_DIR = os.path.join(DATA_DIR,\"mscoco\")\r\nLOG_DIR = \"/home/rsilva/logs/\"\r\n\r\nlogging.basicConfig(level=logging.INFO,\r\n format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',\r\n datefmt='%m-%d %H:%M',\r\n filename=os.path.join(LOG_DIR, 'basic_siamese_batch_norm.log'),\r\n filemode='w')\r\nlogger = logging.getLogger(__name__)\r\n\r\ndef get_random_image(img_groups, group_names, gid):\r\n gname = group_names[gid]\r\n photos = img_groups[gname]\r\n pid = np.random.choice(np.arange(len(photos)), size=1)[0]\r\n pname = photos[pid]\r\n return pname\r\n\r\ndef criar_triplas(image_dir):\r\n data = pd.read_csv(lista_imagens, sep=\",\", header=0, names=[\"image_id\",\"filename\",\"category_id\"])\r\n img_groups = {}\r\n \r\n for index, row in data.iterrows():\r\n pid = row[\"filename\"]\r\n gid = row[\"category_id\"]\r\n \r\n if gid in img_groups:\r\n img_groups[gid].append(pid)\r\n else:\r\n img_groups[gid] = [pid]\r\n \r\n pos_triples, neg_triples = [], []\r\n #A triplas positivas são a combinação de imagens com a mesma categoria\r\n for key in img_groups.keys():\r\n triples = [(x[0], x[1], 1) \r\n for x in itertools.combinations(img_groups[key], 2)]\r\n pos_triples.extend(triples)\r\n # é necessário o mesmo número de exemplos negativos\r\n group_names = list(img_groups.keys())\r\n for i in range(len(pos_triples)):\r\n g1, g2 = np.random.choice(np.arange(len(group_names)), size=2, replace=False)\r\n left = get_random_image(img_groups, group_names, g1)\r\n right = get_random_image(img_groups, group_names, g2)\r\n neg_triples.append((left, right, 0))\r\n pos_triples.extend(neg_triples)\r\n shuffle(pos_triples)\r\n return pos_triples \r\ndef carregar_imagem(image_name):\r\n logging.debug(\"carragendo imagem : %s\" % image_name)\r\n if image_name not in image_cache:\r\n logging.debug(\"cache miss\")\r\n image = plt.imread(os.path.join(IMAGE_DIR, image_name)).astype(np.float32)\r\n image = imresize(image, (224, 224))\r\n image = np.divide(image, 256)\r\n image_cache[image_name] = image\r\n else:\r\n logging.debug(\"cache hit\")\r\n return image_cache[image_name]\r\n\r\ndef gerar_triplas_em_lote(image_triples, batch_size, shuffle=False):\r\n logging.info(\"Gerando triplas\")\r\n while True:\r\n \r\n # loop once per epoch\r\n if shuffle:\r\n indices = np.random.permutation(np.arange(len(image_triples)))\r\n else:\r\n indices = np.arange(len(image_triples))\r\n shuffled_triples = [image_triples[ix] for ix in indices]\r\n num_batches = len(shuffled_triples) // batch_size\r\n \r\n logging.info(\"%s batches of %s generated\" % (num_batches, batch_size))\r\n \r\n for bid in range(num_batches):\r\n # loop once per batch\r\n images_left, images_right, labels = [], [], []\r\n batch = shuffled_triples[bid * batch_size : (bid + 1) * batch_size]\r\n for i in range(batch_size):\r\n lhs, rhs, label = batch[i]\r\n images_left.append(carregar_imagem(lhs))\r\n images_right.append(carregar_imagem(rhs)) \r\n labels.append(label)\r\n Xlhs = np.array(images_left)\r\n Xrhs = np.array(images_right)\r\n Y = np_utils.to_categorical(np.array(labels), num_classes=2)\r\n yield ([Xlhs, Xrhs], Y)\r\n\r\ndef calcular_distancia(vecs, normalizar=False):\r\n x, y = vecs\r\n if normalizar:\r\n x = K.l2_normalize(x, axis=0)\r\n y = K.l2_normalize(x, axis=0)\r\n return K.prod(K.stack([x, y], axis=1), axis=1)\r\n\r\ndef formato_saida_distancia(shapes):\r\n return shapes[0]\r\n\r\ndef computar_precisao(predicoes, rotulos):\r\n return rotulos[predicoes.ravel() < 0.5].mean()\r\n\r\ndef criar_instancia_rede_neural(entrada):\r\n seq = Sequential()\r\n \r\n # CONV => RELU => POOL\r\n seq.add(Conv2D(20, kernel_size=5, padding=\"same\", input_shape=entrada))\r\n seq.add(Activation(\"relu\"))\r\n seq.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\r\n \r\n seq.add(BatchNormalization())\r\n\r\n # CONV => RELU => POOL\r\n seq.add(Conv2D(50, kernel_size=5, padding=\"same\"))\r\n seq.add(Activation(\"relu\"))\r\n seq.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\r\n \r\n seq.add(BatchNormalization())\r\n\r\n # Flatten => RELU\r\n seq.add(Flatten())\r\n seq.add(Dense(500))\r\n \r\n return seq\r\n\r\n####################### Inicio da Execucao #######################\r\n\r\nlogger.info(\"####################### Inicio da Execucao #######################\")\r\n\r\nlogging.info(\"Gerando triplas\")\r\nlista_imagens = os.path.join(DATA_DIR, 'train_2014_1k.csv')\r\ntriplas = criar_triplas(lista_imagens)\r\n\r\nlogging.debug(\"# triplas de imagens: %d\" % len(triplas))\r\n\r\nTAMANHO_LOTE = 64 \r\n\r\ndivisor = int(len(triplas) * 0.7)\r\ndados_treino, dados_teste = triplas[0:divisor], triplas[divisor:]\r\n\r\n################### Processamento das Imagens ##################\r\n\r\nformato_entrada = (224, 224, 3)\r\nrede_neural = criar_instancia_rede_neural(formato_entrada)\r\n\r\nimagem_esquerda = Input(shape=formato_entrada)\r\nimagem_direita = Input(shape=formato_entrada)\r\n\r\nvetor_saida_esquerda = rede_neural(imagem_esquerda)\r\nvetor_saida_direita = rede_neural(imagem_direita)\r\n\r\ndistancia = Lambda(calcular_distancia, \r\n output_shape=formato_saida_distancia)([vetor_saida_esquerda, vetor_saida_direita])\r\n\r\n############# Computando os vetorese de similaridade #############\r\n\r\nfc1 = Dense(128, kernel_initializer=\"glorot_uniform\")(distancia)\r\nfc1 = Dropout(0.2)(fc1)\r\nfc1 = Activation(\"relu\")(fc1)\r\n\r\npred = Dense(2, kernel_initializer=\"glorot_uniform\")(fc1)\r\npred = Activation(\"softmax\")(pred)\r\nmodel = Model(inputs=[imagem_esquerda, imagem_direita], outputs=pred)\r\n#model.summary()\r\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\r\n\r\nNUM_EPOCAS = 1 \r\n\r\nimage_cache = {}\r\nlote_de_treinamento = gerar_triplas_em_lote(dados_treino, TAMANHO_LOTE, shuffle=True)\r\nlote_de_validacao = gerar_triplas_em_lote(dados_teste, TAMANHO_LOTE, shuffle=False)\r\n\r\nnum_passos_treinamento = len(dados_treino) // NUM_EPOCAS\r\nnum_passos_validacao = len(dados_teste) // NUM_EPOCAS\r\n\r\ncsv_logger = CSVLogger(os.path.join(LOG_DIR, 'training_epochs_batch_norm.log'))\r\nmodel_checkpoint = ModelCheckpoint(\"models/best_batch_norm.hdf\", monitor='val_acc', verbose=1, save_best_only=True, mode='max')\r\n\r\ncallbacks_list = [csv_logger, model_checkpoint]\r\n\r\nhistorico = model.fit_generator(lote_de_treinamento,\r\n steps_per_epoch=num_passos_treinamento,\r\n epochs=NUM_EPOCAS,\r\n validation_data=lote_de_validacao,\r\n validation_steps=num_passos_validacao,\r\n callbacks=callbacks_list)\r\n\r\nlogging.info(\"Salvando o modelo em disco\")\r\n# serialize model to JSON\r\nmodel_json = model.to_json()\r\nwith open(\"models/vqa_batch_norm.json\", \"w\") as json_file:\r\n json_file.write(model_json)\r\n\r\n# serialize weights to HDF5\r\nmodel.save_weights(\"models/vqa_weights_batch_norm.h5\")\r\nlogging.info(\"Modelo salvo\")\r\n\r\nlogging.info(\"Finalizado\")\r\n","sub_path":"vqa_basic_bn.py","file_name":"vqa_basic_bn.py","file_ext":"py","file_size_in_byte":8092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"456597719","text":"__author__ = 'koohyh'\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndef main():\n\n regions_overlapping_up_regulated_genes = ['5:22000000-22250000', '1:167000000-167250000', '1:126500000-126750000',\n '12:71750000-72000000', '5:22250000-22500000']\n regions_overlapping_down_regulated_genes = ['1:194750000-195000000', '8:41000000-41250000', '1:173500000-173750000']\n\n hic_df = read_hic_data(\"/bi/group/sysgen/Hashem/ISP_3D/from_Cshilla/PCA_250kb_P5e-2_delta3sigma_with_scores.txt\",\n regions_overlapping_up_regulated_genes, regions_overlapping_down_regulated_genes)\n\ndef read_hic_data(hic_fname, up_regions, down_regions):\n \"\"\"\n To read the HiC data (from Cshill) and return it as a pandas data frame so that I can compare the z-scores\n and if needed more analysis\n :param hic_fname:\n :up_regions : a list containing ids of regions overlapping with our up-regulated genes\n :down_regions: a list containing ids of regions overlapping with our down-regulated genes.\n :return: hic_df\n \"\"\"\n df = pd.read_csv(hic_fname, header=False, engine='python', sep='\\t')\n\n z1_from_all_regions = df['Z1'].values\n z2_from_all_regions = df['Z2'].values\n Z_ratios_from_all_regions = np.array(np.log(z1_from_all_regions/z2_from_all_regions))\n\n z1_from_up_regions = df[ np.in1d(df['label'], up_regions)]['Z1']\n z2_from_up_regions = df[ np.in1d(df['label'], up_regions)]['Z2']\n z_ratio_from_up_regions = np.array(np.log(z1_from_up_regions/z2_from_up_regions))\n\n print(z_ratio_from_up_regions)\n\n z1_from_down_regions = df[ np.in1d(df['label'], down_regions)]['Z1']\n z2_from_down_regions = df[ np.in1d(df['label'], down_regions)]['Z2']\n z_ratio_from_down_regions = np.array(np.log(z1_from_down_regions/z2_from_down_regions))\n\n z_ratios = np.append(z_ratio_from_up_regions, z_ratio_from_down_regions)\n condition = np.append(['Up' for _ in range(len(z_ratio_from_up_regions))], [\"Down\" for _ in range(len(z_ratio_from_down_regions))])\n up_and_down_df = pd.DataFrame({'ZScore_Ratio':z_ratios, 'condition':condition})\n\n sns.set(style=\"whitegrid\",font_scale=1.5)\n f, (ax1, ax2) = plt.subplots(1, 2)\n ax1.set_xlabel('log(ratio(ZScores))')\n ax1.set_ylabel('Frequency')\n ax1.set_title('Comparison of ZSCores')\n sns.distplot(Z_ratios_from_all_regions, ax=ax1, color='red')\n sns.factorplot(data=up_and_down_df, y='ZScore_Ratio', x='condition', ax=ax2)\n ax2.set_title('Comparison of ZSCores Up and Down Regions')\n ax2.set_ylabel('log(ratio(ZScores))')\n ax2.set_xlabel('Condition')\n plt.grid()\n plt.show()\n\n\n #\n # z1 = df['Z1'].values\n # z2 = df['Z2'].values\n # sns.distplot(z1, color='red', label='Z1', bins=5)\n # sns.distplot(z2, color='blue', label='Z2', bins=5)\n # plt.legend(loc='upper right')\n # plt.show()\n # return(df)\n\nif __name__ == '__main__':\n main()\n","sub_path":"pyChIP/pyChIP/compare_zscores_from_HiC_data.py","file_name":"compare_zscores_from_HiC_data.py","file_ext":"py","file_size_in_byte":2982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"188996920","text":"import numpy as np\r\nfrom PIL import Image\r\nimport util\r\nimport cv2\r\nimport random\r\nimport pyclipper\r\nimport Polygon as plg\r\nimport tensorflow as tf\r\n\r\nctw_root_dir = './data/mtwi/'\r\nctw_train_data_dir = ctw_root_dir + 'train/text_image/'\r\nctw_train_gt_dir = ctw_root_dir + 'train/text_label_curve/'\r\nctw_test_data_dir = ctw_root_dir + 'test/text_image/'\r\nctw_test_gt_dir = ctw_root_dir + 'test/text_label_curve/'\r\n\r\nrandom.seed(123456)\r\n\r\ndef get_img(img_path):\r\n try:\r\n img = cv2.imread(img_path)\r\n img = img[:, :, [2, 1, 0]]\r\n except Exception as e:\r\n print(img_path)\r\n raise\r\n return img\r\n\r\n# #this is for polygon box label\r\n# def get_bboxes(img, gt_path):\r\n# h, w = img.shape[0:2]\r\n# lines = util.io.read_lines(gt_path)\r\n# bboxes = []\r\n# tags = []\r\n# for line in lines:\r\n# line = util.str.remove_all(line, '\\xef\\xbb\\xbf')\r\n# gt = util.str.split(line, ',')\r\n#\r\n# x1 = np.int(gt[0])\r\n# y1 = np.int(gt[1])\r\n#\r\n# bbox = [np.int(gt[i]) for i in range(4, 32)]\r\n# bbox = np.asarray(bbox) + ([x1 * 1.0, y1 * 1.0] * 14)\r\n# bbox = np.asarray(bbox) / ([w * 1.0, h * 1.0] * 14)\r\n#\r\n# bboxes.append(bbox)\r\n# tags.append(True)\r\n# return np.array(bboxes), tags\r\n\r\n\r\n##this is for quadra box label\r\ndef get_bboxes(img, gt_path):\r\n h, w = img.shape[0:2]\r\n lines = util.io.read_lines(gt_path)\r\n bboxes = []\r\n tags = []\r\n for line in lines:\r\n line = util.str.remove_all(line, '\\xef\\xbb\\xbf')\r\n gt = util.str.split(line, ',')\r\n\r\n bbox = [np.float(gt[i]) for i in range(8)]\r\n bbox = np.asarray(bbox) / ([w * 1.0, h * 1.0] * 4)\r\n\r\n bboxes.append(bbox)\r\n tags.append(True)\r\n return np.array(bboxes), tags\r\n\r\n\r\ndef random_horizontal_flip(imgs):\r\n if random.random() < 0.5:\r\n for i in range(len(imgs)):\r\n imgs[i] = np.flip(imgs[i], axis=1).copy()\r\n return imgs\r\n\r\ndef random_rotate(imgs):\r\n max_angle = 10\r\n angle = random.random() * 2 * max_angle - max_angle\r\n for i in range(len(imgs)):\r\n img = imgs[i]\r\n w, h = img.shape[:2]\r\n rotation_matrix = cv2.getRotationMatrix2D((h / 2, w / 2), angle, 1)\r\n img_rotation = cv2.warpAffine(img, rotation_matrix, (h, w))\r\n imgs[i] = img_rotation\r\n return imgs\r\n\r\ndef scale(img, long_size=2240):\r\n h, w = img.shape[0:2]\r\n scale = long_size * 1.0 / max(h, w)\r\n img = cv2.resize(img, dsize=None, fx=scale, fy=scale)\r\n return img\r\n\r\ndef random_scale(img, min_size):\r\n h, w = img.shape[0:2]\r\n if max(h, w) > 1280:\r\n scale = 1280.0 / max(h, w)\r\n img = cv2.resize(img, dsize=None, fx=scale, fy=scale)\r\n\r\n h, w = img.shape[0:2]\r\n random_scale = np.array([0.5, 1.0, 2.0, 3.0])\r\n scale = np.random.choice(random_scale)\r\n if min(h, w) * scale <= min_size:\r\n scale = (min_size + 10) * 1.0 / min(h, w)\r\n img = cv2.resize(img, dsize=None, fx=scale, fy=scale)\r\n return img\r\n\r\ndef random_crop(imgs, img_size):\r\n h, w = imgs[0].shape[0:2]\r\n th, tw = img_size\r\n if w == tw and h == th:\r\n return imgs\r\n \r\n if random.random() > 3.0 / 8.0 and np.max(imgs[1]) > 0:\r\n tl = np.min(np.where(imgs[1] > 0), axis = 1) - img_size\r\n tl[tl < 0] = 0\r\n br = np.max(np.where(imgs[1] > 0), axis = 1) - img_size\r\n br[br < 0] = 0\r\n br[0] = min(br[0], h - th)\r\n br[1] = min(br[1], w - tw)\r\n \r\n i = random.randint(tl[0], br[0])\r\n j = random.randint(tl[1], br[1])\r\n else:\r\n i = random.randint(0, h - th)\r\n j = random.randint(0, w - tw)\r\n \r\n # return i, j, th, tw\r\n for idx in range(len(imgs)):\r\n if len(imgs[idx].shape) == 3:\r\n imgs[idx] = imgs[idx][i:i + th, j:j + tw, :]\r\n else:\r\n imgs[idx] = imgs[idx][i:i + th, j:j + tw]\r\n return imgs\r\n\r\ndef dist(a, b):\r\n return np.sqrt(np.sum((a - b) ** 2))\r\n\r\ndef perimeter(bbox):\r\n peri = 0.0\r\n for i in range(bbox.shape[0]):\r\n peri += dist(bbox[i], bbox[(i + 1) % bbox.shape[0]])\r\n return peri\r\n\r\ndef shrink(bboxes, rate, max_shr=20):\r\n rate = rate * rate\r\n shrinked_bboxes = []\r\n for bbox in bboxes:\r\n area = plg.Polygon(bbox).area()\r\n peri = perimeter(bbox)\r\n\r\n pco = pyclipper.PyclipperOffset()\r\n pco.AddPath(bbox, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON)\r\n offset = min((int)(area * (1 - rate) / (peri + 0.001) + 0.5), max_shr)\r\n \r\n shrinked_bbox = pco.Execute(-offset)\r\n if len(shrinked_bbox) == 0:\r\n shrinked_bboxes.append(bbox)\r\n continue\r\n \r\n shrinked_bbox = np.array(shrinked_bbox[0])\r\n if shrinked_bbox.shape[0] <= 2:\r\n shrinked_bboxes.append(bbox)\r\n continue\r\n \r\n shrinked_bboxes.append(shrinked_bbox)\r\n \r\n return np.array(shrinked_bboxes)\r\n\r\nclass CTW1500Loader():\r\n def __init__(self, is_transform=False, img_size=None, kernel_num=7, min_scale=0.4):\r\n self.is_transform = is_transform\r\n \r\n self.img_size = img_size if (img_size is None or isinstance(img_size, tuple)) else (img_size, img_size)\r\n self.kernel_num = kernel_num\r\n self.min_scale = min_scale\r\n\r\n data_dirs = [ctw_train_data_dir]\r\n gt_dirs = [ctw_train_gt_dir]\r\n \r\n self.img_paths = []\r\n self.gt_paths = []\r\n\r\n for data_dir, gt_dir in zip(data_dirs, gt_dirs):\r\n img_names = util.io.ls(data_dir, '.jpg')\r\n img_names.extend(util.io.ls(data_dir, '.png'))\r\n # img_names.extend(util.io.ls(data_dir, '.gif'))\r\n\r\n img_paths = []\r\n gt_paths = []\r\n for idx, img_name in enumerate(img_names):\r\n img_path = data_dir + img_name\r\n img_paths.append(img_path)\r\n\r\n gt_name = img_name.split('.jpg')[0] + '.txt'\r\n gt_path = gt_dir + gt_name\r\n gt_paths.append(gt_path)\r\n\r\n self.img_paths.extend(img_paths)\r\n self.gt_paths.extend(gt_paths)\r\n \r\n\r\n def __len__(self):\r\n return len(self.img_paths)\r\n\r\n def __getitem__(self, index):\r\n img_path = self.img_paths[index]\r\n gt_path = self.gt_paths[index]\r\n\r\n img = get_img(img_path)\r\n bboxes, tags = get_bboxes(img, gt_path)\r\n \r\n if self.is_transform:\r\n img = random_scale(img, self.img_size[0])\r\n\r\n gt_text = np.zeros(img.shape[0:2], dtype='uint8')\r\n training_mask = np.ones(img.shape[0:2], dtype='uint8')\r\n if bboxes.shape[0] > 0:\r\n #bboxes = np.reshape(bboxes * ([img.shape[1], img.shape[0]] * 14), (bboxes.shape[0], bboxes.shape[1] / 2, 2)).astype('np.int32')\r\n #bboxes = bboxes * ([img.shape[1], img.shape[0]] * 14)\r\n bboxes = bboxes * ([img.shape[1], img.shape[0]] * 4)\r\n bboxes = bboxes.reshape((bboxes.shape[0], np.int(bboxes.shape[1] / 2), 2)).astype('int32')\r\n for i in range(bboxes.shape[0]):\r\n cv2.drawContours(gt_text, [bboxes[i]], -1, i + 1, -1)\r\n if not tags[i]:\r\n cv2.drawContours(training_mask, [bboxes[i]], -1, 0, -1)\r\n \r\n gt_kernals = []\r\n for i in range(1, self.kernel_num):\r\n rate = 1.0 - (1.0 - self.min_scale) / (self.kernel_num - 1) * i\r\n gt_kernal = np.zeros(img.shape[0:2], dtype='uint8')\r\n kernal_bboxes = shrink(bboxes, rate)\r\n for i in range(bboxes.shape[0]):\r\n cv2.drawContours(gt_kernal, [kernal_bboxes[i]], -1, 1, -1)\r\n gt_kernals.append(gt_kernal)\r\n\r\n if self.is_transform:\r\n imgs = [img, gt_text, training_mask]\r\n imgs.extend(gt_kernals)\r\n\r\n imgs = random_horizontal_flip(imgs)\r\n imgs = random_rotate(imgs)\r\n imgs = random_crop(imgs, self.img_size)\r\n\r\n img, gt_text, training_mask, gt_kernals = imgs[0], imgs[1], imgs[2], imgs[3:]\r\n \r\n gt_text[gt_text > 0] = 1\r\n gt_kernals = np.array(gt_kernals)\r\n \r\n if self.is_transform:\r\n img = (img / 255.).astype('float32')\r\n img = tf.image.random_brightness(img, 32.0/255)\r\n img = tf.image.random_saturation(img, 0.5, 1.5)\r\n\r\n mean = tf.constant([0.485, 0.456, 0.406])\r\n std = tf.constant([0.229, 0.224, 0.225])\r\n img = (img - mean) / std\r\n\r\n gt_text = tf.convert_to_tensor(gt_text, dtype=tf.float32)\r\n gt_kernals = tf.convert_to_tensor(gt_kernals, dtype=tf.float32)\r\n training_mask = tf.convert_to_tensor(training_mask, dtype=tf.float32)\r\n\r\n return img, gt_text, gt_kernals, training_mask\r\n \r\ndef ctw_train_loader(dataset, batch_size, shuffle=True, drop_last=True): # shuffle, drop_last 的判断省略\r\n data_length = len(dataset)\r\n num_iter = data_length // batch_size\r\n shf = np.arange(data_length)\r\n np.random.shuffle(shf)\r\n for i in range(num_iter):\r\n imgs, gt_texts, gt_kernals, training_masks = [], [], [], []\r\n for j in range(batch_size):\r\n sample = dataset[shf[i*batch_size+j]]\r\n #imgs.append(tf.transpose(sample[0],(2,0,1)))\r\n imgs.append(sample[0])\r\n gt_texts.append(sample[1])\r\n gt_kernals.append(sample[2])\r\n #gt_kernals.append(tf.transpose(sample[2],(1,2,0)))\r\n training_masks.append(sample[3])\r\n imgs = tf.stack(imgs, 0)\r\n gt_texts = tf.stack(gt_texts, 0)\r\n gt_kernals = tf.stack(gt_kernals, 0)\r\n training_masks = tf.stack(training_masks, 0)\r\n yield imgs, gt_texts, gt_kernals, training_masks, data_length","sub_path":"dataset/mtwi_loader.py","file_name":"mtwi_loader.py","file_ext":"py","file_size_in_byte":9732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"292457087","text":"import socket\r\nimport json, types,string\r\nHOST = '127.0.0.1'\r\nPORT = 7000\r\n\r\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\ns.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\ns.bind((HOST, PORT))\r\ns.listen(5)\r\n\r\nprint('server start at: %s:%s' % (HOST, PORT))\r\nprint('wait for connection...')\r\n\r\nwhile True:\r\n conn, addr = s.accept()\r\n print('connected by ' + str(addr))\r\n\r\n while True:\r\n indata = conn.recv(1024)\r\n if len(indata) == 0: # connection closed\r\n conn.close()\r\n print('client closed connection.')\r\n break\r\n jdata = json.loads(indata)\r\n print (\"Receive jdata from '%r'\" %(jdata))\r\n #print('recv: ' + indata.decode())\r\n\r\n outdata = 'echo ' + indata.decode()\r\n conn.send(outdata.encode())\r\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"442278405","text":"# -*- coding: utf-8 -*-\n'''\nCreated on 02.04.2015\n\n@author: Andreas\n'''\n\nimport sys\nimport codecs\nimport logging\nfrom nltk.util import ngrams\nfrom nltk.tag import pos_tag\nfrom nltk.tokenize import word_tokenize\nfrom config import config\nfrom config.config import word_ngram_prefix,character_ngram_prefix, pos_tag_prefix\nfrom config.config import fv_basis\n\nlogger = logging.getLogger(__name__)\n\ntweets = [] # a list of all tweets (String, not Tweet object)\ntokens = set() # a set of all tokens in the svm data\n\ndef generate_fv_basis(fp):\n global tweets,tokens\n extract_tweets_and_tokens(fp)\n create_feature_vector_basis_file()\n \"\"\" cleanup \"\"\"\n tweets = []\n tokens = set()\n \ndef create_feature_vector_basis_file():\n add_word_ngrams(5,4,3,2)\n add_char_ngrams(6,5,4,3,2)\n add_pos_categories()\n\ndef remove_unavailable_tweets(fpin,fpout,train_data_limit=0):\n \"\"\"\n Cleans an input file of all lines with \"Not Available\" and writes a new file containing only all other lines.\n \n Keyword arguments:\n train_data_limit -- specifies how man tweets (lines) the output file will contain. \n A value of 0 (zero) equals all tweets (lines).\n \"\"\"\n fin = codecs.open(fpin, 'r', \"utf-8\")\n fout = codecs.open(fpout,'w', \"utf-8\")\n \n if train_data_limit == 0: train_data_limit = sys.maxint\n counter = 0\n for line in fin: \n if counter < train_data_limit:\n tmp = line.rstrip().split(\"\\t\")\n if tmp[3] != \"Not Available\":\n fout.write(line)\n counter += 1 \n fin.close()\n fout.close()\n \ndef extract_tweets_and_tokens(fp):\n global tweets\n global tokens\n f = codecs.open(fp, 'r', \"utf-8\")\n for i,line in enumerate(f):\n if i= thresholds[i]:\n f.write(word_ngram_prefix+\" \".join(key)+\"\\n\")\n logger.debug(word_ngram_prefix+\" \".join(key))\n f.close()\n\ndef add_char_ngrams(uni_threshold=500,bi_threshold=300,tri_threshold=150,four_threshold=100,five_threshold=50):\n \"\"\"Writes a file containing all character-1-5-grams above or equal to a certain threshold. \n Thresholds can be defined individually. Based on the data of the global variable \"tweets\".\n\n Keyword arguments:\n uni_threshold -- character unigram occurence threshold necessary to be included in the output file\n bi_threshold -- ...\n \"\"\"\n uni, bi, tri, four, five = ({},{},{},{},{})\n ngram_list = [uni,bi,tri,four,five]\n thresholds = [uni_threshold,bi_threshold,tri_threshold,four_threshold,five_threshold]\n global tokens\n \n # generate char_ngrams and save them in the respective dictionaries\n for token in tokens:\n for n in range (1,6):\n tmp = ngrams(token,n)\n for charseq in tmp:\n if charseq in ngram_list[n-1]:\n ngram_list[n-1][charseq] += 1\n else:\n ngram_list[n-1][charseq] = 1\n \n # print dictionaries to file\n f = codecs.open(fv_basis, 'a', \"utf-8\")\n for i, dic in enumerate(ngram_list):\n for key in sorted(dic):\n if dic[key] >= thresholds[i]:\n f.write(character_ngram_prefix+\"\".join(key)+\"\\n\")\n logger.debug(character_ngram_prefix+\"\".join(key))\n f.close()\n\ndef add_pos_categories():\n global tweets\n pos_tags = set()\n for tweet in tweets: \n tweet_pos_tagged = pos_tag(word_tokenize(tweet))\n for pair in tweet_pos_tagged:\n pos_tags.add(pair[1])\n # print dictionaries to file\n f = codecs.open(fv_basis, 'a', \"utf-8\")\n for item in pos_tags:\n f.write(pos_tag_prefix+item+\"\\n\")\n logger.debug(pos_tag_prefix+item)\n f.close()","sub_path":"src/preprocessing/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":4778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"48926796","text":"import xlsxwriter\nimport datetime\n\n\nclass PortfolioExporter(object):\n\n def __init__(self, longs, shorts):\n self.workbook = None\n self.longs = longs\n self.shorts = shorts\n\n def export(self, analyst, direction):\n filename = \"aim best ideas {} {}.xlsx\".format(analyst, direction)\n output_path = \"/var/www/output/{}\".format(filename)\n self.workbook = xlsxwriter.Workbook(output_path)\n try:\n self.__write_headers('Sheet1')\n self.__write_data('Sheet1', direction, analyst)\n except Exception as e:\n print(str(e))\n finally:\n self.workbook.close()\n return output_path, filename\n\n def __write_headers(self, sheet):\n worksheet = self.workbook.add_worksheet(sheet)\n merge_format = self.workbook.add_format({'bold': 1, 'align': 'center', 'valign': 'vcenter', 'border': 1})\n worksheet.write('A1', 'Portfolio Name', merge_format)\n worksheet.write('B1', 'Security ', merge_format)\n worksheet.write('C1', 'Weight', merge_format)\n worksheet.write('D1', 'Date', merge_format)\n worksheet.write('E1', 'Reason For Change', merge_format)\n worksheet.write('F1', 'CDE Weight', merge_format)\n worksheet.write('G1', 'CDE Portfolio Name', merge_format)\n\n def __write_data(self, sheet, direction, analyst):\n worksheet = self.workbook.get_worksheet_by_name(sheet)\n percentage_format = self.workbook.add_format()\n percentage_format.set_num_format(0x0a)\n count = 2\n\n if direction == 'long':\n for stock, (weight, rfc) in self.longs.items():\n worksheet.write('A{}'.format(count), 'AIM BEST IDEAS {} LONG'.format(analyst))\n worksheet.write('B{}'.format(count), stock)\n worksheet.write('C{}'.format(count), weight*100)\n now = datetime.datetime.now()\n worksheet.write('D{}'.format(count), now.strftime('%m/%d/%y'))\n worksheet.write('E{}'.format(count), rfc)\n worksheet.write('F{}'.format(count), weight*100)\n worksheet.write('G{}'.format(count), 'AIM BEST IDEAS {} LONG'.format(analyst))\n count += 1\n elif direction == 'short':\n for stock, (weight, rfc) in self.shorts.items():\n worksheet.write('A{}'.format(count), 'AIM BEST IDEAS {} SHORT'.format(analyst))\n worksheet.write('B{}'.format(count), stock)\n worksheet.write('C{}'.format(count), -weight*100)\n now = datetime.datetime.now()\n worksheet.write('D{}'.format(count), now.strftime('%m/%d/%y'))\n worksheet.write('E{}'.format(count), rfc)\n worksheet.write('F{}'.format(count), -weight*100)\n worksheet.write('G{}'.format(count), 'AIM BEST IDEAS {} SHORT'.format(analyst))\n count += 1\n\n","sub_path":"exporter/portfolio/portfolio_exporter.py","file_name":"portfolio_exporter.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"428167706","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2016 NORDUnet A/S\n# Copyright (c) 2018 SUNET\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or\n# without modification, are permitted provided that the following\n# conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided\n# with the distribution.\n# 3. Neither the name of the NORDUnet nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\nimport json\nfrom typing import Any, Dict, Mapping, Optional\n\nfrom mock import patch\n\nfrom eduid_common.api.exceptions import ApiException\nfrom eduid_common.api.testing import EduidAPITestCase\n\nfrom eduid_webapp.personal_data.app import PersonalDataApp, pd_init_app\n\n\nclass PersonalDataTests(EduidAPITestCase):\n app: PersonalDataApp\n\n def setUp(self):\n super(PersonalDataTests, self).setUp(copy_user_to_private=True)\n\n def load_app(self, config: Mapping[str, Any]) -> PersonalDataApp:\n \"\"\"\n Called from the parent class, so we can provide the appropriate flask\n app for this test case.\n \"\"\"\n return pd_init_app('testing', config)\n\n def update_config(self, config: Dict[str, Any]) -> Dict[str, Any]:\n config.update(\n {\n 'available_languages': {'en': 'English', 'sv': 'Svenska'},\n 'msg_broker_url': 'amqp://dummy',\n 'am_broker_url': 'amqp://dummy',\n 'celery_config': {'result_backend': 'amqp', 'task_serializer': 'json'},\n }\n )\n return config\n\n # parameterized test methods\n\n def _get_user(self, eppn: Optional[str] = None):\n \"\"\"\n Send a GET request to get the personal data of a user\n\n :param eppn: the eppn of the user\n \"\"\"\n response = self.browser.get('/user')\n self.assertEqual(response.status_code, 302) # Redirect to token service\n\n eppn = eppn or self.test_user_data['eduPersonPrincipalName']\n with self.session_cookie(self.browser, eppn) as client:\n response2 = client.get('/user')\n\n return json.loads(response2.data)\n\n def _get_user_all_data(self, eppn: Optional[str] = None):\n \"\"\"\n Send a GET request to get all the data of a user\n\n :param eppn: the eppn of the user\n \"\"\"\n response = self.browser.get('/all-user-data')\n self.assertEqual(response.status_code, 302) # Redirect to token service\n\n eppn = eppn or self.test_user_data['eduPersonPrincipalName']\n with self.session_cookie(self.browser, eppn) as client:\n response2 = client.get('/all-user-data')\n\n return json.loads(response2.data)\n\n @patch('eduid_common.api.am.AmRelay.request_user_sync')\n def _post_user(self, mock_request_user_sync: Any, mod_data: Optional[dict] = None):\n \"\"\"\n POST personal data for some user\n\n :param eppn: the eppn of the user\n \"\"\"\n mock_request_user_sync.side_effect = self.request_user_sync\n eppn = self.test_user_data['eduPersonPrincipalName']\n with self.session_cookie(self.browser, eppn) as client:\n with self.app.test_request_context():\n with client.session_transaction() as sess:\n data = {\n 'given_name': 'Peter',\n 'surname': 'Johnson',\n 'display_name': 'Peter Johnson',\n 'language': 'en',\n 'csrf_token': sess.get_csrf_token(),\n }\n if mod_data:\n data.update(mod_data)\n response = client.post('/user', data=json.dumps(data), content_type=self.content_type_json)\n return json.loads(response.data)\n\n def _get_user_nins(self, eppn: Optional[str] = None):\n \"\"\"\n GET a list of all the nins of some user\n\n :param eppn: the eppn of the user\n \"\"\"\n response = self.browser.get('/nins')\n self.assertEqual(response.status_code, 302) # Redirect to token service\n\n eppn = eppn or self.test_user_data['eduPersonPrincipalName']\n with self.session_cookie(self.browser, eppn) as client:\n response2 = client.get('/nins')\n\n return json.loads(response2.data)\n\n # actual test methods\n\n def test_get_user(self):\n user_data = self._get_user()\n self.assertEqual(user_data['type'], 'GET_PERSONAL_DATA_USER_SUCCESS')\n self.assertEqual(user_data['payload']['given_name'], 'John')\n self.assertEqual(user_data['payload']['surname'], 'Smith')\n self.assertEqual(user_data['payload']['display_name'], 'John Smith')\n self.assertEqual(user_data['payload']['language'], 'en')\n # Check that unwanted data is not serialized\n self.assertIsNotNone(self.test_user.to_dict().get('passwords'))\n self.assertIsNone(user_data['payload'].get('passwords'))\n\n def test_get_unknown_user(self):\n with self.assertRaises(ApiException):\n self._get_user(eppn='fooo-fooo')\n\n def test_get_user_all_data(self):\n user_data = self._get_user_all_data()\n self.assertEqual(user_data['type'], 'GET_PERSONAL_DATA_ALL_USER_DATA_SUCCESS')\n self.assertEqual(user_data['payload']['given_name'], 'John')\n self.assertEqual(user_data['payload']['surname'], 'Smith')\n self.assertEqual(user_data['payload']['display_name'], 'John Smith')\n self.assertEqual(user_data['payload']['language'], 'en')\n phones = user_data['payload']['phones']\n self.assertEqual(len(phones), 2)\n self.assertEqual(phones[0]['number'], u'+34609609609')\n self.assertTrue(phones[0]['verified'])\n nins = user_data['payload']['nins']\n self.assertEqual(len(nins), 2)\n self.assertEqual(nins[0]['number'], u'197801011234')\n self.assertTrue(nins[0]['verified'])\n emails = user_data['payload']['emails']\n self.assertEqual(len(emails), 2)\n self.assertEqual(emails[0]['email'], u'johnsmith@example.com')\n self.assertTrue(emails[0]['verified'])\n\n # Check that unwanted data is not serialized\n self.assertIsNotNone(self.test_user.to_dict().get('passwords'))\n self.assertIsNone(user_data['payload'].get('passwords'))\n\n def test_get_unknown_user_all_data(self):\n with self.assertRaises(ApiException):\n self._get_user_all_data(eppn='fooo-fooo')\n\n def test_post_user(self):\n resp_data = self._post_user()\n self.assertEqual(resp_data['type'], 'POST_PERSONAL_DATA_USER_SUCCESS')\n self.assertEqual(resp_data['payload']['surname'], 'Johnson')\n self.assertEqual(resp_data['payload']['given_name'], 'Peter')\n self.assertEqual(resp_data['payload']['display_name'], 'Peter Johnson')\n self.assertEqual(resp_data['payload']['language'], 'en')\n\n def test_post_user_bad_csrf(self):\n resp_data = self._post_user(mod_data={'csrf_token': 'wrong-token'})\n self.assertEqual(resp_data['type'], 'POST_PERSONAL_DATA_USER_FAIL')\n self.assertEqual(resp_data['payload']['error']['csrf_token'], ['CSRF failed to validate'])\n\n def test_post_user_no_given_name(self):\n resp_data = self._post_user(mod_data={'given_name': ''})\n self.assertEqual(resp_data['type'], 'POST_PERSONAL_DATA_USER_FAIL')\n self.assertEqual(resp_data['payload']['error']['given_name'], ['pdata.field_required'])\n\n def test_post_user_blank_given_name(self):\n resp_data = self._post_user(mod_data={'given_name': ' '})\n self.assertEqual(resp_data['type'], 'POST_PERSONAL_DATA_USER_FAIL')\n self.assertEqual(resp_data['payload']['error']['given_name'], ['pdata.field_required'])\n\n def test_post_user_no_surname(self):\n resp_data = self._post_user(mod_data={'surname': ''})\n self.assertEqual(resp_data['type'], 'POST_PERSONAL_DATA_USER_FAIL')\n self.assertEqual(resp_data['payload']['error']['surname'], ['pdata.field_required'])\n\n def test_post_user_blank_surname(self):\n resp_data = self._post_user(mod_data={'surname': ' '})\n self.assertEqual(resp_data['type'], 'POST_PERSONAL_DATA_USER_FAIL')\n self.assertEqual(resp_data['payload']['error']['surname'], ['pdata.field_required'])\n\n def test_post_user_no_display_name(self):\n resp_data = self._post_user(mod_data={'display_name': ''})\n self.assertEqual(resp_data['type'], 'POST_PERSONAL_DATA_USER_FAIL')\n self.assertEqual(resp_data['payload']['error']['display_name'], ['pdata.field_required'])\n\n def test_post_user_no_language(self):\n resp_data = self._post_user(mod_data={'language': ''})\n self.assertEqual(resp_data['type'], 'POST_PERSONAL_DATA_USER_FAIL')\n self.assertEqual(resp_data['payload']['error']['language'], [\"Language '' is not available\"])\n\n def test_post_user_unknown_language(self):\n resp_data = self._post_user(mod_data={'language': 'es'})\n self.assertEqual(resp_data['type'], 'POST_PERSONAL_DATA_USER_FAIL')\n self.assertEqual(resp_data['payload']['error']['language'], [\"Language 'es' is not available\"])\n\n def test_get_user_nins(self):\n nin_data = self._get_user_nins()\n self.assertEqual(nin_data['type'], 'GET_PERSONAL_DATA_NINS_SUCCESS')\n self.assertEqual(nin_data['payload']['nins'][1]['number'], '197801011235')\n self.assertEqual(len(nin_data['payload']['nins']), 2)\n","sub_path":"src/eduid_webapp/personal_data/tests/test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":10627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"484545018","text":"import unittest.mock\nimport xml.etree.ElementTree as ET\nfrom broadsoft.requestobjects.UserThirdPartyVoiceMailSupportModifyRequest import UserThirdPartyVoiceMailSupportModifyRequest\n\n\nclass TestUserThirdPartyVoiceMailSupportModifyRequest(unittest.TestCase):\n def test_validate(self):\n u = UserThirdPartyVoiceMailSupportModifyRequest()\n with self.assertRaises(ValueError):\n u.validate()\n\n @unittest.mock.patch.object(UserThirdPartyVoiceMailSupportModifyRequest, 'validate')\n def test_build_command_xml_calls_validate(\n self,\n validate_patch\n ):\n u = UserThirdPartyVoiceMailSupportModifyRequest(sip_user_id='6175551212@broadsoft-dev.mit.edu')\n u.build_command_xml()\n self.assertTrue(validate_patch.called)\n\n def test_build_command_xml(self):\n self.maxDiff = None\n u = UserThirdPartyVoiceMailSupportModifyRequest(sip_user_id='6175551212@broadsoft-dev.mit.edu',\n is_active=True, busy_redirect_to_voice_mail=False,\n no_answer_redirect_to_voice_mail=True,\n server_selection='User Specific Mail Server',\n user_server='617-253-0000',\n mailbox_id_type='User Or Group Phone Number',\n no_answer_number_of_rings=3, always_redirect_to_voice_mail=False,\n out_of_primary_zone_redirect_to_voice_mail=True)\n target_xml = \\\n '' + \\\n '6175551212@broadsoft-dev.mit.edu' + \\\n 'true' + \\\n 'false' + \\\n 'true' + \\\n 'User Specific Mail Server' + \\\n '6172530000' + \\\n 'User Or Group Phone Number' + \\\n '3' +\\\n 'false' + \\\n 'true' + \\\n ''\n\n xml = u.to_xml()\n cmd = xml.findall('./command')[0]\n self.assertEqual(\n target_xml,\n ET.tostring(cmd).decode('utf-8')\n )\n\n # change the results to ensure no mix ups\n u = UserThirdPartyVoiceMailSupportModifyRequest(sip_user_id='6175551213@broadsoft-dev.mit.edu',\n is_active=False, busy_redirect_to_voice_mail=True,\n no_answer_redirect_to_voice_mail=False,\n server_selection='garbanzo',\n user_server='617-253-0001',\n mailbox_id_type='ham',\n no_answer_number_of_rings=4,\n always_redirect_to_voice_mail=True,\n out_of_primary_zone_redirect_to_voice_mail=False)\n target_xml = \\\n '' + \\\n '6175551213@broadsoft-dev.mit.edu' + \\\n 'false' + \\\n 'true' + \\\n 'false' + \\\n 'garbanzo' + \\\n '6172530001' + \\\n 'ham' + \\\n '4' + \\\n 'true' + \\\n 'false' + \\\n ''\n\n xml = u.to_xml()\n cmd = xml.findall('./command')[0]\n self.assertEqual(\n target_xml,\n ET.tostring(cmd).decode('utf-8')\n )\n","sub_path":"broadsoft/tests/requestobjects/test_UserThirdPartyVoiceMailSupportModifyRequest.py","file_name":"test_UserThirdPartyVoiceMailSupportModifyRequest.py","file_ext":"py","file_size_in_byte":4548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"524054721","text":"# There are 4 lanes on the bridge road and 1 to 4 bikes to control. There can\r\n# only be one moto per lane and they are always vertically aligned.\r\n\r\n# Each game turn, you can send a single instruction to every bike. Since the\r\n# bikes operate on the same frequency, they will all synchronize on the\r\n# commands you send them.\r\n\r\n# The possible commands are:\r\n# - SPEED to speed up by 1.\r\n# - SLOW to slow down by 1.\r\n# - JUMP to jump.\r\n# - WAIT to go straight on.\r\n# - UP to send all motorbikes one lane up.\r\n# - DOWN to send all motorbikes one lane down.\r\n\r\n# The starting speeds of the bikes are synced, and can be 0. After every game\r\n# turn, the bikes will move a number of squares equal to their current speed\r\n# across the X axis.\r\n\r\n# The UP and DOWN instructions will make the bikes move across the Y axis i\r\n# addition to the movement across the X axis (Y = 0 corresponds to the highest\r\n# lane). If a motorbike is prevented from moving up or down by the bridge's\r\n# guard rails, none of the bikes will move on the Y axis that turn.\r\n\r\n# When a motorbike goes in a straight line and does not jump, if there is a\r\n# hole between the current position and the next position (after the move),\r\n# then the motorbike is lost forever. For example, if X=2 and S=3, the next\r\n# position of the bike will have X=5: if there is a hole in X=3, X=4 or X=5,\r\n# the bike will be destroyed.\r\n\r\n# Going up or down will put you at risk of falling in any hole situated in the\r\n# black zone (consider the holes on the current and next lane):\r\n# - The mission is a success if the minimum amount of required bikes gets to\r\n# the far side of the bridge.\r\n# - You fail if too many motorbikes fall into holes.\r\n# - You fail if the motorbikes do not cross the entire bridge after 50 turns.\r\n\r\n\r\nfrom itertools import product\r\n\r\n\r\nM = int(input())\r\ninput()\r\nroad = [input() for _ in range(4)]\r\nend = len(road[0])\r\nACTIONS = ['SPEED', 'UP', 'DOWN', 'JUMP', 'SLOW']\r\n\r\nwhile 1:\r\n speed = int(input())\r\n bikes = [list(map(int, input().split())) for i in range(M)]\r\n heuristics = {k: 0 for k in product(ACTIONS, ACTIONS, ACTIONS, ACTIONS)}\r\n for k in heuristics:\r\n t_speed = speed\r\n t_alive = [b[:] for b in bikes if b[2]]\r\n x = t_alive[0][0]\r\n for action in k:\r\n if t_alive:\r\n if action == 'SPEED':\r\n t_speed += 1\r\n for _, y, a in t_alive:\r\n if '0' in road[y][x+1:min(end, x+t_speed+1)]:\r\n t_alive.remove([_, y, a])\r\n else:\r\n heuristics[k] += 1\r\n elif action == 'SLOW':\r\n t_speed -= 1\r\n if t_speed > 1:\r\n for _, y, a in t_alive:\r\n if '0' in road[y][x+1:min(end, x+t_speed+1)]:\r\n t_alive.remove([_, y, a])\r\n else:\r\n heuristics[k] += 1\r\n else:\r\n heuristics[k] -= 10\r\n elif action == 'UP':\r\n if t_alive[0][1]:\r\n for i, (_, y, a) in enumerate(t_alive):\r\n if '0' in road[y][x+1:min(end, x+t_speed)] + road[y-1][x+1:min(end, x+t_speed+1)]:\r\n t_alive.remove([_, y, a])\r\n else:\r\n t_alive[i] = [x, y-1, 1]\r\n heuristics[k] += 1\r\n else:\r\n action = 'JUMP'\r\n elif action == 'DOWN':\r\n if t_alive[-1][1] < len(road)-1:\r\n for i, (_, y, a) in enumerate(t_alive):\r\n if '0' in road[y][x+1:min(end, x+t_speed)] + road[y+1][x+1:min(end, x+t_speed+1)]:\r\n t_alive.remove([_, y, a])\r\n else:\r\n t_alive[i] = [x, y+1, 1]\r\n heuristics[k] += 1\r\n else:\r\n action = 'JUMP'\r\n elif action == 'JUMP':\r\n for _, y, a in t_alive:\r\n if x + t_speed < end and road[y][x+t_speed] == '0':\r\n t_alive.remove([_, y, a])\r\n else:\r\n heuristics[k] += 1\r\n x += t_speed\r\n \r\n best = max(heuristics, key=lambda k:(heuristics[k], -ACTIONS.index(k[0])))\r\n print(best[0])","sub_path":"CG/hard_the-bridge-episode-2.py","file_name":"hard_the-bridge-episode-2.py","file_ext":"py","file_size_in_byte":4591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"466141680","text":"print(\"Starting Py program\")\n\ndef f():\n x=1\n y=2\n if(x==1):\n t= x+y\n print(\"here\")\n return t\nx=1+3*100/2+f()\ny=x*100+10*3\nprint(\"x=\",x)\nprint(\"y=\",y)","sub_path":"hw4/hw2_testcase.py","file_name":"hw2_testcase.py","file_ext":"py","file_size_in_byte":174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"506465523","text":"import site\r\nimport socket\r\n\r\nif socket.gethostbyaddr(socket.gethostname())[0] == 'QFR1L0611.viola.local':\r\n site.addsitedir('/home/rk/pylib')\r\nelse:\r\n site.addsitedir(\"D:\\\\Analytics\\\\NetworkAnalytics\\\\trunk\\\\UserSpace\\\\Kelzenberg\\\\pylib\")\r\n\r\nimport mx.DateTime.Feasts as feasts\r\nimport matplotlib as mpl\r\nfrom datetime import date, datetime, timedelta\r\n#from scipy import sin\r\nimport matplotlib.pyplot as plt\r\nimport numpy\r\nfrom scipy import signal, convolve\r\nfrom matplotlib.dates import date2num, num2date\r\nfrom oracle_connect import get_oracle_cursor_rkna1\r\nfrom scipy import optimize\r\nimport xlwt\r\n\r\nmpl.rcParams['font.size'] = 8.0\r\nmpl.rcParams['figure.figsize'] = 12.69, 8.27\r\nmpl.rcParams['savefig.dpi'] = 300\r\nmpl.rcParams['pdf.compression'] = 3\r\nmpl.rcParams['pdf.fonttype'] = 42\r\n\r\nlbound = lambda p, x: 1e4 * numpy.sqrt(p - x) + 1e-3 * (p - x) if (x < p) else 0\r\nubound = lambda p, x: 1e4 * numpy.sqrt(x - p) + 1e-3 * (x - p) if (x > p) else 0\r\nbound = lambda p, x: lbound(p[0], x) + ubound(p[1], x)\r\nfixed = lambda p, x: bound((p, p), x)\r\n\r\n\r\nticketfilter = \"\"\"\r\nA_AUFTRAGSKLASSE = 'SK'\r\nand A_BEARBEITUNGSZUSTAND <> 'st'\r\nand a_orgetyp = 'P'\r\nand a_auftragsart = 'Aufgabe'\r\n\"\"\"\r\n\r\nlinear = lambda p, x: p[0]*(x - p[-1]) + p[1]\r\nsquared = lambda p, x: p[0]*(x - p[-1]) ** 2 + p[1]*(x - p[-1]) + p[2]\r\nsineline = lambda p, x: (p[0]*numpy.sin(2 * numpy.pi * (x - p[-1]) / p[1] + p[2]) + p[4]) * p[3]*(x - p[-1]) + p[5]\r\nexponential = lambda p, x: p[0]*p[1]**(x - p[-1]) + p[2]\r\n\r\n\r\ndef holiday_correction(dates, values, reduction):\r\n for i in range(len(dates)):\r\n if isinstance(dates[i], float):\r\n datum = num2date(dates[i])\r\n datum = datetime(datum.year, datum.month, datum.day)\r\n else:\r\n datum = dates[i]\r\n year = datum.year\r\n himmelfahrt = feasts.Himmelfahrt(year)\r\n himmelfahrt = datetime(year, himmelfahrt.month, himmelfahrt.day)\r\n karfreitag = feasts.Karfreitag(year)\r\n karfreitag = datetime(year, karfreitag.month, karfreitag.day)\r\n ostermontag = feasts.Ostermontag(year)\r\n ostermontag = datetime(year, ostermontag.month, ostermontag.day)\r\n fronleichnam = feasts.Fronleichnam(year)\r\n fronleichnam = datetime(year, fronleichnam.month, fronleichnam.day)\r\n pfingstmontag = feasts.Pfingstmontag(year)\r\n pfingstmontag = datetime(year, pfingstmontag.month, pfingstmontag.day)\r\n feiertage = [datetime(year, 1, 1), datetime(year, 5, 1), datetime(year, 10, 3),\r\n datetime(year, 11, 1), datetime(year, 10, 31), #allerheiligen, reformationstag .. .\r\n datetime(year, 12, 25), datetime(year, 12, 26),\r\n datetime(year, 12, 24), datetime(year, 12, 31),\r\n himmelfahrt, fronleichnam, karfreitag, ostermontag, pfingstmontag]\r\n #feiertage = [x for x in feiertage if x.weekday() not in (5, 6)]\r\n if set([datum + timedelta(days=x) for x in range(5)]).intersection(set(feiertage)):\r\n values[i] = values[i]*reduction\r\n\r\n\r\ndef getdesc(p):\r\n if len(p) != 7:\r\n return \"\"\r\n phase = num2date(p[-1] - p[2] / 2 / numpy.pi)\r\n parameters = \"Offset: {:d}, Base: {:d}, Amplitude {:d}: Increase: {:.4}/day, Phase: {}, Period: {:d} days\"\r\n return parameters.format(int(round(p[5])), int(round(p[4])), int(round(p[0])), p[3], phase, int(round(p[1])))\r\n\r\nkai = {}\r\nkai[\"dienstkategorie\"] = 'KAI'\r\nkai[\"holidaycorrection\"] = 1#0.85\r\nkai[\"startdate\"] = datetime.now() - timedelta(days=600)\r\nkai[\"tickets\"] = [[\"plotstart\", \"plotend\"],\r\n [datetime.now() - timedelta(days=600), datetime.now()]\r\n ]\r\nkai[\"fitlines\"] = [\r\n [\"fitfunc\", \"fitstart\", \"fitend\", \"plotstart\", \"plotend\", \"linename\"],\r\n [sineline, [100, 300, 0, 0, 100, 0], datetime(2010, 4, 10), datetime(2011, 10, 4),\r\n datetime(2010, 4, 10), datetime(2012, 2, 1), \"forecast\", \"r\", 0]\r\n ]\r\nkai[\"fitmods\"] = [\r\n [\"linename\", \"fitline\", \"parmod\"],\r\n ]\r\n\r\nkav = {}\r\nkav[\"dienstkategorie\"] = 'KAV'\r\nkav[\"holidaycorrection\"] = 1#0.85\r\nkav[\"startdate\"] = datetime.now() - timedelta(days=600)\r\nkav[\"tickets\"] = [[\"plotstart\", \"plotend\"],\r\n [datetime.now() - timedelta(days=600), datetime.now()]\r\n ]\r\nkav[\"fitlines\"] = [\r\n [\"fitfunc\", \"fitstart\", \"fitend\", \"plotstart\", \"plotend\", \"linename\", \"color\", \"errors\"],\r\n [sineline, [50, 300, 0, 0, 100, 0], datetime(2010, 4, 10), datetime(2011, 10, 4),\r\n datetime(2010, 4, 10), datetime(2012, 2, 1), \"forecast\", \"r\", 0]\r\n ]\r\nkav[\"fitmods\"] = [\r\n [\"linename\", \"fitline\", \"parmod\"],\r\n ]\r\n\r\nhdw = {}\r\nhdw[\"dienstkategorie\"] = 'HDW'\r\nhdw[\"holidaycorrection\"] = 1#0.90\r\nhdw[\"startdate\"] = datetime.now() - timedelta(days=600)\r\nhdw[\"tickets\"] = [[\"plotstart\", \"plotend\"],\r\n [datetime.now() - timedelta(days=600), datetime.now()]\r\n ]\r\nhdw[\"fitlines\"] = [\r\n [\"fitfunc\", \"fitstart\", \"fitend\", \"plotstart\", \"plotend\", \"linename\"],\r\n [sineline, [200, 300, 0, 1, 200, 0], datetime(2010, 4, 10), datetime(2011, 10, 10),\r\n datetime(2010, 4, 10), datetime(2011, 9, 5), \"forecast\", \"r\", 0]\r\n ]\r\nhdw[\"fitmods\"] = [\r\n [\"linename\", \"fitline\", \"parmod\"],\r\n [\"forecast\", \"forecast\", [0, 0, 0, -0.001, 0, 20, 0], datetime(2011, 9, 5), datetime(2012, 2, 1), \"r\", 50],\r\n ]\r\n\r\nkad = {}\r\nkad[\"dienstkategorie\"] = 'KAD'\r\nkad[\"holidaycorrection\"] = 1#0.80\r\nkad[\"startdate\"] = datetime.now() - timedelta(days=1500)\r\nkad[\"tickets\"] = [[\"plotstart\", \"plotend\"],\r\n [datetime.now() - timedelta(days=600), datetime.now()]]\r\nkad[\"fitlines\"] = [\r\n [\"fitfunc\", \"fitstart\", \"fitend\", \"plotstart\", \"plotend\", \"linename\", \"color\"],\r\n #[linear, [1.,1.], datetime.now()-timedelta(days=700), datetime(2011,6,19),\r\n # datetime.now()-timedelta(days=700), datetime(2011,6,19), \"pre SMB 1 year linear\", \"r\", 0],\r\n [sineline, [400, 350, 0, 1, 1000, 0], datetime(2011, 11, 14) - timedelta(days=700), datetime(2011, 6, 19),\r\n datetime.now() - timedelta(days=600), datetime(2011, 6, 19), \"pre SMB 1 year sine\", \"r\", 0],\r\n #[linear, [1.,1.], datetime(2011,6,19)-timedelta(days=90), datetime(2011,6,19),\r\n # datetime(2011,6,19)-timedelta(days=90), datetime(2011,6,19), \"pre SMB 90 days\", \"m\", 0]\r\n ]\r\nkad[\"fitmods\"] = [\r\n [\"linename\", \"fitline\", \"parmod\", \"plotstart\", \"plotend\", \"color\"],\r\n #[\"post SMB 1 year linear\", \"pre SMB 1 year linear\", [0,500,90], datetime(2011,9,19),datetime(2012,1,1), \"r\", 0],\r\n [\"post SMB 1 year sine\", \"pre SMB 1 year sine\", [0, 0, 0, 0, 0, 650, 0], datetime(2011, 6, 19), datetime(2012, 2, 1), \"r\", 100],\r\n #[\"post SMB 1 year sine, slow\", \"pre SMB 1 year sine\", [0,0,0,-0.01,0,600,0], datetime(2011,6,19),datetime(2012,1,1), \"r\",100],\r\n #[\"post SMB 90 days\", \"pre SMB 90 days\", [0,600,0], datetime(2011,6,19),datetime(2012,1,1), \"m\", 0]\r\n ]\r\nkaa = {}\r\nkaa[\"dienstkategorie\"] = 'KAA'\r\nkaa[\"holidaycorrection\"] = 1#0.80\r\nkaa[\"startdate\"] = datetime.now() - timedelta(days=1300)\r\nkaa[\"tickets\"] = [[\"plotstart\", \"plotend\"],\r\n [datetime.now() - timedelta(days=300), datetime.now()]\r\n ]\r\nkaa[\"fitlines\"] = [\r\n [\"fitfunc\", \"fitstart\", \"fitend\", \"plotstart\", \"plotend\", \"linename\"],\r\n [linear, [1., 1.], datetime(2011, 7, 12), datetime(2011, 11, 30),\r\n datetime(2011, 7, 12), datetime.now(), \"DAB+\", \"m\", 0],\r\n [sineline, [150, 350, 100, 0, 1000, 0], datetime(2011, 11, 14) - timedelta(days=1200), datetime(2011, 6, 19),\r\n datetime.now() - timedelta(days=600), datetime(2011, 6, 19), \"pre SMB\", \"r\", 0],\r\n ]\r\nkaa[\"fitmods\"] = [\r\n [\"linename\", \"fitline\", \"parmod\", \"plotstart\", \"plotend\"],\r\n [\"post SMB forecast\", \"pre SMB\", [1.5, 0, 200, 0, 0, 600, 0], datetime(2011, 6, 19), datetime(2011, 6, 20), \"r\", 100],\r\n ]\r\ndabstart = date(2011, 7, 17)\r\nkaa[\"extras\"] = [\r\n [\"linename\", \"color\", \"fitadd\", \"fitmodadd\", \"dates\", \"values\"],\r\n [\"DAB forecast\", \"red\", \"\", \"post SMB forecast\", [dabstart + timedelta(i * 7) for i in range(24)], [2.7 ** (-x / 10.) * 300 + 25 for x in xrange(24)]]\r\n ]\r\n\r\n#[1.5, 0, 200, 0, 0, 600, 00],\r\n#[2.7 ** (-x / 10.) * 300 + 25 for x in xrange(25)]]\r\n#[x ** 2 / 1.5 for x in xrange(-25, -1)]\r\n#[0, 0, 0, 0, 0, 500, 00],\r\n\r\nnet = {}\r\nnet[\"dienstkategorie\"] = 'NET'\r\nnet[\"holidaycorrection\"] = 1#0.88\r\nnet[\"startdate\"] = datetime.now() - timedelta(days=600)\r\nnet[\"tickets\"] = [[\"plotstart\", \"plotend\"],\r\n [datetime.now() - timedelta(days=600), datetime.now()]\r\n ]\r\nnet[\"fitlines\"] = [\r\n [\"fitfunc\", \"fitstart\", \"fitend\", \"plotstart\", \"plotend\", \"linename\"],\r\n [sineline, [1000, 350, 0, 0.001, 2500, 0], datetime(2010, 4, 10), datetime(2011, 9, 10),\r\n datetime(2010, 4, 10), datetime(2012, 2, 1), \"forecast\", \"r\", 0]\r\n ]\r\nnet[\"fitmods\"] = [\r\n [\"linename\", \"fitline\", \"parmod\"],\r\n ]\r\n\r\n\r\n\r\ndef iso_year_start(iso_year):\r\n \"The gregorian calendar date of the first day of the given ISO year\"\r\n fourth_jan = datetime(iso_year, 1, 4)\r\n delta = timedelta(fourth_jan.isoweekday() - 1)\r\n return fourth_jan - delta\r\n\r\ndef iso_to_gregorian(iso_year, iso_week, iso_day):\r\n \"Gregorian calendar date for the given ISO year, week and day\"\r\n year_start = iso_year_start(iso_year)\r\n return year_start + timedelta(days=iso_day - 1, weeks=iso_week - 1)\r\n\r\ndef todate(date):\r\n year = date[:2]\r\n week = date[2:]\r\n year = int(\"20\" + year)\r\n week = int(week)\r\n return iso_to_gregorian(year, week, 1)\r\n\r\n\r\ndef forecast(dienstkategorie, startdate, fitlines, fitmods, holidaycorrection, extras=[], tickets=[]):\r\n returndict = {}\r\n returndict[\"category\"] = dienstkategorie\r\n con, cur = get_oracle_cursor_rkna1()\r\n sql = u\"select a_annahmezeitpunkt_yyiw, sum(Anzahl) from rk.tickets_by_iw_dst_at_110930 \"\r\n sql += \"where a_dienstkategorie = '{}' and cast(a_annahmezeitpunkt_yyiw as integer) < 1139 group by a_annahmezeitpunkt_yyiw order by a_annahmezeitpunkt_yyiw \".format(dienstkategorie)\r\n result = []\r\n print(sql)\r\n cur.execute(sql)\r\n for row in cur:\r\n datum = todate(row[0])\r\n if datum >= startdate:\r\n result += [[todate(row[0]), row[1]]]\r\n switchdate = date(2011, 9, 21)\r\n switchdate = \"to_date('{}', 'dd.mm.yyyy')\".format(switchdate.strftime(\"%d.%m.%Y\"))\r\n startdate = \"to_date('{}', 'dd.mm.yyyy')\".format(startdate.strftime(\"%d.%m.%Y\"))\r\n nowdate = date.today() - timedelta(days=7)\r\n nowdate = \"to_date('{}', 'dd.mm.yyyy')\".format(nowdate.strftime(\"%d.%m.%Y\"))\r\n sql = u\"select trunc(A_annahmezeitpunkt, 'iw'), count(*) from tickets \"\r\n sql += \"where trunc(A_annahmezeitpunkt, 'iw') >= {0} \".format(switchdate)\r\n sql += \"and trunc(A_annahmezeitpunkt, 'iw') <= {0} \".format(nowdate)\r\n sql += \"and A_dienstkategorie = '{}' \".format(dienstkategorie)\r\n sql += \"and \" + ticketfilter\r\n sql += \"group by trunc(A_annahmezeitpunkt, 'iw') order by trunc(A_annahmezeitpunkt, 'iw')\"\r\n print(sql)\r\n print(dienstkategorie)\r\n cur.execute(sql)\r\n for row in cur:\r\n result += [list(row)]\r\n\r\n xdata = [x[0] for x in result]\r\n ydata = [x[1] for x in result]\r\n f = plt.figure()\r\n plt.title(dienstkategorie + \" Feldticket Forecast\", fontsize=12)\r\n fitpars = {}\r\n fitfuncs = {}\r\n fitmodfuncs = {}\r\n fitmodpars = {}\r\n\r\n returndict[\"xdata\"] = xdata\r\n returndict[\"ydata\"] = ydata\r\n\r\n\r\n\r\n for fitline in fitlines[1:]:\r\n fitfunc = fitline[0]\r\n fitparam = fitline[1]\r\n fitstart = fitline[2]\r\n fitend = fitline[3]\r\n plotstart = fitline[4]\r\n plotend = fitline[5]\r\n linename = fitline[6]\r\n color = fitline[7]\r\n error = fitline[8]\r\n\r\n errfunc = lambda p, x, y: fitfunc(p, x) - y\r\n\r\n xfitdata = [date2num(x[0]) for x in result if x[0] >= fitstart and x[0] <= fitend]\r\n yfitdata = [x[1] for x in result if x[0] >= fitstart and x[0] <= fitend]\r\n p0 = fitparam + [xfitdata[0]]\r\n print(p0)\r\n holiday_correction(xfitdata, yfitdata, 1 / holidaycorrection)\r\n p1, success = optimize.leastsq(errfunc, p0[:], args=(numpy.array(xfitdata), numpy.array(yfitdata)))\r\n holiday_correction(xfitdata, yfitdata, holidaycorrection)\r\n print(p1)\r\n print(getdesc(p1))\r\n fitpars[linename] = p1\r\n fitfuncs[linename] = fitfunc\r\n xplotdata = [x[0] for x in result if x[0] >= plotstart and x[0] <= plotend]\r\n while xplotdata[-1] < plotend - timedelta(days=7):\r\n xplotdata += [xplotdata[-1] + timedelta(days=7)]\r\n fitplotdata = [fitfunc(p1, date2num(x)) for x in xplotdata]\r\n holiday_correction(xplotdata, fitplotdata, holidaycorrection)\r\n plt.plot_date(xplotdata, fitplotdata, marker=\"None\", linestyle=\"-\",\r\n color=color, label=linename)\r\n if error:\r\n plt.vlines(xplotdata, fitplotdata,\r\n [x + error for x in fitplotdata])\r\n plt.vlines(xplotdata, fitplotdata,\r\n [x - error for x in fitplotdata])\r\n\r\n returndict[\"switchdate\"] = plotend\r\n returndict[\"fitpars\"] = p1\r\n\r\n if len(fitmods) > 1:\r\n for fitmod in fitmods[1:]:\r\n linename = fitmod[0]\r\n fitline = fitmod[1]\r\n pars = fitmod[2]\r\n plotstart = fitmod[3]\r\n plotend = fitmod[4]\r\n color = fitmod[5]\r\n error = fitmod[6]\r\n fitfunc = fitfuncs[fitline]\r\n for p in range(len(fitpars[fitline])):\r\n pars[p] += fitpars[fitline][p]\r\n print(pars)\r\n xplotdata = [x[0] for x in result if x[0] >= plotstart and x[0] <= plotend]\r\n while xplotdata[-1] < plotend - timedelta(days=7):\r\n xplotdata += [xplotdata[-1] + timedelta(days=7)]\r\n fitplotdata = [fitfunc(pars, date2num(x)) for x in xplotdata]\r\n holiday_correction(xplotdata, fitplotdata, holidaycorrection)\r\n plt.plot_date(xplotdata, fitplotdata, marker=\"None\", linestyle=\"-\",\r\n color=color, label=linename)\r\n if error:\r\n plt.vlines(xplotdata, fitplotdata,\r\n [x + error for x in fitplotdata])\r\n plt.vlines(xplotdata, fitplotdata,\r\n [x - error for x in fitplotdata])\r\n fitmodpars[linename] = pars\r\n fitmodfuncs[linename] = fitfunc\r\n returndict[\"extrpars\"] = pars\r\n\r\n\r\n\r\n\r\n if tickets:\r\n xtemp = []\r\n ytemp = []\r\n for i in range(len(xdata)):\r\n if xdata[i] >= tickets[1][0] and xdata[i] <= tickets[1][1]:\r\n xtemp += [xdata[i]]\r\n ytemp += [ydata[i]]\r\n xdata = xtemp\r\n ydata = ytemp\r\n\r\n\r\n plt.plot_date(xdata, ydata, markersize=4, label=\"tickets per week\")\r\n plt.ylim(0, max(ydata) * 1.1)\r\n holiday_correction(xdata, ydata, 1 / holidaycorrection)\r\n smoothdates = xdata\r\n winsize = 13\r\n winhalf = int((winsize - 1) / 2.)\r\n s = [ydata[0] for x in range(winhalf)] + ydata + [ydata[-1] for x in range(winhalf)]\r\n smoothdat = convolve(signal.boxcar(winsize) / signal.boxcar(winsize).sum(), s, mode='valid')\r\n plt.plot_date(smoothdates, smoothdat, marker=\"None\", linestyle=\"-\",\r\n color=\"green\", label=\"3 month average\")\r\n winsize = 3\r\n winhalf = int((winsize - 1) / 2.)\r\n s = [ydata[0] for x in range(winhalf)] + ydata + [ydata[-1] for x in range(winhalf)]\r\n smoothdat = convolve(signal.boxcar(winsize) / signal.boxcar(winsize).sum(), s, mode='valid')\r\n plt.plot_date(smoothdates, smoothdat, marker=\"None\", linestyle=\"-\",\r\n color=\"orange\", label=\"3 week average\")\r\n\r\n\r\n for extra in extras[1:]:\r\n linename = extra[0]\r\n color = extra[1]\r\n fitadd = extra[2]\r\n fitmodadd = extra[3]\r\n dates = extra[4]\r\n values = extra[5]\r\n\r\n if fitadd:\r\n func = fitfuncs[fitadd]\r\n pars = fitpars[fitadd]\r\n elif fitmodadd:\r\n func = fitmodfuncs[fitmodadd]\r\n pars = fitmodpars[fitmodadd]\r\n\r\n if fitmodadd or fitadd:\r\n values = [values[i] + func(pars, date2num(dates[i])) for i in range(len(values))]\r\n plt.plot_date(dates, values, marker=\"None\", linestyle=\"-\",\r\n color=color, label=linename)\r\n\r\n\r\n kundenkategorie = dienstkategorie\r\n if kundenkategorie == 'NET':\r\n kundenkategorie = 'KAI'\r\n elif kundenkategorie == 'HDW':\r\n kundenkategorie = \"KAI','KAD\"\r\n sql = u\"select datum, sum(einheiten_angeschlossen) from we_history where Region = 10 \"\r\n sql += \"and datum >= {0} \".format(startdate)\r\n sql += \"and A_dienstkategorie in ('{}') \".format(kundenkategorie)\r\n sql += \"group by datum order by datum \"\r\n #print(sql)\r\n cur.execute(sql)\r\n result = []\r\n for row in cur:\r\n result += [list(row)]\r\n xdata = [x[0] for x in result]\r\n ydata = [x[1] for x in result]\r\n if tickets:\r\n xtemp = []\r\n ytemp = []\r\n for i in range(len(xdata)):\r\n if xdata[i] >= tickets[1][0] and xdata[i] <= tickets[1][1]:\r\n xtemp += [xdata[i]]\r\n ytemp += [ydata[i]]\r\n xdata = xtemp\r\n ydata = ytemp\r\n leg = plt.legend(loc=\"upper left\", fancybox=True, shadow=True)\r\n frame = leg.get_frame()\r\n frame.set_facecolor('1.0')\r\n leg.set_zorder(10)\r\n ax = plt.gca()\r\n ax.grid(zorder=2)\r\n ax.set_ylabel(\"tickets\")\r\n ax.set_xlabel(\"date\")\r\n f.autofmt_xdate()\r\n ax2 = plt.twinx()\r\n ax2.set_ylabel(\"customers\")\r\n plt.plot_date(xdata, ydata, marker=\"None\", linestyle=\"-\", color=\"gray\", label=\"customers\", zorder=5)\r\n ydelta = [(ydata[i] - ydata[i - 7]) * 100 for i in range(7, len(ydata)) if xdata[i] > datetime(2011, 4, 1)]\r\n xdelta = xdata[-len(ydelta):]\r\n winsize = 7\r\n winhalf = int((winsize - 1) / 2.)\r\n s = [ydelta[0] for x in range(winhalf)] + ydelta + [ydelta[-1] for x in range(winhalf)]\r\n smoothdat = convolve(signal.boxcar(winsize) / signal.boxcar(winsize).sum(), s, mode='valid')\r\n plt.plot_date(xdelta, smoothdat, marker=\"None\", linestyle=\"--\", color=\"gray\", label=\"weekly new customers * 100\", zorder=5)\r\n leg = plt.legend(loc=\"lower right\", fancybox=True, shadow=True)\r\n frame = leg.get_frame()\r\n frame.set_facecolor('1.0')\r\n leg.set_zorder(20)\r\n ax.set_zorder(ax2.get_zorder() + 1) # put ax in front of ax2\r\n ax.patch.set_visible(False) # hide the 'canvas'\r\n\r\n\r\n\r\n\r\n #plt.show()\r\n f.autofmt_xdate()\r\n plt.savefig(\"forecast_\" + dienstkategorie + \".pdf\")\r\n return returndict\r\n\r\n\r\ndef plot_all(dicts, startdate, enddate):\r\n datums = []\r\n for dic in dicts:\r\n datums += dic[\"xdata\"]\r\n datums = sorted(list(set(datums)))\r\n tickets = [0 for x in datums]\r\n for dic in dicts:\r\n for i in range(len(dic[\"ydata\"])):\r\n if dic[\"xdata\"][i] in datums:\r\n index = datums.index(dic[\"xdata\"][i])\r\n tickets[index] += dic[\"ydata\"][i]\r\n f = plt.figure()\r\n plotdatums = [x for x in datums if x > startdate]\r\n plottickets = tickets[-len(plotdatums):]\r\n plt.plot_date(plotdatums, plottickets)\r\n smoothdates = plotdatums\r\n winsize = 13\r\n winhalf = int((winsize - 1) / 2.)\r\n s = [plottickets[0] for x in range(winhalf)] + plottickets + [plottickets [-1] for x in range(winhalf)]\r\n smoothdat = convolve(signal.boxcar(winsize) / signal.boxcar(winsize).sum(), s, mode='valid')\r\n plt.plot_date(smoothdates, smoothdat, marker=\"None\", linestyle=\"-\",\r\n color=\"green\")\r\n winsize = 3\r\n winhalf = int((winsize - 1) / 2.)\r\n s = [plottickets [0] for x in range(winhalf)] + plottickets + [plottickets [-1] for x in range(winhalf)]\r\n smoothdat = convolve(signal.boxcar(winsize) / signal.boxcar(winsize).sum(), s, mode='valid')\r\n plt.plot_date(smoothdates, smoothdat, marker=\"None\", linestyle=\"-\",\r\n color=\"orange\")\r\n switchdate = plotdatums[-1]\r\n while plotdatums[-1] < enddate:\r\n plotdatums += [plotdatums[-1] + timedelta(days=7)]\r\n fittickets = [0 for x in plotdatums]\r\n for dic in dicts:\r\n for i in range(len(plotdatums)):\r\n if (plotdatums[i] <= dic[\"switchdate\"]) or \"extrpars\" not in dic:\r\n fittickets[i] += sineline(dic[\"fitpars\"], date2num(plotdatums[i]))\r\n else:\r\n fittickets[i] += sineline(dic[\"extrpars\"], date2num(plotdatums[i]))\r\n plt.plot_date(plotdatums, fittickets, marker=\"None\", linestyle=\"-\",\r\n color=\"red\")\r\n errordatums = [x for x in plotdatums if x > switchdate]\r\n errlen = len(errordatums)\r\n plt.vlines(errordatums, fittickets[-errlen:], [fittickets[-errlen + x] + (200 + 10 * x) for x in range(errlen)], color=\"r\")\r\n plt.vlines(errordatums, fittickets[-errlen:], [fittickets[-errlen + x] - (200 + 5 * x) for x in range(errlen)], color=\"r\")\r\n plt.vlines(errordatums, fittickets[-errlen:], [fittickets[-errlen + x] + (50 + 10 * x) for x in range(errlen)], color=\"g\")\r\n plt.vlines(errordatums, fittickets[-errlen:], [fittickets[-errlen + x] - (50 + 5 * x) for x in range(errlen)], color=\"g\")\r\n\r\n plt.title(\"Gesamtforecast\", fontsize=12)\r\n ax = plt.gca()\r\n ax.set_ylabel(\"Tickets\")\r\n ax.set_xlabel(\"Datum\")\r\n plt.savefig(\"all.pdf\")\r\n wb = xlwt.Workbook()\r\n sheet = wb.add_sheet(\"data\")\r\n sheet.write(0, 0, \"Datum\")\r\n sheet.write(0, 1, \"Fit-Extrapolation\")\r\n sheet.write(0, 2, \"Tickets\")\r\n xf = xlwt.easyxf(num_format_str='YYYYMMDD')\r\n for i in range(len(plotdatums)):\r\n sheet.write(i + 1, 0, plotdatums[i], xf)\r\n sheet.write(i + 1, 1, fittickets[i])\r\n if i < len(plottickets):\r\n sheet.write(i + 1, 2, plottickets[i])\r\n sheet.write(i + 1, 3, \"gesamt\")\r\n row = len(plotdatums) + 1\r\n for dic in dicts:\r\n for i in range(len(plotdatums)):\r\n sheet.write(row, 0, plotdatums[i], xf)\r\n if (plotdatums[i] <= dic[\"switchdate\"]) or \"extrpars\" not in dic:\r\n fitval = sineline(dic[\"fitpars\"], date2num(plotdatums[i]))\r\n else:\r\n fitval = sineline(dic[\"extrpars\"], date2num(plotdatums[i]))\r\n sheet.write(row, 1, fitval)\r\n if plotdatums[i] in dic[\"xdata\"]:\r\n sheet.write(row, 2, dic[\"ydata\"][dic[\"xdata\"].index(plotdatums[i])])\r\n sheet.write(row, 3, dic[\"category\"])\r\n row += 1\r\n\r\n wb.save(\"data.xls\")\r\n\r\n\r\n\r\ndicts = []\r\ndicts.append(forecast(**net))\r\ndicts.append(forecast(**kai))\r\ndicts.append(forecast(**kav))\r\ndicts.append(forecast(**kaa))\r\ndicts.append(forecast(**kad))\r\ndicts.append(forecast(**hdw))\r\nplot_all(dicts, datetime(2011, 4, 1), datetime(2012, 4, 1))\r\n\r\n\r\n","sub_path":"naos-python/Source/RK/forecast.py","file_name":"forecast.py","file_ext":"py","file_size_in_byte":22772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"45852529","text":"import pygame\r\nimport copy\r\n\r\nhidden_rows = 4\r\n\r\nclass Board:\r\n\r\n\tdef __init__(self):\r\n\t\tself.x = 10\r\n\t\tself.y = 20 + hidden_rows\r\n\r\n\t\tself.locked_board = [[(255,255,255) for _ in range(self.x)] for _ in range(self.y)]\r\n\t\tself.temp_board = copy.deepcopy(self.locked_board)\r\n\t\tself.temp_input_board = copy.deepcopy(self.locked_board)\r\n\r\n\t\tself.level = 0\r\n\t\tself.lines = 0\r\n\t\tself.score = 0\r\n\r\n\t\tself.height = 0\r\n\r\n\r\n\tdef update_board(self, piece):\r\n\r\n\t\t# Given a piece, this function updates the colour of the board data.\r\n\t\t# update_validation must be called before this to check feasibility.\r\n\t\t#\r\n\t\t# param piece \t\tTetromino\r\n\r\n\t\tself.temp_board = copy.deepcopy(self.locked_board)\r\n\t\t\r\n\t\tfor i, line in enumerate(piece.shape[piece.rotation%len(piece.shape)]):\r\n\t\t\tfor j, char in enumerate(line):\r\n\r\n\t\t\t\tif char == '0':\r\n\t\t\t\t\tself.temp_board[piece.y+j][piece.x+i] = piece.colour\r\n\r\n\r\n\tdef update_validation(self, piece):\r\n\r\n\t\t# Checks whether position of piece is feasible on the board.\r\n\t\t#\r\n\t\t# param piece \t\tTetromino\r\n\r\n\t\t# potential positions\r\n\t\taccepted_positions = [] \t\r\n\t\tfor i in range(self.x):\r\n\t\t\tfor j in range(self.y):\r\n\t\t\t\tif self.locked_board[j][i] == (255,255,255):\r\n\t\t\t\t\taccepted_positions.append( (j,i) )\r\n\r\n\t\tfor i, line in enumerate(piece.shape[piece.rotation%len(piece.shape)]):\r\n\t\t\tfor j, char in enumerate(line):\r\n\t\t\t\tif char == '0':\r\n\t\t\t\t\tif (piece.y+j,piece.x+i) not in accepted_positions:\r\n\t\t\t\t\t\treturn False\r\n\r\n\t\treturn True\r\n\r\n\r\n\tdef lock_piece(self, piece):\r\n\r\n\t\t# Locks piece in locked data.\r\n\t\t#\r\n\t\t# param piece \t\tTetromino\r\n\r\n\t\tfor i, line in enumerate(piece.shape[piece.rotation%len(piece.shape)]):\r\n\t\t\tfor j, char in enumerate(line):\r\n\r\n\t\t\t\tif char == '0':\r\n\t\t\t\t\tself.locked_board[piece.y+j][piece.x+i] = piece.colour\r\n\r\n\r\n\tdef scoring(self):\r\n\r\n\t\t# Given a successful tetris, this function will implement the Original Sega scoring \r\n\t\t#system.\r\n\r\n\t\tline = 0\r\n\t\tpoints = 0\r\n\r\n\t\t# Check for completed lines in board\r\n\t\tfor old_row in range(self.y-1,0,-1):\r\n\t\t\tif (255,255,255) not in self.locked_board[old_row]:\r\n\t\t\t\tline += 1\r\n\r\n\t\t\t\tdel self.locked_board[old_row]\r\n\t\t\t\tself.locked_board.insert(0, [(255,255,255) for _ in range(self.x)])\r\n\r\n\r\n\t\t# Original Sega Scoring System\r\n\t\t# line_multiplier = {1:1, 2:4, 3:9, 4:20}\r\n\t\t# if line == 0:\r\n\t\t# \tpass\r\n\t\t# elif 0 <= self.level <= 1:\r\n\t\t# \tpoints += 100*line_multiplier[line]\r\n\t\t# elif 2 <= self.level <= 3:\r\n\t\t# \tpoints += 200*line_multiplier[line]\r\n\t\t# elif 4 <= self.level <= 5:\r\n\t\t# \tpoints += 300*line_multiplier[line]\r\n\t\t# elif 6 <= self.level <= 7:\r\n\t\t# \tpoints += 400*line_multiplier[line]\r\n\t\t# elif self.level <= 8:\r\n\t\t# \tpoints += 500*line_multiplier[line]\r\n\t\tif line == 0:\r\n\t\t\tpass\r\n\t\telif line == 1:\r\n\t\t\tpoints += 40\r\n\t\telif line == 2:\r\n\t\t\tpoints += 120\r\n\t\telif line == 3:\r\n\t\t\tpoints += 300\r\n\t\telif line == 4:\r\n\t\t\tpoints += 1200\r\n\r\n\r\n\t\t# Check for Perfect Clear\r\n\t\tperfect_clear = all([x == (255,255,255) for x in self.locked_board[i]] for i in range(len(self.locked_board)))\r\n\t\tif perfect_clear:\r\n\t\t\tpoints *= 10\r\n\r\n\t\tself.lines += line\r\n\t\tself.score += points\r\n\r\n\t\t# Tetris(NES, Nintendo) level system\r\n\t\tif self.lines < 200:\r\n\t\t\tself.level = self.lines // 10\r\n\r\n\r\n\tdef draw_board(self ,win, board_x, board_y, block_size):\r\n\r\n\t\t# Draws the board and grid lines using pygame.\r\n\t\t#\t\r\n\t\t# param win\t\t\tPygame window\r\n\t\t# param board_x\t\tStarting x point of board\r\n\t\t# param board y \tStarting y point of board\r\n\t\t# param block_size\tBlock size\r\n\r\n\t\tborder_size = 3\r\n\r\n\r\n\t\tfor i in range(self.x):\r\n\t\t\tfor j in range(hidden_rows,self.y):\r\n\r\n\t\t\t\t# Draw board\r\n\t\t\t\tpygame.draw.rect(win, self.temp_board[j][i], \r\n\t\t\t\t\t(board_x + i*block_size, board_y + j*block_size, block_size, block_size), 0)\t\r\n\r\n\t\t\t\t# Draw grid line\r\n\t\t\t\tpygame.draw.line(win, (128,128,128), \r\n\t\t\t\t\t(board_x + i*block_size, board_y + (hidden_rows*block_size)), \r\n\t\t\t\t\t(board_x + i*block_size, board_y + block_size*self.y))\t\r\n\t\t\t\tpygame.draw.line(win, (128,128,128), \r\n\t\t\t\t\t(board_x, board_y + j*block_size), \r\n\t\t\t\t\t(board_x + self.x*block_size, board_y + j*block_size))\r\n\r\n\r\n\t\t# Draw border line\r\n\t\tpygame.draw.line(win, (255,0,0),\r\n\t\t\t(board_x, board_y + (hidden_rows*block_size)), \r\n\t\t\t(board_x + self.x*block_size, board_y + (hidden_rows*block_size)),\r\n\t\t\tborder_size)\r\n\t\tpygame.draw.line(win, (255,0,0),\r\n\t\t\t(board_x, board_y + self.y*block_size), \r\n\t\t\t(board_x + self.x*block_size, board_y + self.y*block_size),\r\n\t\t\tborder_size)\r\n\t\tpygame.draw.line(win, (255,0,0),\r\n\t\t\t(board_x, board_y + (hidden_rows*block_size)), \r\n\t\t\t(board_x, board_y + (self.y*block_size)),\r\n\t\t\tborder_size)\r\n\t\tpygame.draw.line(win, (255,0,0),\r\n\t\t\t(board_x + self.x*block_size, board_y + (hidden_rows*block_size)), \r\n\t\t\t(board_x + self.x*block_size, board_y + (self.y*block_size)),\r\n\t\t\tborder_size)\r\n\r\n\r\n\tdef input_data(self, piece):\r\n\r\n\t\t# Calculates the input data for genetic algorithm given the tetromino piece.\r\n\t\t#\r\n\t\t# param piece \t\t\t\tTetromino\r\n\t\t# output sum(heights)\t\tAggregrated height\r\n\t\t# output completed_lines\tLines completed\r\n\t\t# output holes \t\t\t\tHoles within stack\r\n\t\t# output bumpiness\t\t\tBumpiness within height\r\n\r\n\r\n\t\t# Updates temp_board with hard-dropped piece to conduct analysis\r\n\t\tfor i in range(30):\r\n\t\t\tpiece.y += 1\r\n\r\n\t\t\tif not self.update_validation(piece):\r\n\t\t\t\tpiece.y -= 1\r\n\t\t\t\tself.update_board(piece)\r\n\t\t\t\tpiece.y -= i\r\n\t\t\t\tbreak\r\n\r\n\r\n\t\t# Calculate input data\r\n\t\theights = [0 for i in range(self.x)]\r\n\t\theight_counted = [False for i in range(self.x)]\r\n\r\n\t\tholes = 0\r\n\t\tcompleted_lines = 0\r\n\t\tbumpiness = 0\r\n\r\n\r\n\t\tfor j in range(hidden_rows, self.y):\r\n\r\n\t\t\tif not (255,255,255) in self.temp_board[j]:\r\n\t\t\t\tcompleted_lines += 1\r\n\r\n\t\t\tfor i in range(self.x):\r\n\r\n\t\t\t\t# Find height if column not empty\r\n\t\t\t\tif not self.temp_board[j][i] == (255,255,255) and not height_counted[i]:\r\n\t\t\t\t\theights[i] = self.y - j\r\n\t\t\t\t\theight_counted[i] = True\r\n\r\n\t\t\t\t# Count holes if column height acquired\r\n\t\t\t\tif self.temp_board[j][i] == (255,255,255) and height_counted[i]:\r\n\t\t\t\t\tholes += 1\r\n\r\n\t\t# Calculate bumpiness\r\n\t\tfor i in range(self.x - 2):\r\n\t\t\tbumpiness += abs(heights[i] - heights[i+1])\r\n\r\n\r\n\t\treturn [sum(heights), completed_lines, holes, bumpiness]\r\n\t\t#return (*heights, completed_lines, holes, bumpiness)\r\n\t\t#return sum(heights), completed_lines, holes, bumpiness\r\n\r\n\r\n\r\n\r\n\tdef board_heuristic_inputs(self, piece):\r\n\r\n\t\t# Calculates heursitic inputs for every combination of rotation and position in x axis.\r\n\t\t#\r\n\t\t# param\t piece \t\tTetromino\r\n\t\t# output inputs\t\tInputs (size: [160])\r\n\r\n\t\tinputs = [0 for i in range(40*4)]\r\n\r\n\t\tfor k in range(piece.rotations):\r\n\t\t\tpiece.rotation = k\r\n\r\n\t\t\t# Move furthest to left\r\n\t\t\tfor j in range(5):\r\n\t\t\t\tpiece.x -= 1\r\n\t\t\t\tif not self.update_validation(piece):\r\n\t\t\t\t\tpiece.x += 1\r\n\t\t\t\t\tbreak\r\n\r\n\t\t\t# Obtain heuristic inputs for each combination of rotation and column position\r\n\t\t\tfor j in range(10):\t\t\t\t\r\n\t\t\t\tif self.update_validation(piece):\r\n\t\t\t\t\tinputs[ 10*k + 4*j : 10*k + 4*(j+1) ] = self.input_data(piece)\r\n\t\t\t\tpiece.x += 1\r\n\r\n\t\t# Reset to original piece parameters\r\n\t\tpiece.x = 0\r\n\t\tpiece.rotation = 0\r\n\r\n\t\treturn inputs\r\n","sub_path":"Board.py","file_name":"Board.py","file_ext":"py","file_size_in_byte":7026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"197579467","text":"\nfrom js9 import j\nfrom pprint import pprint as print\nimport os\nimport struct\nimport copy\n\nTEMPLATE = \"\"\"\naddr = \"localhost\"\nport = \"9900\"\nnamespace = \"\"\nadminsecret_ = \"\"\nsecret_ = \"\"\nmode = \"direct\"\nid_enable = true\ndelete = false\n\"\"\"\n\nJSConfigBase = j.tools.configmanager.base_class_config\n\n\nclass ZDBClient(JSConfigBase):\n\n def __init__(self, instance, data={}, parent=None, interactive=False,started=True):\n \"\"\"\n is connection to ZDB\n\n - secret is also the name of the directory where zdb data is for this namespace/secret\n\n config params:\n secret {str} -- is same as namespace id, is a secret to access the data (default: {None})\n port {[int} -- (default: 9900)\n mode -- user,direct,sequential see https://github.com/rivine/0-db/blob/master/README.md\n id_enabled -- if mode: user or sequential then key_enabled needs to be False, there will be pos_id for each change in the DB\n namespace -- zdb supports namespace\n adminsecret does not have to be set, but when you want to create namespaces it is a must\n\n \"\"\"\n self.init(instance=instance, data=data, parent=parent, interactive=interactive,started=started)\n\n def init(self, instance, data={}, parent=None, interactive=False, reset=False,started=True):\n\n JSConfigBase.__init__(self, instance=instance, data=data,\n parent=parent, template=TEMPLATE, ui=None, interactive=interactive)\n\n if self.config.data[\"id_enable\"]:\n ipath = j.dirs.VARDIR + \"/zdb/index/%s.db\" % instance\n j.sal.fs.createDir(j.dirs.VARDIR + \"/zdb/index\")\n if reset:\n j.sal.fs.remove(ipath)\n self._indexfile = j.data.indexfile.get(name=instance, path=ipath, nrbytes=6)\n else:\n self._indexfile = None\n \n if not started:\n return\n\n redis = j.clients.redis.get(ipaddr=self.config.data['addr'],\n port=self.config.data['port'],\n fromcache=False)\n\n self.client = self._patch_redis_client(redis)\n\n if self.config.data[\"adminsecret_\"] is not \"\" and self.config.data[\"adminsecret_\"] is not None:\n self.client.execute_command(\"AUTH\", self.config.data[\"adminsecret_\"])\n\n self.id_enable = bool(self.config.data[\"id_enable\"])\n\n if self.id_enable:\n self.config.data[\"mode\"] == \"direct\"\n\n self.key_enable = False\n if self.config.data[\"mode\"] == \"user\":\n if self.id_enable:\n raise RuntimeError(\"cannot have id_enable and user mode on db\")\n self.key_enable = True\n if self.config.data[\"mode\"] == \"direct\":\n self.key_enable = False\n if self.config.data[\"mode\"] == \"seq\":\n self.key_enable = False\n if self.id_enable:\n raise RuntimeError(\"cannot have id_enable and seq mode on db\")\n\n nsname = self.config.data[\"namespace\"]\n secret = self.config.data[\"secret_\"]\n\n self.mode = self.config.data[\"mode\"]\n\n def namespace_init(nsname, secret):\n # means the namespace does already exists\n if secret is \"\":\n self.client.execute_command(\"SELECT\", nsname)\n else:\n self.client.execute_command(\"SELECT\", nsname, secret)\n self.namespace = nsname\n\n if self.namespace_exists(nsname):\n namespace_init(nsname, secret)\n self.logger.debug(\"namespace:%s exists\" % nsname)\n else:\n self.client.execute_command(\"NSNEW\", nsname)\n namespace_init(nsname, secret)\n if secret is not \"\":\n self.client.execute_command(\n \"NSSET\", self.namespace, \"password\", secret)\n self.client.execute_command(\n \"NSSET\", self.namespace, \"public\", \"no\")\n self.logger.debug(\"namespace:%s NEW\" % nsname)\n\n self.logger.debug(self.nsinfo)\n\n def _patch_redis_client(self, redis):\n # don't auto parse response for set, cause it's not 100% redis compatible\n # 0-db does return a key after in set\n del redis.response_callbacks['SET']\n return redis\n\n def set(self, data, id=None, key=None, checknew=False):\n \"\"\"[summary]\n\n Arguments:\n data {str or binary} -- the payload can be e.g. capnp binary\n\n Keyword Arguments:\n id {int} -- needs id_enabled to be on true, can be used to find info back based on id (default: {None})\n if None and id_enabled==True then will autoincrement if not given\n\n key {[type]} -- string, only usable if key_enable == True\n\n @PARAM checknew, if True will return (key,new) and new is bool\n \"\"\"\n if self.mode==\"seq\":\n if id is None:\n id=\"\"\n else:\n id = struct.pack(\" end:\n break\n \n else: \n if self.id_enable == False:\n raise RuntimeError(\"only id_enable supported for iterate\")\n\n if start is not None:\n id = start\n else:\n id = 0\n\n self._indexfile._f.seek(self._indexfile._offset(id))\n\n while True:\n pos = self._indexfile._f.read(self._indexfile.nrbytes)\n if len(pos) < self._indexfile.nrbytes:\n break # EOF\n\n data = self.client.execute_command(\"GET\", pos)\n\n result = method(id, data, result=result)\n id += 1\n if end is not None and id > end:\n break\n\n return result\n\n def namespace_exists(self, name):\n try:\n self.client.execute_command(\"NSINFO\", name)\n return True\n except Exception as e:\n if not \"Namespace not found\" in str(e):\n raise RuntimeError(\"could not check namespace:%s, error:%s\" % (name, e))\n return False\n\n def namespace_new(self, name, secret=\"\", maxsize=0, instance=None):\n if self.namespace_exists(name):\n raise RuntimeError(\"namespace already exists:%s\" % name)\n\n data = copy.copy(self.config.data)\n data[\"namespace\"] = name\n data[\"secret_\"] = secret\n if instance is not None:\n self.instance = instance\n self.init(self.instance, data=data, reset=True)\n\n if maxsize is not 0:\n self.client.execute_command(\"NSSET\", self.namespace, \"maxsize\", maxsize)\n\n @property\n def count(self):\n i = self.nsinfo\n if self.id_enable:\n return self._indexfile.count\n else:\n return i[\"entries\"]\n\n def test(self):\n\n nr = self.nsinfo[\"entries\"]\n assert nr == 0\n # do test to see that we can compare\n id = self.set(b\"r\")\n assert id == 0\n assert self.get(id) == b\"r\"\n newid, exists = self.set(b\"r\", id=id, checknew=True)\n assert exists is False\n assert newid == id\n\n nr = self.nsinfo[\"entries\"]\n\n self.set(\"test\", 1)\n print (self.nsinfo)\n\n # test the list function\n assert self.list(0, 0) == [0]\n assert self.list(0, 1) == [0, 1]\n assert self.list(1, 1) == [1]\n\n res = self.list()\n assert res == [0, 1]\n\n print(res)\n\n result = {}\n\n def test(id, data, result):\n print(\"%s:%s\" % (id, data))\n result[id] = data\n return result\n\n result = self.iterate(test, result={})\n\n assert self.list(start=newid, end=newid) == [newid]\n\n result = self.iterate(test, result={}, start=newid, end=newid)\n\n assert result == {newid: b'r'}\n\n assert self.exists(newid)\n\n def dumpdata():\n\n if self.key_enable:\n inputs = {}\n for i in range(4):\n data = os.urandom(4096)\n key = self.set(data, key=str(i))\n inputs[key] = data\n\n elif self.id_enable:\n inputs = {}\n for i in range(4):\n data = os.urandom(4096)\n key = self.set(data)\n inputs[key] = data\n\n for k, expected in inputs.items():\n actual = self.get(k)\n assert expected == actual\n\n dumpdata() # is in default namespace\n\n for i in range(1000):\n nsname = \"testns_%s\" % i\n exists = self.namespace_exists(nsname)\n if not exists:\n break\n\n print (\"count:%s\" % self.count)\n\n self.namespace_new(nsname, secret=\"1234\", maxsize=1000, instance=None)\n\n assert self.nsinfo[\"data_limits_bytes\"] == 1000\n assert self.nsinfo[\"data_size_bytes\"] == 0\n assert self.nsinfo[\"data_size_mb\"] == 0.0\n assert self.nsinfo[\"entries\"] == 0\n assert self.nsinfo[\"index_size_bytes\"] == 0\n assert self.nsinfo[\"index_size_kb\"] == 0.0\n assert self.nsinfo[\"name\"] == nsname\n assert self.nsinfo[\"password\"] == \"yes\"\n assert self.nsinfo[\"public\"] == \"no\"\n\n assert self.namespace == nsname\n\n # both should be same\n id = self.set(b\"a\")\n assert self.get(id) == b\"a\"\n assert self._indexfile.count == 1\n assert self.nsinfo[\"entries\"] == 1\n\n try:\n dumpdata()\n except Exception as e:\n assert \"No space left\" in str(e)\n\n self.namespace_new(nsname+\"2\", secret=\"1234\", instance=None)\n\n nritems = 100000\n j.tools.timer.start(\"zdb\")\n\n print(\"perftest for 100.000 records, should get above 10k per sec\")\n for i in range(nritems):\n id = self.set(b\"a\")\n\n j.tools.timer.stop(nritems)\n","sub_path":"JumpScale9RecordChain/clients/zdb/ZDBClient.py","file_name":"ZDBClient.py","file_ext":"py","file_size_in_byte":14585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"566830694","text":"import sys\r\nfrom random import random\r\n\r\nw = 100\r\nh = 150\r\nhodnoty = []\r\n\r\nfor i in range(w):\r\n\thodnoty.append([0]*h)\r\n\r\nminers = []\r\n\r\nsmery = [(1, 0), (0, 1), (-1, 0), (0, -1)]\r\ndef new_cross(x, y, smery):\r\n\t#nesmi byt slepa\r\n\thodnoty[x][y] = 1\r\n\tsmer1 = smery[int(random()*len(smery))]\r\n\tMiner(x, y, smer1)\r\n\tsmery.remove(smer1)\r\n\tfor smer in smery:\r\n\t\tif random() < 0.7:\r\n\t\t\tMiner(x, y, smer)\r\n\r\n\r\n\r\nclass Miner():\r\n\tdef __init__(self, x, y, smer):\r\n\t\tself.x = x\r\n\t\tself.y = y\r\n\t\tself.smer = smer\r\n\t\tminers.append(self)\r\n\t\tself.fuel = 3 + int(random()*7)\r\n\r\n\t\tself.vertical = (smer[0] == 0)\r\n\r\n\r\n\tdef update(self):\r\n\t\tself.fuel -= 1\r\n\r\n\t\tself.x += self.smer[0]\r\n\t\tself.y += self.smer[1]\r\n\r\n\t\t#vyjel z mapy\r\n\t\tif self.x < 0 or self.y < 0 or self.x >= w or self.y >= h:\r\n\t\t\tminers.remove(self)\r\n\t\t\treturn\r\n\t\t#narazil na cestu\r\n\t\tif hodnoty[self.x][self.y] == 1:\r\n\t\t\tminers.remove(self)\r\n\t\t\treturn\r\n\r\n\t\tif self.vertical:\r\n\t\t\tif self.x < w - 1 and hodnoty[self.x + 1][self.y] == 1:\r\n\t\t\t\tif (hodnoty[self.x + 1][self.y - self.smer[1]] == 0 and \r\n\t\t\t\t\thodnoty[self.x - 1][self.y - self.smer[1]] == 0):\r\n\t\t\t\t\thodnoty[self.x][self.y] = 1\r\n\t\t\t\tminers.remove(self)\r\n\t\t\t\treturn\r\n\t\t\tif self.x > 1 and hodnoty[self.x - 1][self.y] == 1:\r\n\t\t\t\tif (hodnoty[self.x + 1][self.y - self.smer[1]] == 0 and \r\n\t\t\t\t\thodnoty[self.x - 1][self.y - self.smer[1]] == 0):\r\n\t\t\t\t\thodnoty[self.x][self.y] = 1\r\n\t\t\t\tminers.remove(self)\r\n\t\t\t\treturn\r\n\t\telse:\r\n\t\t\tif self.y < h - 1 and hodnoty[self.x][self.y + 1] == 1:\r\n\t\t\t\tif (hodnoty[self.x - self.smer[0]][self.y + 1] == 0 and \r\n\t\t\t\t\thodnoty[self.x - self.smer[0]][self.y - 1] == 0):\r\n\t\t\t\t\thodnoty[self.x][self.y] = 1\r\n\t\t\t\tminers.remove(self)\r\n\t\t\t\treturn\r\n\t\t\tif self.y > 1 and hodnoty[self.x][self.y - 1] == 1:\r\n\t\t\t\tif (hodnoty[self.x - self.smer[0]][self.y + 1] == 0 and \r\n\t\t\t\t\thodnoty[self.x - self.smer[0]][self.y - 1] == 0):\r\n\t\t\t\t\thodnoty[self.x][self.y] = 1\r\n\t\t\t\tminers.remove(self)\r\n\t\t\t\treturn\r\n\r\n\r\n\t\t#vyčerpal palivo\r\n\t\tif not self.fuel:\r\n\t\t\tminers.remove(self)\r\n\t\t\ttry:\r\n\t\t\t\tif hodnoty[self.x + self.smer[0]][self.y + self.smer[1]] != 1:\r\n\t\t\t\t\tsm = smery[:]\r\n\t\t\t\t\tsm.remove(self.smer)\r\n\t\t\t\t\tnew_cross(self.x, self.y, sm)\r\n\t\t\t\telse:\r\n\t\t\t\t\thodnoty[self.x + self.smer[0]][self.y + self.smer[1]] = 1\r\n\t\t\texcept:\r\n\t\t\t\tpass\r\n\r\n\t\telse:\r\n\t\t\thodnoty[self.x][self.y] = 1\r\n\r\ndef generate(width, height):\r\n\tglobal hodnoty, w, h\r\n\tw = width\r\n\th = height\r\n\thodnoty = []\r\n\t\r\n\tfor i in range(w):\r\n\t\thodnoty.append([0]*h)\r\n\r\n\tnew_cross(w//3, h//3, smery[:])\r\n\tnew_cross(w//3*2, h//3, smery[:])\r\n\tnew_cross(w//3, h//3*2, smery[:])\r\n\tnew_cross(w//3*2, h//3*2, smery[:])\r\n\twhile len(miners):\r\n\t\tfor m in miners:\r\n\t\t\tm.update()\r\n\r\n\t#zahrada = Robot(0,0)\r\n\t#zahrada.fill()\r\n\treturn hodnoty\r\n\r\n\r\nclass Robot():\r\n\tsmery = [(1, 0), (0, 1), (-1, 0), (0, -1)]\r\n\r\n\tdef __init__(self,x,y):\r\n\t\tself.alive = 1\r\n\t\tself.otoceni = 0\r\n\t\tself.x = 0\r\n\t\tself.y = 0\r\n\t\thodnoty[self.x][self.y] = 3\r\n\t\tself.smer = smery[0]\r\n\t\r\n\tdef left(self):\r\n\t\ti = smery.index(self.smer)\r\n\t\tself.smer = smery[i - 1]\r\n\r\n\r\n\r\n\tdef go(self):\r\n\r\n\t\tif self.x+self.smer[0] > -1 and self.x+self.smer[0] < w and self.y+self.smer[1] > -1 and self.y+self.smer[1] < h:\r\n\t\t\tprint('cisla ok')\r\n\t\t\tif hodnoty[self.x+self.smer[0]][self.y+self.smer[1]] == 1 or hodnoty[self.x+self.smer[0]][self.y+self.smer[1]] == 3:\r\n\t\t\t\tself.left()\r\n\t\t\t\tself.otoceni += 1\r\n\t\t\t\tprint('vlevo')\r\n\t\t\telse:\r\n\t\t\t\tprint('vpred')\r\n\t\t\t\tself.otoceni = 0\r\n\t\t\t\tself.x += self.smer[0]\r\n\t\t\t\tself.y += self.smer[1]\r\n\t\t\t\thodnoty[self.x][self.y] = 3\r\n\t\telse:\t\r\n\t\t\tself.left()\r\n\t\t\tself.otoceni += 1\r\n\r\n\t\r\n\tdef fill(self):\r\n\t\twhile self.alive:\r\n\t\t\tprint('alive')\r\n\t\t\tprint(self.x, self.y)\r\n\t\t\tself.go()\r\n\t\t\tif self.otoceni >= 4:\r\n\t\t\t\tself.alive = 0\r\n\r\ndef tisk():\r\n\tfor line in hodnoty:\r\n\t\tbuf = ''\r\n\t\tfor i in line:\r\n\t\t\tif i == 0:\r\n\t\t\t\tbuf += '.'\r\n\t\t\telif i == 1:\r\n\t\t\t\tbuf += 'X'\r\n\t\t\telif i == 2:\r\n\t\t\t\tbuf += '!'\r\n\t\t\telif i == 3:\r\n\t\t\t\tbuf += 'M'\r\n\t\tprint(buf)\r\n\t\r\n\r\nif __name__ == '__main__':\r\n\r\n\ttisk()\r\n\t#new_cross(w//2, h//2, smery[:])\r\n\r\n\tnew_cross(w//3, h//3, smery[:])\r\n\tnew_cross(w//3*2, h//3, smery[:])\r\n\tnew_cross(w//3, h//3*2, smery[:])\r\n\tnew_cross(w//3*2, h//3*2, smery[:])\r\n\twhile len(miners):\r\n\t\tfor m in miners:\r\n\t\t\tm.update()\r\n\t\ttisk()\r\n\t\tinput()\r\n\t\r\n\r\n\ttisk()\r\n\tfinished = 0\r\n\tprevious = 0","sub_path":"games/gamejam/gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":4228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"404152375","text":"def main():\n info = input().split()\n house_prices = [int(x) for x in input().split()]\n\n n = int(info[0])\n m = int(info[1])\n k = int(info[2])\n min_distance = 10**10\n for i in range(len(house_prices)):\n if house_prices[i] < k and house_prices[i] != 0:\n distance = abs(i+1-m)*10\n if min_distance > distance:\n min_distance = distance\n\n print(min_distance)\n\nif __name__ == '__main__':\n main()","sub_path":"codeforces/900/buying_a_house.py","file_name":"buying_a_house.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"347624679","text":"# protocol = 'http'\n# server = 'https://httpbin.org/post'\n\nimport logging\nimport logging.handlers\nimport tempfile\nimport os\n\n# USER SETTINGS\nlog_level = logging.DEBUG\n# END\n\nformatter = logging.Formatter(\"== %(levelname)7s %(asctime)s [%(filename)s:%(lineno)s - %(funcName)s()] :\\n%(message)s\")\n\nenviroment = 'production'\nlog_file = os.path.join(tempfile.gettempdir(), \"renderownia.log\")\nlogger = logging.getLogger(enviroment)\n\nlogger.handlers[:] = []\n\nlogger.setLevel(log_level)\nch = logging.handlers.RotatingFileHandler(log_file, maxBytes=52428800, backupCount=2)\nch.setFormatter(formatter)\nch.setLevel(log_level)\nlogger.addHandler(ch)\n\n\nserver = 'http://localhost:5000/job'\n","sub_path":"cis_render/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"644061627","text":"from pyspark.sql import SparkSession\nwarehouseLocation = \"/datalake/landing\"\nspark = SparkSession\\\n.builder.appName(\"TestSparkCTIC\")\\\n.config(\"spark.sql.warehouse.dir\", warehouseLocation)\\\n.enableHiveSupport()\\\n.getOrCreate()\n\ndata2 = [1, 2, 3, 4, 5, 6 , 7, 8, 9, 10]\ndistData2 = spark.sparkContext.parallelize(data2)\ndistData3 = distData2.map(lambda x:x*2)#narrow transformation map\ndemo = distData3.collect()#Action\nprint(\"resultado\")\nprint(demo)","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"104844022","text":"##\n## Imprima la suma de la columna 2 por cada letra \n## de la columna 4, ordnados alfabeticamente.\n##\n## a,114\n## b,40\n## c,91\n## d,65\n## e,79\n## f,110\n## g,35\n##\nmail=open('data.csv','r').readlines()\nmail=[row.split('\\t') for row in mail]\nmail=[[row[3].split(','), row[1]] for row in mail]\na=dict()\nfor row in mail: \n for k in range(len(row[0])):\n if row[0][int(k)] not in a.keys():\n a[row[0][int(k)]]=0\n a[row[0][int(k)]]=a[row[0][int(k)]]+int(row[1])\nfor i in sorted(a.keys()):\n print(i,',',a[i],sep='')\n","sub_path":"q12.py","file_name":"q12.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"33642642","text":"# pylint: disable=E1101\nfrom collections import namedtuple\nfrom unittest.mock import MagicMock\n\nimport MySQLdb\nimport pytest\n\nimport libs.db.maria_db_handler as db_handler\nfrom libs.db.maria_db_handler import InsertRowObject, InvalidRowFormatError\n\nxfail = pytest.mark.xfail\n\nInvalidRowNamedTuple = namedtuple(\"InvalidRowNamedTuple\", ['data1', 'data2', 'data3'])\nFAKE_ROW_NAMED_TUPLE = InvalidRowNamedTuple('some', 'fake', 'data')\nFAKE_ROW_MAP = {\n 'column1': 'data1',\n 'column2': 'data2',\n 'column3': 'data3',\n 'column4': 'data4',\n 'column5': 'data5',\n}\nFAKE_ROW_MAP_COLUMNS = *FAKE_ROW_MAP,\nFAKE_ROW_MAP_ROW_DATA = *FAKE_ROW_MAP.values(),\nFAKE_ROW_MAP_PARAMS = '%s, %s, %s, %s, %s'\nFAKE_ROW_PRIM_KEYS = ('column1', 'column2')\nFAKE_SIMPLE_INSERT_QUERY = 'INSERT INTO sample_table_name(column1, column2) VALUES (%s, %s)'\nFAKE_SIMPLE_INSERT_QUERY_ON_DUPLICATE = (\n 'INSERT INTO sample_table_name(column1, column2) VALUES (%s, %s) ON'\n ' DUPLICATE KEY UPDATE column1 = column1, column2 = column2')\nFAKE_TABLE_NAME = 'FAKE_TABLE_NAME'\n\n\n@pytest.fixture(autouse=True)\ndef cleanup_db():\n db_handler.db = None\n\nclass MockMariaDB:\n def connect(self):\n return MagicMock()\n\n\ndef test_form_insert_query(mocker):\n FAKE_BASIC_INSERT_QUERY = 'BASIC QUERY'\n FAKE_COMPLETE_INSERT_QUERY = 'COMPLETE QUERY'\n mocker.patch.object(db_handler, '_insert_into_with_values',\n return_value=FAKE_BASIC_INSERT_QUERY)\n mocker.patch.object(db_handler, '_on_duplicate_key_update',\n return_value=FAKE_COMPLETE_INSERT_QUERY)\n db_handler._form_insert_query(FAKE_TABLE_NAME, FAKE_ROW_MAP_COLUMNS,\n FAKE_ROW_MAP_PARAMS, FAKE_ROW_PRIM_KEYS)\n\n db_handler._insert_into_with_values.assert_called_once_with(\n FAKE_TABLE_NAME, FAKE_ROW_MAP_COLUMNS, FAKE_ROW_MAP_PARAMS)\n db_handler._on_duplicate_key_update(FAKE_BASIC_INSERT_QUERY, FAKE_ROW_PRIM_KEYS)\n\n\n@pytest.mark.parametrize('table_name, columns, param_string, expected_query', [\n ('sample_table_name', ('column1', 'column2'), '%s, %s',\n 'INSERT INTO sample_table_name(column1, column2) VALUES (%s, %s)'),\n ('sample_table_name_deux', (\"column1\", \"column2\"), '%s, %s',\n 'INSERT INTO sample_table_name_deux(column1, column2) VALUES (%s, %s)'),\n ('cr@z33_t@bl3', ('#4389%$&#', '^&*())_+)*/\\\\'), '%s, %s',\n 'INSERT INTO cr@z33_t@bl3(#4389%$&#, ^&*())_+)*/\\\\\\\\) VALUES (%s, %s)'),\n ('RidicCoin_table', (\"ridic's column1\", \"ridic's column2\", \"ridic's column3\"), '%s, %s, %s',\n 'INSERT INTO RidicCoin_table(ridic\\'s column1, ridic\\'s column2, ridic\\'s column3) VALUES (%s, %s, %s)')\n])\ndef test_insert_into_with_values(table_name, columns, param_string, expected_query):\n query = db_handler._insert_into_with_values(table_name, columns, param_string)\n assert query == expected_query\n\n@pytest.mark.parametrize('prim_keys, insert_query, expected_query', [\n (None, FAKE_SIMPLE_INSERT_QUERY, FAKE_SIMPLE_INSERT_QUERY),\n ((), FAKE_SIMPLE_INSERT_QUERY, FAKE_SIMPLE_INSERT_QUERY),\n (FAKE_ROW_PRIM_KEYS, FAKE_SIMPLE_INSERT_QUERY, FAKE_SIMPLE_INSERT_QUERY_ON_DUPLICATE)\n])\ndef test_on_duplicate_key_update(prim_keys, insert_query, expected_query):\n query = db_handler._on_duplicate_key_update(insert_query, prim_keys)\n assert query == expected_query\n\n@pytest.mark.parametrize('table_columns, exp_result', [\n ([], {}),\n (['column1', 'column2'], {\n 'column1': 'data1',\n 'column2': 'data2'\n }),\n pytest.param(['mangled_column1', 'mangled_column2'], {}, marks=xfail(\n raises=KeyError, reason=\"table_columns must exist in map_data\", strict=True)),\n (['column1', 'column2', 'column3', 'column4', 'column5'], FAKE_ROW_MAP)\n])\ndef test_build_row(table_columns, exp_result):\n result = db_handler.build_row(table_columns, FAKE_ROW_MAP)\n assert result == exp_result\n\ndef test_commit_all(mocker):\n db_handler.db = MockMariaDB().connect()\n db_handler.commit_all()\n db_handler.db.commit.assert_called_once_with()\n\n\n@pytest.mark.parametrize('insert_obj, exp_columns, exp_row_data, exp_params', [\n pytest.param(InsertRowObject(FAKE_TABLE_NAME, {}, FAKE_ROW_PRIM_KEYS), (), (), '', marks=xfail(\n raises=InvalidRowFormatError, reason=\"row must not be empty\", strict=True)),\n pytest.param(InsertRowObject(FAKE_TABLE_NAME, FAKE_ROW_NAMED_TUPLE, FAKE_ROW_PRIM_KEYS), (), (), '', marks=xfail(\n raises=InvalidRowFormatError, reason=\"row must be a dict\", strict=True)),\n pytest.param(InsertRowObject(FAKE_TABLE_NAME, ('some', 'tuple'), FAKE_ROW_PRIM_KEYS), (), (), '', marks=xfail(\n raises=InvalidRowFormatError, reason=\"row must be a dict\", strict=True)),\n pytest.param(InsertRowObject(FAKE_TABLE_NAME, ['some', 'list'], FAKE_ROW_PRIM_KEYS), (), (), '', marks=xfail(\n raises=InvalidRowFormatError, reason=\"row must be a dict\", strict=True)),\n (InsertRowObject(FAKE_TABLE_NAME, FAKE_ROW_MAP, ()), FAKE_ROW_MAP_COLUMNS, FAKE_ROW_MAP_ROW_DATA, FAKE_ROW_MAP_PARAMS),\n (InsertRowObject(FAKE_TABLE_NAME, FAKE_ROW_MAP, FAKE_ROW_PRIM_KEYS), FAKE_ROW_MAP_COLUMNS, FAKE_ROW_MAP_ROW_DATA, FAKE_ROW_MAP_PARAMS)\n])\ndef test_insert_row(mocker, insert_obj, exp_columns, exp_row_data, exp_params):\n mock_cursor = MagicMock()\n mock_query = MagicMock()\n db_handler.db = MockMariaDB().connect()\n\n mocker.patch.object(db_handler, '_form_insert_query', return_value=mock_query)\n mocker.patch.object(db_handler.db, 'cursor', return_value=mock_cursor)\n\n db_handler.insert_row(insert_obj)\n\n db_handler.db.cursor.assert_called_once_with()\n mock_cursor.execute.assert_called_once_with(mock_query, exp_row_data)\n db_handler._form_insert_query.assert_called_once_with(\n FAKE_TABLE_NAME, exp_columns, exp_params, insert_obj.prim_key_columns)\n mock_cursor.close.assert_called_once_with()\n\n\ndef test_ping_db(mocker):\n db = mocker.patch.object(db_handler, 'db')\n db_handler.ping_db()\n db.ping.assert_called_once_with()\n\n\n@pytest.mark.parametrize('db_started', [ True, False ])\ndef test_start_db(mocker, db_started):\n FAKE_USER = 'fake_user'\n FAKE_PASSWORD = 'fake_password'\n FAKE_DB_NAME = 'fake_name'\n\n if db_started:\n db_handler.db = MockMariaDB().connect()\n\n mocker.patch.object(MySQLdb, 'connect')\n db_handler.start_db(FAKE_USER, FAKE_PASSWORD, FAKE_DB_NAME)\n\n if db_started is False:\n MySQLdb.connect.assert_called_once_with(user=FAKE_USER, passwd=FAKE_PASSWORD, db=FAKE_DB_NAME)\n else:\n MySQLdb.connect.assert_not_called()\n","sub_path":"tests/unit/libs/db/test_maria_db_handler.py","file_name":"test_maria_db_handler.py","file_ext":"py","file_size_in_byte":6561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"540235969","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass ResnetBlock(nn.Module):\n def __init__(self, size_in, size_out):\n super().__init__()\n size_h = min(size_in, size_out)\n\n self.fc_0 = nn.Linear(size_in, size_h)\n self.fc_1 = nn.Linear(size_h, size_out)\n self.fc_2 = nn.Linear(size_in, size_out, bias=False)\n self.relu = nn.ReLU()\n\n def forward(self, x):\n dx = self.fc_0(self.relu(x))\n dx = self.fc_1(self.relu(dx))\n\n x_skip = self.fc_2(x)\n\n return x_skip + dx\n\n\nclass PointNetEncoder(nn.Module):\n def __init__(self):\n super(PointNetEncoder, self).__init__()\n self.fc1 = nn.Linear(3, 512)\n self.resnet_1 = ResnetBlock(512, 256)\n self.resnet_2 = ResnetBlock(512, 256)\n self.resnet_3 = ResnetBlock(512, 256)\n self.resnet_4 = ResnetBlock(512, 256)\n self.fc_final = nn.Linear(256, 256)\n\n def forward(self, x):\n x = x.squeeze(dim=3)\n x = x.permute(0, 2, 1)\n\n x = F.relu(self.fc1(x))\n\n x = self.resnet_1(x)\n\n n, k, c = x.size()\n x = x.permute(0, 2, 1)\n\n pooled = F.max_pool1d(x, k).expand(x.size())\n x = torch.cat([x, pooled], dim=1)\n\n x = x.permute(0, 2, 1)\n\n x = F.relu(x)\n\n x = self.resnet_2(x)\n\n n, k, c = x.size()\n\n x = x.permute(0, 2, 1)\n\n pooled = F.max_pool1d(x, k).expand(x.size())\n x = torch.cat([x, pooled], dim=1)\n\n x = x.permute(0, 2, 1)\n\n x = F.relu(x)\n x = self.resnet_3(x)\n\n n, k, c = x.size()\n\n x = x.permute(0, 2, 1)\n\n pooled = F.max_pool1d(x, k).expand(x.size())\n x = torch.cat([x, pooled], dim=1)\n\n x = x.permute(0, 2, 1)\n\n x = self.resnet_4(x)\n n, k, c = x.size()\n x = x.permute(0, 2, 1)\n\n x = F.max_pool1d(x, k)\n\n x = x.squeeze(dim=2)\n pts = self.fc_final(x)\n\n return pts\n\n\nclass Block(nn.Module):\n def __init__(self):\n super(Block, self).__init__()\n self.fc1 = nn.Conv2d(256, 256, kernel_size=1)\n self.fc2 = nn.Conv2d(256, 256, kernel_size=1)\n self.bn1 = nn.BatchNorm2d(256, affine=False, track_running_stats=True)\n self.bn2 = nn.BatchNorm2d(256, affine=False, track_running_stats=True)\n self.gammaLayer1 = nn.Conv1d(256, 256, kernel_size=1)\n self.gammaLayer2 = nn.Conv1d(256, 256, kernel_size=1)\n self.betaLayer1 = nn.Conv1d(256, 256, kernel_size=1)\n self.betaLayer2 = nn.Conv1d(256, 256, kernel_size=1)\n\n def forward(self, y):\n x = y['ex']\n n, c, k, d = x.size()\n\n encoding = y['enc']\n gamma = self.gammaLayer1(encoding)\n\n # Need to stack the beta and gamma\n # so that we multiply all the points for one mesh\n # by the same value\n gamma = torch.stack([gamma for _ in range(k)], dim=2)\n\n beta = self.betaLayer1(encoding)\n beta = torch.stack([beta for _ in range(k)], dim=2)\n\n # First apply Conditional Batch Normalization\n out = gamma * self.bn1(x) + beta\n # Then ReLU activation function\n out = F.relu(out)\n # fully connected layer\n out = self.fc1(out)\n # Second CBN layer\n gamma = self.gammaLayer2(encoding)\n gamma = torch.stack([gamma for _ in range(k)], dim=2)\n\n beta = self.betaLayer2(encoding)\n beta = torch.stack([beta for _ in range(k)], dim=2)\n\n out = gamma * self.bn2(out) + beta\n # RELU activation\n out = F.relu(out)\n # 2nd fully connected\n out = self.fc2(out)\n # Add to the input of the ResNet Block\n out = x + out\n\n return {'ex': out, 'enc': encoding}\n\n\nclass OccupancyModel(nn.Module):\n def __init__(self):\n super(OccupancyModel, self).__init__()\n self.blocks = self.makeBlocks()\n self.encoderModel = PointNetEncoder()\n self.gammaLayer = nn.Conv1d(256, 256, kernel_size=1)\n self.betaLayer = nn.Conv1d(256, 256, kernel_size=1)\n self.cbn = nn.BatchNorm2d(256, affine=False, track_running_stats=True)\n self.fc1 = nn.Conv2d(3, 256, kernel_size=1)\n self.fc2 = nn.Conv2d(256, 1, kernel_size=1)\n\n def makeBlocks(self):\n blocks = []\n for _ in range(5):\n blocks.append(Block())\n return nn.Sequential(*blocks)\n\n def forward(self, x, pointcloud):\n n, c, k, d = x.size()\n pt_cloud = self.encoderModel(pointcloud)\n pt_cloud = pt_cloud.view(-1, 256, 1) # Add's another dimension? dunno why\n x = self.fc1(x)\n # 5 pre-activation ResNet-blocks\n x = self.blocks({'enc': pt_cloud, 'ex': x})\n x = x['ex']\n # CBN\n gamma = self.gammaLayer(pt_cloud)\n gamma = torch.stack([gamma for _ in range(k)], dim=2)\n beta = self.betaLayer(pt_cloud)\n beta = torch.stack([beta for _ in range(k)], dim=2)\n x = gamma.mul(self.cbn(x)).add_(beta)\n x = F.relu(x)\n x = self.fc2(x)\n x = x.view(-1, 1)\n x = torch.sigmoid(x)\n\n return x\n","sub_path":"point_completion_occupancy_model/models/point_completion.py","file_name":"point_completion.py","file_ext":"py","file_size_in_byte":5080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"297590558","text":"class BConv:\r\n txt = None\r\n\r\n def __init__(self, text):\r\n self.txt = text\r\n\r\n def convert(self):\r\n toOriginal = []\r\n split_text = list(self.txt)\r\n for i in range(0, len(split_text) - 1):\r\n current = split_text[i]\r\n next = split_text[i + 1]\r\n if current.lower() == \"a\" or current.lower() == \"e\" or current.lower() == \"i\" or current.lower() == \"o\" or current.lower() == \"u\" or current.isspace():\r\n\r\n if next.lower() == \"a\" or next.lower() == \"e\" or next.lower() == \"i\" or next.lower() == \"o\" or next.lower() == \"u\":\r\n toOriginal.append(current + \"+\")\r\n else:\r\n toOriginal.append(current)\r\n else:\r\n toOriginal.append(current + \"+\")\r\n\r\n if next.lower() == \"a\" or next.lower() == \"e\" or next.lower() == \"i\" or next.lower() == \"o\" or next.lower() == \"u\":\r\n toOriginal.append(next)\r\n else:\r\n toOriginal.append(next + \"+\")\r\n\r\n new_str = \" \"\r\n\r\n for item in toOriginal:\r\n new_str += item\r\n\r\n return new_str\r\n\r\n @staticmethod\r\n def listToString(s):\r\n str1 = None\r\n\r\n for ele in s:\r\n str1 += ele\r\n\r\n return str1\r\n","sub_path":"BaybayinConverter/BConv.py","file_name":"BConv.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"497568289","text":"#! python3\n'''Cleans all the recipes in the folder, does not do anything to already\nclean recipes. Ignores any file that starts with an underscore'''\n\nimport sys\nimport os\nimport re\nfrom os.path import join as join_path\n\n\nbad = r\"1/2 1/3 1/4 1/8 2/3 3/4 3/8 5/8 7/8 tsp tbsp Tbsp tbs(?!p) Tbs(?!p) cup Oz Lb\".split(\" \")\ngood = \"½ ⅓ ¼ ⅛ ⅔ ¾ ⅜ ⅝ ⅞ tsp Tbsp Tbsp Tbsp Tbsp Cup oz lb\".split(\" \")\nrepls = list(zip(bad, good))\n\ndef fix_title(title):\n new_title = re.sub(r\"\\.|'|,\", \"\", title)\n new_title = re.sub(\"&\", \"and\", new_title)\n new_title = re.sub(\" \", \"-\", new_title)\n new_title = re.sub(\"---\", \"--\", new_title)\n new_title = re.sub(r\"\\(|\\)\", \"_\", new_title)\n return new_title.strip()\n\ndef clean(text):\n \"\"\"fix measures, fractions, and some other things\"\"\"\n #clean structure\n text = re.sub(r\"(? \").casefold()\n \n if chap == \"savory\".casefold():\n dest_folder = savory_folder\n page_template = savory_template\n \n elif chap == \"sweet\".casefold():\n dest_folder = sweet_folder\n page_template = sweet_template\n \n else:\n input(\"I don't know what {} means \".format(chap))\n sys.exit(1)\n \n found = all_local_files(source_folder, dest_folder)\n if not found:\n print(\"No new files found? Updating index anyway.\")\n else:\n print(\"Updating index.\")\n \n items = generate_list(dest_folder, list_entry_template)\n index_text = page_template+''.join(items)\n\n with open(join_path(dest_folder, \"index.markdown\"), \"w\", encoding=\"utf8\") as file:\n file.write(index_text)\n print(\"New index generated.\")\n\n input(\"press enter to end. \")\n\nmain()","sub_path":"markdown pages/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":4686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"372862947","text":"#coding = utf-8\n'''\n删除圈子浏览历史记录\n\n'''\n\nimport requests\nimport hashlib\nimport json\nfrom USER.Login import login\nfrom pprint import pprint\n\n\nu_id,u_token = login()#直接使用两个变量来接收login()函数返回的两个值,这就是利用了 Python 提供的序列解包功能。\napp_key_old = 'c40e32c6ac99617b'\napp_key = '193dd7cc7845df55'\nsign_new = '6cefaf5e35a382e6'\nget_id = '39938'\n\n'''\n获取帖子浏览历史\n'''\n\ndef get_history():\n data = 'appkey=%s&pg=1&token=%s&userId=%s|%s'%(app_key,u_token,u_id,sign_new)\n signs = hashlib.md5(data.encode(encoding='utf-8')).hexdigest()\n return signs\n\ndef history_list():\n url = 'http://a.api1.peiyinxiu.com/Api/Topic/GetTopicHistoryList'\n header = {'Content-Type':'application/json'}\n data = {'appkey':app_key,'pg':'1','token':u_token,'userId':u_id,'sign':get_history()}\n resq = requests.get(url,params=data,headers= header)\n # pprint(resq.text)\n # 编码:把一个Python对象编码转换成Json字符串\n # json.dumps()\n # 解码:把Json格式字符串解码转换成Python对象\n # json.loads()\n get_date = json.loads(resq.text)\n dates = get_date['data']\n pprint(dates)\n '''取出帖子ID'''\n ID_list = []\n for id in range(len(dates)):\n ID = dates[id]['id']\n ID_list.append(ID)\n print(ID_list)\n\ndef get_sign():\n data = 'appkey=%s&id=%s&token=145e1bdddacaaa7038e5be88fddbb209&userId=%s|%s'%(app_key,get_id,use_id,sign_new)\n signs = hashlib.md5(data.encode(encoding='utf-8')).hexdigest()\n return signs\n\ndef deletehistory():\n url = 'http://a.api1.peiyinxiu.com/Api/Topic/DeleteTopicHistory'\n headers = {'Content-Type':'application/json'}\n data ={'appkey':app_key,'id':get_id,'token':'145e1bdddacaaa7038e5be88fddbb209','userId':use_id,'sign':get_sign()}\n resq = requests.post(url,params=data,headers=headers)\n print(resq.text)\n\n'''\n清空所有圈子浏览历史记录\n'''\ndef deletehistory_all():\n sign_data = 'appkey=%s&token=145e1bdddacaaa7038e5be88fddbb209&userId=%s|%s'%(app_key,use_id,sign_new)\n signs = hashlib.md5(sign_data.encode(encoding='utf-8')).hexdigest()\n\n url = 'http://a.api1.peiyinxiu.com/Api/Topic/DeleteTopicHistoryAll'\n headers = {'Content-Type':'application/json'}\n data = {\n 'appkey' : app_key ,\n 'token' : '145e1bdddacaaa7038e5be88fddbb209' ,\n 'userId' : use_id ,\n 'sign' : signs\n }\n\n resp = requests.post(url,params= data,headers= headers)\n print(resp.text)\n\n\nif __name__==\"__main__\":\n # deletehistory()\n # deletehistory_all()\n history_list()\n","sub_path":"Circle/DeleteHistory.py","file_name":"DeleteHistory.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"569322681","text":"import parse_data\nimport difflib\nimport sys\nimport os\nimport pickle\nimport random\n\ndef build_ngrams(inDocs, outDocs, n):\n igrams = []\n ograms = []\n for di, do in zip(inDocs, outDocs):\n if len(di) < len(do):\n di = di + ['NULL' for i in range(len(do) - len(di))]\n elif len(do) < len(di):\n do = do + ['NULL' for i in range(len(di) - len(do))]\n for i in range(len(di) - n + 1):\n igrams.append(di[i:i+n])\n ograms.append(do[i:i+n])\n\n return igrams, ograms\n\ndef countPairs(igrams, ograms):\n counts = {}\n for ig, og in zip(igrams, ograms):\n ig = ' '.join(ig)\n og = ' '.join(og)\n if ig not in counts:\n counts[ig] = {}\n\n counts[ig][og] = counts[ig].get(og, 0) + 1\n\n return counts\n\n# Count common replacements\ndef countReplacements(toks):\n cts = {}\n i=0\n for di, do in toks:\n sys.stdout.write('\\r{:d}'.format(i))\n i+=1\n diff = difflib.ndiff(di, do)\n\n prevWord = None\n addChain = []\n delChain = []\n for x in diff:\n prefix = x[0]\n text = x[2:]\n if prefix == ' ':\n addText = ' '.join(addChain)\n\n # If just an insertion, no deleted words\n # Treat it as a replacement of adjacent words with more text\n if len(addChain) > 0 and len(delChain) == 0:\n if prevWord is not None:\n if prevWord not in cts:\n cts[prevWord] = {}\n addBeforeText = prevWord + ' ' + addText\n cts[prevWord][addBeforeText] = cts[prevWord].get(addBeforeText, 0) + 1\n\n if text not in cts:\n cts[text] = {}\n addAfterText = addText + ' ' + text\n cts[text][addAfterText] = cts[text].get(addAfterText, 0) + 1\n # Otherwise, it is a replacement if either chain is non-empty\n elif len(addChain) > 0 or len(delChain) > 0:\n delText = ' '.join(delChain)\n if delText not in cts:\n cts[delText] = {}\n cts[delText][addText] = cts[delText].get(addText, 0) + 1\n\n addChain = []\n delChain = []\n prevWord = text\n elif prefix == '+':\n addChain.append(text)\n elif prefix == '-':\n delChain.append(text)\n\n # A replacement at the end of the document\n addText = ' '.join(addChain)\n delText = ' '.join(delChain)\n if len(addChain) > 0 and len(delChain) == 0:\n if prevWord is not None:\n if prevWord not in cts:\n cts[prevWord] = {}\n addBeforeText = prevWord + ' ' + addText\n cts[prevWord][addBeforeText] = cts[prevWord].get(addBeforeText, 0) + 1\n elif len(addChain) > 0 or len(delChain) > 0:\n if delText not in cts:\n cts[delText] = {}\n cts[delText][addText] = cts[delText].get(addText, 0) + 1\n\n print()\n return cts\n\ndef ngramTermFreq(toks, n=3):\n tf = {}\n it=0\n for di, do in toks:\n sys.stdout.write('\\r{:d}'.format(it))\n it+=1\n for i in range(1, n+1):\n igrams, ograms = build_ngrams([di], [do], i)\n for w in igrams:\n w = ' '.join(w)\n tf[w] = tf.get(w,0) + 1\n print()\n return tf\n\n\n\ndef relativeReplaceFreq(toks, thresh=10):\n cts = countReplacements(toks)\n tf = ngramTermFreq(toks, 2)\n res = {w: {k: v/tf[w] for k,v in cts[w].items()} for w in cts if tf.get(w,0) > thresh}\n return res\n\n\n\ndef doReplace(grams, cts):\n igrams, ograms = grams\n res = []\n for x in igrams:\n x = ' '.join(x)\n if x in cts:\n bestRep = max(cts[x], key=lambda y: cts[x][y])\n if sum(cts[x].values()) > 30:\n res += bestRep.split(' ')\n else:\n res.append([x])\n else:\n res.append([x])\n return res\n\ndef doReplaceFreqReplace(docs, cts, n=5):\n res = []\n for d in docs:\n rd = []\n j = 0\n while j < len(d):\n rep = False\n for k in range(1, n+1):\n if j+k <= len(d):\n w = ' '.join(d[j:j+k])\n if w in cts:\n rd += cts[w].split(' ')\n j+=k\n rep=True\n break\n if not rep:\n rd.append(d[j])\n j+=1\n res.append(rd)\n return res\n\n\ndef termFreq(docs):\n cts = {}\n for di, do in docs:\n for w in di:\n cts[w] = cts.get(w,0) + 1\n return cts\n\n\ndef loadOrElse(path, func):\n if os.path.exists(path):\n with open(path, 'rb') as inFile:\n res = pickle.load(inFile)\n else:\n res = func()\n with open(path, 'wb') as outFile:\n pickle.dump(res, outFile)\n return res\n\ndef testReplacementModel(cts, tf, N, testToks, countThresh, freqThresh):\n cts = {w: {k: v/tf[w] for k,v in cts[w].items()} for w in cts if tf.get(w,0) > countThresh}\n cts = {w: max(cts[w].items(), key=lambda x: x[1]) for w in cts}\n cts = {k: v[0] for k,v in cts.items() if v[1] >= freqThresh}\n print(\"Num replacements: \" + str(len(cts)))\n print(\"Doing replacements\")\n res = doReplaceFreqReplace(map(lambda x: x[0], testToks), cts, N)\n print(\"Scoring\")\n sumRep = 0\n for r, t in zip(res, testToks):\n dr = r\n di, do = t\n sumRep += difflib.SequenceMatcher(None, dr, do).ratio()\n\n\n return sumRep/len(testToks), cts\n\n\n#Current best: 0.815602 acc, 87 count, 0.343530 freq\ndef replacementModelFineTune():\n N = 5\n # toks = parse_data.readTokens('data/train.uniq.tsv')\n print('Reading data')\n toks = loadOrElse('toks.pkl', lambda: parse_data.readTokens('/home/henry/Downloads/5gram-edits-train.uniq.tsv'))\n testToks = parse_data.readTokens('data/dev.tsv.nopunc.tsv')\n\n # cts = countReplacements(toks)\n print('Doing counts')\n cts = loadOrElse('counts.pkl', lambda: countReplacements(toks))\n tf = loadOrElse('termFreq{:d}.pkl'.format(N), lambda: ngramTermFreq(toks, N))\n\n bestParams = (86,0.310787)\n bestAcc = 0.815564\n while True:\n countThresh = random.randint(1,100)\n freqThresh = random.random()\n acc, model = testReplacementModel(cts, tf, N, testToks, countThresh, freqThresh)\n if acc > bestAcc:\n bestAcc = acc\n bestParams = (countThresh, freqThresh)\n # Save the model for later\n with open('replacementModel.best.pkl', 'wb') as outFile:\n pickle.dump(model, outFile)\n print(\"Last: {:.6f} acc, {:d} count, {:.6f} freq\".format(acc, countThresh, freqThresh))\n print(\"Current best: {:.6f} acc, {:d} count, {:.6f} freq\".format(bestAcc, *bestParams))\n\ndef testPairedModel():\n return 0\n\nif __name__ == '__main__':\n replacementModelFineTune()\n\n\n\n\n","sub_path":"ngram_replace.py","file_name":"ngram_replace.py","file_ext":"py","file_size_in_byte":7098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"33281472","text":"# Copyright 2016 Mellanox Technologies, Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom oslo_config import cfg\n\nfrom networking_mlnx._i18n import _\nfrom networking_mlnx.plugins.ml2.drivers.sdn import constants as sdn_const\n\nsdn_opts = [\n cfg.BoolOpt('sync_enabled',\n help=_(\"Whether synchronising state to an SDN provider is \"\n \"enabled.\"),\n default=True),\n cfg.StrOpt('url',\n help=_(\"HTTP URL of SDN Provider.\"),\n ),\n cfg.StrOpt('domain',\n help=_(\"Cloud domain name in SDN provider \"\n \"(for example: cloudx)\"),\n default='cloudx'\n ),\n cfg.StrOpt('username',\n help=_(\"HTTP username for authentication.\"),\n ),\n cfg.StrOpt('password',\n help=_(\"HTTP password for authentication.\"),\n secret=True,\n default='123456'\n ),\n cfg.IntOpt('timeout',\n help=_(\"HTTP timeout in seconds.\"),\n default=10\n ),\n cfg.IntOpt('sync_timeout', default=10,\n help=_(\"Sync thread timeout in seconds.\")),\n cfg.IntOpt('retry_count', default=-1,\n help=_(\"Number of times to retry a row \"\n \"before failing.\"\n \"To disable retry count value should be -1\")),\n cfg.IntOpt('maintenance_interval', default=300,\n help=_(\"Journal maintenance operations interval \"\n \"in seconds.\")),\n cfg.IntOpt('completed_rows_retention', default=600,\n help=_(\"Time to keep completed rows in seconds.\"\n \"Completed rows retention will be checked every \"\n \"maintenance_interval by the cleanup thread.\"\n \"To disable completed rows deletion \"\n \"value should be -1\")),\n cfg.IntOpt('processing_timeout', default='100',\n help=_(\"Time in seconds to wait before a \"\n \"processing row is marked back to pending.\")),\n cfg.ListOpt('physical_networks',\n default=sdn_const.ANY,\n help=_(\"Comma-separated list of \"\n \"that it will send notification. * \"\n \"means all physical_networks\")),\n]\n","sub_path":"networking_mlnx/plugins/ml2/drivers/sdn/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"133358517","text":"#!/usr/bin/env python\n\n__author__ = 'Adam R. Smith'\n__license__ = 'Apache 2.0'\n\nfrom pyon.core.process import GreenProcess, PythonProcess, GreenProcessSupervisor\nfrom pyon.util.int_test import IonIntegrationTestCase\nfrom unittest import SkipTest\nfrom nose.plugins.attrib import attr\n\nimport time\n\n@attr('UNIT', group='process')\nclass ProcessTest(IonIntegrationTestCase):\n def setUp(self):\n self.counter = 0\n\n def increment(self, amount=1):\n self.counter += amount\n\n def test_green(self):\n self.counter = 0\n proc = GreenProcess(self.increment, 2)\n proc.start()\n self.assertEqual(self.counter, 0)\n proc.join()\n self.assertEqual(self.counter, 2)\n\n def test_supervisor(self):\n self.counter = 0\n sup = GreenProcessSupervisor()\n sup.start()\n proc = sup.spawn(('green', self.increment), amount=2)\n self.assertEqual(self.counter, 0)\n sup.join_children()\n self.assertEqual(self.counter, 2)\n\n def test_supervisor_shutdown(self):\n \"\"\" Test shutdown joining/forcing with timeouts. \"\"\"\n sup = GreenProcessSupervisor()\n sup.start()\n\n import gevent\n self.assertIs(time.sleep, gevent.hub.sleep)\n\n # Test that it takes at least the given timeout to join_children, but not much more\n proc_sleep_secs, proc_count = 0.01, 5\n [sup.spawn(('green', time.sleep), proc_sleep_secs) for i in xrange(5)]\n elapsed = sup.shutdown(2*proc_sleep_secs)\n # MM, 1/12: Ok, I loosened the timing boundaries. Do the tests still work?\n # Enabled 0.2s of slack for all tests\n\n self.assertLess(elapsed - proc_sleep_secs, 0.2)\n\n # this could be trouble\n self.assertLess(elapsed, 0.2 + proc_sleep_secs*3)\n\n # Test that a small timeout forcibly shuts down without waiting\n wait_secs = 0.0001\n [sup.spawn(('green', time.sleep), proc_sleep_secs) for i in xrange(5)]\n elapsed = sup.shutdown(wait_secs)\n self.assertLess(elapsed - wait_secs, 0.2)\n\n # this could be trouble too\n self.assertLess(elapsed, 0.2 + proc_sleep_secs)\n\n # Test that no timeout waits until all finished\n [sup.spawn(('green', time.sleep), proc_sleep_secs) for i in xrange(5)]\n elapsed = sup.shutdown()\n self.assertLess(elapsed - proc_sleep_secs, 0.2)\n\n def test_python(self):\n raise SkipTest('Need a better test here')\n self.counter = 0\n proc = PythonProcess(self.increment, 2)\n proc.start()\n self.assertEqual(self.counter, 0)\n proc.join()\n self.assertEqual(self.counter, 2)\n","sub_path":"pyon/core/test/test_process.py","file_name":"test_process.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"569382243","text":"import dash\nimport dash_table\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output, State\nfrom dash.exceptions import PreventUpdate\nimport pandas as pd\nimport numpy as np\nfrom textwrap import dedent as d\nimport plotly.graph_objs as go\nimport plotly.figure_factory as ff\nimport plotly.express as px\nfrom plotly.offline import plot\nimport dash_table.FormatTemplate as FormatTemplate\nfrom dash_table.Format import Sign\n#from sklearn.externals import joblib\nimport joblib\nfrom util import dynamic_predict\n\nfrom visualization import analysis \n# from visualization import plots \n\ncsv_path = 'data/bank-additional-full.csv'\nmy_analysis = analysis.Analysis(csv_path)\nmyList, labels = my_analysis.map_age()\n\n# Read and modify prediction data\npredictions = pd.read_csv('data/predictions.csv')\n\ndf = predictions.copy()\n\ndf = df[['customer_id', 'age', 'job_transformed', 'poutcome', 'pred', 'prob_1']] # prune columns for example\ndf.sort_values(by = ['prob_1'], ascending = False, inplace = True)\ndf['prob_1'] = np.around(df['prob_1'], decimals = 2)\ndf['is_called'] = 'Not Called'\n\ndf.loc[df['job_transformed'] == 'no_income', 'job_transformed'] = 'No Income'\ndf.loc[df['job_transformed'] == 'higher_income', 'job_transformed'] = 'Higher Income'\ndf.loc[df['job_transformed'] == 'lower_income', 'job_transformed'] = 'Lower Income'\ndf.loc[df['job_transformed'] == 'unknown', 'job_transformed'] = 'Unknown'\n\ndf.loc[df['poutcome'] == 'success', 'poutcome'] = 'Success'\ndf.loc[df['poutcome'] == 'nonexistent', 'poutcome'] = 'None'\ndf.loc[df['poutcome'] == 'failure', 'poutcome'] = 'Failure'\n\ndef marital_state_distribution():\n '''\n This function gives the plot of distribution of people based on marital status.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n\n\n '''\n percents = my_analysis.percentage_of_population('marital')\n v = my_analysis.get_count('marital')['y']\n values = [v[1], v[0], v[2], v[3]]\n labels = ['Married', 'Divorced', 'Single', 'Unknown']\n my_analysis.get_count('marital')\n explode = (0.2, 0, 0)\n fig = px.pie(percents, values= values, names = labels, \n title = '% of Population based on marital status')\n return fig\n \ndef marital_status_probab():\n '''\n This function gives the plot of probability of success based on people's marital status.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n marital_status_probab = my_analysis.get_probabilities('marital')\n data = marital_status_probab\n data['y'] = data['y']*100\n fig = px.bar(data, x='marital', y='y',\n hover_data=data, labels={'y':'Probability of Success (%)', 'marital': 'Marital Status'},\n height=400, title = 'Probability of success by marital status')\n fig.update_traces(marker_color='#F8A19F', marker_line_color='rgb(111,64,112)',\n marker_line_width=1.5, opacity=0.8)\n return fig\n\ndef education_level_distribution():\n '''\n This function gives plot of distribution of people based on education level.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n \n percents = my_analysis.percentage_of_population('education')\n v = my_analysis.get_count('education')['y']\n values = [v[1], v[0], v[2], v[3], v[4], v[5], v[6], v[7]]\n labels = ['basic_4y', 'basic_6y', 'basic_9y', 'high school', 'illiterate', 'professional course', 'university degree', 'unknown']\n fig = px.pie(percents, values= values, names = labels, \n title = '% of Population based on education')\n return fig\n\ndef education_level_prob():\n '''\n This function gives the plot of probability of success based on people's education level.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n data = my_analysis.get_probabilities('education')\n data['y'] = data['y']*100\n fig = px.bar(data, x='education', y='y',\n hover_data=data, labels={'y':'Probability of Success (%)', 'education': 'Education Level'},\n height=400, title = 'Probability of success by education')\n fig.update_traces(marker_color='#F8A19F', marker_line_color='rgb(111,64,112)',\n marker_line_width=1.5, opacity=0.8)\n return fig\n\ndef income_level_distribution():\n '''\n This function gives plot of distribution of people based on income level.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n percents = my_analysis.percentage_of_population('job')\n v = my_analysis.get_count('job')['y']\n values = [v[1], v[0], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11]]\n labels = ['admin', 'blue-collar', 'entrepreneur', 'house maid', 'management', 'retired', 'self-employed', 'services', 'student', 'technician', 'unemployed', 'unknown']\n fig = px.pie(percents, values= values, names = labels, \n title = '% of Population based on job')\n return fig\n\ndef job_prob():\n '''\n This function gives the plot of probability of success based on people's job level.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n job_prob = my_analysis.get_probabilities('job')\n data = job_prob\n data['y'] = data['y']*100\n fig = px.bar(data, x='job', y='y',\n hover_data=data, labels={'y':'Probability of Success (%)', 'job': 'Job'},\n height=400, title = 'Probability of success by job')\n fig.update_traces(marker_color='#F8A19F', marker_line_color='rgb(111,64,112)',\n marker_line_width=1.5, opacity=0.8)\n return fig\n\ndef contact_way_distribution():\n '''\n This function gives plot of distribution of people based on how they were contacted, i.e, cell phone or telephone.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n contact_count = my_analysis.get_count('contact')\n contact_success_count = my_analysis.get_success_count('contact')\n status=['cellular', 'telephone']\n\n fig = go.Figure(data=[\n go.Bar(name='Not Successful', x=status, y=contact_count['y']-contact_success_count['y']),\n go.Bar(name='Success', x=status, y=contact_success_count['y'])\n ])\n # Change the bar mode\n fig.update_layout(barmode='stack', xaxis_title=\"Contact type\", yaxis_title=\"Number of people\", title = 'Number of people contacted on cellular phone or telephone')\n return fig\n\ndef contact_prob():\n '''\n This function gives plot of probability of success based on how people were contacted, i.e, cell phone or telephone.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n contact_prob = my_analysis.get_probabilities('contact')\n data = contact_prob\n data['y'] = data['y']*100\n fig = px.bar(data, x='contact', y='y',\n hover_data=data, labels={'y':'Probability of Success (%)', 'contact': 'Contact type'},\n height=400, title = 'Probability of success by method of contact')\n fig.update_traces(marker_color='#F8A19F', marker_line_color='rgb(111,64,112)',\n marker_line_width=1.5, opacity=0.8)\n return fig\n\ndef loan_status():\n '''\n This function gives the plot of distribution of people based on loan status.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n loan_count = my_analysis.get_count('loan')\n loan_success_count = my_analysis.get_success_count('loan')\n status=['yes', 'no', 'Info Not Available']\n\n fig = go.Figure(data=[\n go.Bar(name='Not Successful', x=status, y=loan_count['y']-loan_success_count['y']),\n go.Bar(name='Success', x=status, y=loan_success_count['y'])\n ])\n # Change the bar mode\n fig.update_layout(barmode='stack', title = \"Do people have a loan?\", xaxis_title = \"Loan status\", yaxis_title=\"Number of people\", height=400)\n return fig\n\ndef loan_prob():\n '''\n This function gives plot of probability of success based on people's loan status.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n loan_prob = my_analysis.get_probabilities('loan')\n data = loan_prob\n data['y'] = data['y']*100\n fig = px.bar(data, x='loan', y='y',\n hover_data=data, labels={'y':'Probability of Success (%)', 'loan': 'Loan status'},\n height=400, title = 'Probability of success by loan status')\n fig.update_traces(marker_color='#F8A19F', marker_line_color='rgb(111,64,112)',\n marker_line_width=1.5, opacity=0.8)\n return fig\n\ndef house_status_distribution():\n '''\n This function gives the plot of distribution of people based on housing status.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n housing_count = my_analysis.get_count('housing')\n housing_success_count = my_analysis.get_success_count('housing')\n status=['yes', 'no', 'Info Not Available']\n\n fig = go.Figure(data=[\n go.Bar(name='Not Successful', x=status, y=housing_count['y']-housing_success_count['y']),\n go.Bar(name='Success', x=status, y=housing_success_count['y'])\n ])\n # Change the bar mode\n fig.update_layout(barmode='stack', xaxis_title=\"Housing Status\", yaxis_title=\"Number of people\", height=400, title = 'Housing status of the population')\n return fig\n\ndef house_prob():\n '''\n This function gives plot of probability of success based on people's housing status.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n housing_prob = my_analysis.get_probabilities('housing')\n data = housing_prob\n data['y'] = data['y']*100\n fig = px.bar(data, x='housing', y='y',\n hover_data=data, labels={'y':'Probability of Success (%)', 'housing': 'Housig Status'},\n height=400, title = 'Probability of success by housing status')\n fig.update_traces(marker_color='#F8A19F', marker_line_color='rgb(111,64,112)',\n marker_line_width=1.5, opacity=0.8)\n return fig\n\ndef prediction_pie_chart():\n '''\n Plot predicted telecaller success ratios on the test data.\n \n :return: Plots the prediction pie chart.\n :rtype: plotly.graph_objs._figure.Figure\n '''\n fig = px.pie(predictions, \n values=[1 for i in range(len(predictions))], \n names= np.where(predictions['pred'] == 1, 'Purchase', 'No Purchase'), \n title='Overall Telemarketing Success Predictions')\n return fig\n\ndef predicted_prob_hist():\n '''\n Plot the histogram of the predicted probabilities.\n \n :return: Plots the prediction probability histogram.\n :rtype: plotly.graph_objs._figure.Figure\n '''\n fig = px.histogram(predictions, \n x=\"prob_1\", \n nbins=5, \n labels = {'prob_1' : 'Success Probabilty'},\n title='Histogram of Success Probabilities')\n return fig\n\ndef age_distribution():\n '''\n This function gives the plot of distribution of people's responses based on age groups that they fall in.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n No = [x[0] for x in myList]\n Yes = [x[1] for x in myList]\n x = np.arange(len(labels)) \n width = 0.20 \n\n fig = go.Figure()\n fig.add_trace(go.Bar(\n x=x - width/2,\n y = No,\n name='NO',\n marker_color='indianred'\n ))\n fig.add_trace(go.Bar(\n x=x + width/2,\n y = Yes,\n name='YES',\n marker_color='lightsalmon'\n ))\n\n fig.update_layout(\n title = 'Count of yes/no response for different age groups',\n xaxis_title=\"Age Group\",\n yaxis_title=\"Number of People\",\n xaxis = dict(\n tickmode = 'array',\n tickvals = [i for i in range(len(labels))],\n ticktext = labels\n )\n )\n return fig\n\ndef age_prob():\n '''\n This function gives the plot of distribution of people's responses based on age groups that they fall in.\n\n Returns\n -------\n plotly.graph_objs._figure.Figure\n returns a interactive graph of marital status distribution.\n \n \n '''\n data = my_analysis.get_success_count(\"age\")\n fig = px.bar(data, x='age', y='y',\n hover_data=data, labels={'y':'Number of Success (%)', 'age': 'Age'},\n height=400, title = 'Success for different ages')\n fig.update_traces(marker_color='#F8A19F', marker_line_color='rgb(111,64,112)',\n marker_line_width=1.5, opacity=0.8)\n return fig\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\n\n#app.scripts.config.serve_locally = True\n\napp.config['suppress_callback_exceptions'] = True\ncolors = {\n 'background': '#111111',\n 'text': '#7FDBFF'\n}\n\ntab_style = {\n 'fontWeight': 'bold'\n}\nvis_tab_style = {\n 'borderBottom': '1px solid #d6d6d6',\n 'padding': '12px',\n}\n\ntab_selected_style = {\n 'borderTop': '1px solid #d6d6d6',\n 'borderBottom': '1px solid #d6d6d6',\n 'backgroundColor': '#119DFF',\n 'color': 'white',\n 'padding': '12px'\n}\napp.layout = html.Div(children = [\n dcc.Tabs(id=\"tabs\", value='tab-1', children=[\n dcc.Tab(label='Manager Dashboard', value='tab-1', style=tab_style),\n dcc.Tab(label='Telecaller Dashboard', value='tab-2', style=tab_style),\n dcc.Tab(label='Live Prediction Dashboard', value='tab-new', style=tab_style),\n ]),\n html.Div(id='tabs-content')\n])\nlayout_tab_1 = html.Div(children = [\n dcc.Tabs(id = \"vis-tabs\", value = \"vistab\", vertical=True, parent_style={'float': 'left','width': '40'},children =[\n dcc.Tab(label='Marital Status', value='tab-3', style=vis_tab_style, selected_style=tab_selected_style),\n dcc.Tab(label='Educational Level', value='tab-4', style=vis_tab_style, selected_style=tab_selected_style),\n dcc.Tab(label='Income&Job', value='tab-5', style=vis_tab_style, selected_style=tab_selected_style),\n dcc.Tab(label='Contact Type', value='tab-6', style=vis_tab_style, selected_style=tab_selected_style),\n dcc.Tab(label='Loan Status', value='tab-7', style=vis_tab_style, selected_style=tab_selected_style),\n dcc.Tab(label='Housing Status', value='tab-8', style=vis_tab_style, selected_style=tab_selected_style),\n dcc.Tab(label='Age', value='tab-9', style=vis_tab_style, selected_style=tab_selected_style),\n dcc.Tab(label='Prediction Overview', value='tab-10', style=vis_tab_style, selected_style=tab_selected_style),\n ]),\n html.Div(id='vis-tabs-content',style={'float': 'right'})\n])\n\nmarital_status_vis = html.Div(children =[\n html.Div([\n html.Div(children =[\n dcc.Graph(\n id = \"marital status\",\n figure = marital_state_distribution()\n ) ],\n style={'height': 400,'width': '300', 'float': 'left', 'display': 'flex', 'justify-content': 'center' }),\n\n html.Div(children =[\n dcc.Graph(\n id = \"marital prob\",\n figure = marital_status_probab()\n )],\n style={'height': 400,'width': '400', 'float': 'left', 'display': 'flex', 'justify-content': 'center'})\n ]),\n\n ])\neducational_Level_vis = html.Div(children =[\n html.Div([\n html.Div(children =[\n dcc.Graph(\n id = \"marital status\",\n figure = education_level_distribution()\n ) ],\n style={'height': 400,'width': '300', 'float': 'left', 'display': 'flex', 'justify-content': 'center'}),\n\n html.Div(children =[\n dcc.Graph(\n id = \"marital prob\",\n figure = education_level_prob()\n )],\n style={'height':400,'width': '400', 'float': 'left', 'display': 'flex', 'justify-content': 'center'})\n ]),\n\n])\n\nincome_vis = html.Div(children =[\n\n html.Div([\n html.Div(children =[\n dcc.Graph(\n id = \"marital status\",\n figure = income_level_distribution()\n ) ],\n style={'height': 400,'width': '300', 'float': 'left', 'display': 'flex', 'justify-content': 'center'}),\n\n html.Div(children =[\n dcc.Graph(\n id = \"marital prob\",\n figure = job_prob()\n )],\n style={'height':400,'width': '400', 'float': 'left', 'display': 'flex', 'justify-content': 'center'})\n ]),\n\n])\n\ncontact_vis = html.Div(children =[\n html.Div([\n html.Div(children =[\n dcc.Graph(\n id = \"marital status\",\n figure = contact_way_distribution()\n ) ],\n style={'height': 400,'width': '400', 'float': 'left', 'display': 'flex', 'justify-content': 'center'}),\n\n html.Div(children =[\n dcc.Graph(\n id = \"marital prob\",\n figure = contact_prob()\n )],\n style={'height':400,'width': '400', 'float': 'left', 'display': 'flex', 'justify-content': 'center'})\n ]),\n\n])\n\nloan_vis = html.Div(children =[\n html.Div([\n html.Div(children =[\n dcc.Graph(\n id = \"marital status\",\n figure = loan_status()\n ) ],\n style={'height': 400,'width': '400', 'float': 'left', 'display': 'flex', 'justify-content': 'center'}),\n\n html.Div(children =[\n dcc.Graph(\n id = \"marital prob\",\n figure = loan_prob()\n )],\n style={'height':400,'width': '400', 'float': 'left', 'display': 'flex', 'justify-content': 'center'})\n ]),\n\n])\nhouse_vis = html.Div(children =[ \n html.Div([\n html.Div(children =[\n dcc.Graph(\n id = \"marital status\",\n figure = house_status_distribution()\n ) ],\n style={'height': 400,'width': '400', 'float': 'left', 'display': 'flex', 'justify-content': 'center'}),\n\n html.Div(children =[\n dcc.Graph(\n id = \"marital prob\",\n figure = house_prob()\n )],\n style={'height':400,'width': '400', 'float': 'left', 'display': 'flex', 'justify-content': 'center'})\n ]),\n\n])\n\n\nprediction_vis = html.Div(children =[\n html.Div([\n html.Div(children =[\n dcc.Graph(\n id = \"prediction_pie_chart\",\n figure = prediction_pie_chart()\n ) ],\n style={'height': 400,'width': '300', 'float': 'left', 'display': 'flex', 'justify-content': 'center'}),\n\n html.Div(children =[\n dcc.Graph(\n id = \"predicted_prob_hist\",\n figure = predicted_prob_hist()\n )],\n style={'height':400,'width': '400', 'float': 'left', 'display': 'flex', 'justify-content': 'center'})\n ]),\n\n ])\n\nage_vis = html.Div(children =[\n html.Div([\n html.Div(children =[\n dcc.Graph(\n id = \"prediction_pie_chart\",\n figure = age_distribution()\n ) ],\n style={'height': 400,'width': '300', 'float': 'left', 'display': 'flex', 'justify-content': 'center'}),\n\n html.Div(children =[\n dcc.Graph(\n id = \"predicted_prob_hist\",\n figure = age_prob()\n )],\n style={'height':400,'width': '400', 'float': 'left', 'display': 'flex', 'justify-content': 'center'})\n ]),\n\n ])\n\n@app.callback(Output('vis-tabs-content', 'children'),\n [Input('vis-tabs', 'value')])\ndef render_content(tab):\n if tab == 'tab-3':\n return marital_status_vis\n elif tab == 'tab-4':\n return educational_Level_vis\n elif tab == 'tab-5':\n return income_vis \n elif tab == 'tab-6':\n return contact_vis \n elif tab == 'tab-7':\n return loan_vis \n elif tab == 'tab-8':\n return house_vis \n elif tab == 'tab-9':\n return age_vis\n elif tab == \"tab-10\":\n return prediction_vis\n else:\n return marital_status_vis\n\n\nlayout_tab_2 = html.Div(children =[\n \n html.Div(dash_table.DataTable(\n columns=[\n {'name': 'Customer ID', 'id': 'customer_id', 'type': 'numeric', 'editable': False},\n {'name': 'Age', 'id': 'age', 'type': 'numeric', 'editable': False},\n {'name': 'Income', 'id': 'job_transformed', 'type': 'text', 'editable': False},\n {'name': 'Previously Contacted', 'id': 'poutcome', 'type': 'text', 'editable': False},\n {'name': 'Probability of Success', 'id': 'prob_1', 'type': 'numeric', 'editable': False, 'format': FormatTemplate.percentage(1)},\n {'name': 'Call Result', 'id': 'is_called', 'type': 'any', 'editable': True, 'presentation': 'dropdown'}\n ],\n data=df.to_dict('records'),\n filter_action='native',\n dropdown={\n 'is_called': {\n 'options': [\n {'label': i, 'value': i}\n for i in ['Not Called', 'Success', 'Failure']\n ]\n }\n }, \n style_table={\n 'maxHeight': '50ex',\n 'overflowY': 'scroll',\n 'width': '100%',\n 'minWidth': '100%',\n },\n style_data={\n 'width': '150px', 'minWidth': '150px', 'maxWidth': '150px',\n 'overflow': 'hidden',\n 'textOverflow': 'ellipsis',\n },\n style_cell = {\n 'font_family': 'arial',\n 'font_size': '16px',\n 'text_align': 'center'\n },\n# style_cell_conditional=[\n# {\n# 'if': {'column_id': c},\n# 'textAlign': 'left'\n# } for c in ['customer_id', 'job_transformed', 'poutcome', 'is_called']\n# ],\n style_data_conditional=[\n {\n 'if': {'row_index': 'odd'},\n 'backgroundColor': 'rgb(248, 248, 248)'\n }, {\n 'if': {\n 'column_id': 'is_called',\n 'filter_query': '{is_called} eq \"Not Called\"'\n },\n 'backgroundColor': '#E0E280'\n }, {\n 'if': {\n 'column_id': 'is_called',\n 'filter_query': '{is_called} eq \"Success\"'\n },\n 'backgroundColor': '#8CE280'\n }, {\n 'if': {\n 'column_id': 'is_called',\n 'filter_query': '{is_called} eq \"Failure\"'\n },\n 'backgroundColor': '#E28080'\n }\n ],\n style_header={\n 'backgroundColor': 'rgb(230, 230, 230)',\n 'fontWeight': 'bold'\n },\n page_action=\"native\",\n page_current= 0,\n sort_action=\"native\",\n sort_mode=\"multi\"\n ) \n ) \n \n ])\n\nlayout_tab_new = html.Div(children =[\n html.Div(children =[\n html.Div(children =[\n html.Label('Enter number of employees (quarterly indicator): '),\n dcc.Input(id='nremployed', placeholder='# employees', type='number')],\n style={'float': 'center', 'display': 'flex', 'justify-content': 'center'}),\n \n html.Div(children =[\n html.Label('Enter the outcome of the previous marketing campaign: '),\n dcc.Input(id='poutcome_success', placeholder='prev.', type='number', min = 0, max = 1, step = 1)],\n style={'float': 'center', 'display': 'flex', 'justify-content': 'center'}),\n \n html.Div(children =[\n html.Label('Enter the employment variation rate - quarterly indicator: '),\n dcc.Input(id='emp', placeholder='emp. variation rate', type='number')],\n style={'float': 'center', 'display': 'flex', 'justify-content': 'center'}),\n \n html.Div(children =[\n html.Label('Enter the number of days since the last call (999 if NA): '),\n dcc.Input(id='pdays', placeholder='# days since last call', type='number')],\n style={'float': 'center', 'display': 'flex', 'justify-content': 'center'}),\n \n html.Div(children =[\n html.Label('Enter the consumer confidence index (monthly indicator): '),\n dcc.Input(id='consconfidx', placeholder='consumer conf. index', type='number')],\n style={'float': 'center', 'display': 'flex', 'justify-content': 'center'}),\n \n html.Div(children =[\n html.Label('Enter the euribor 3 month rate (daily indicator): '),\n dcc.Input(id='euribor3m', placeholder='euribor rate', type='number')],\n style={'float': 'center', 'display': 'flex', 'justify-content': 'center'}),\n \n html.Div(children =[\n html.Label('Enter the no income indicator, 1 if the customer job retired, student or unemployed: '),\n dcc.Input(id='job_transformed_no_income', placeholder='inc', type='number', min = 0, max = 1, step = 1)],\n style={'float': 'center', 'display': 'flex', 'justify-content': 'center'}),\n \n ]),\n \n html.Div(children=[\n html.H1(children='Probability of Success: '),\n html.Div(id='pred-output')\n ], style={'textAlign': 'center', 'justify-content': 'center'}),\n])\n@app.callback(\n Output('pred-output', 'children'),\n [Input('nremployed', 'value'),\n Input('poutcome_success', 'value'),\n Input('emp', 'value'),\n Input('pdays', 'value'),\n Input('consconfidx', 'value'),\n Input('euribor3m', 'value'),\n Input('job_transformed_no_income', 'value')])\ndef show_success_probability(nr_employed, poutcome_success, emp_var_rate, pdays, cons_conf, euribor, no_income):\n if not nr_employed: \n nr_employed = 0\n if not poutcome_success: \n poutcome_success = 0\n if not emp_var_rate: \n emp_var_rate = 0\n if not pdays: \n pdays = 0\n if not cons_conf: \n cons_conf = 0\n if not euribor: \n euribor = 0\n if not no_income:\n no_income = 0\n \n #raise PreventUpdate\n #else:\n prob = dynamic_predict(nr_employed, poutcome_success, emp_var_rate, pdays, cons_conf, euribor, no_income)[0]*100\n return html.Div(children =[\n html.H1(children=f'{round(prob, ndigits = 2)}'+\"%\")\n ])\n\n\n@app.callback(Output('tabs-content', 'children'),\n [Input('tabs', 'value')])\ndef render_content(tab):\n if tab == 'tab-1':\n return layout_tab_1\n elif tab == 'tab-2':\n return layout_tab_2\n elif tab == \"tab-new\":\n return layout_tab_new\n\nserver = app.server\n\nif __name__ == '__main__':\n model = joblib.load(\"LR_prediction.joblib\")\n #app.run_server(debug=True)\n #application.run_server(host='0.0.0.0', port=8050, debug=True)\n #application.run(debug=True, port=8080)\n #application.run_server(host='0.0.0.0')\n #app.run_server(host=\"0.0.0.0\")\n app.run_server()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":29384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"569657963","text":"captain_list= ['Ajinkya Rahane\\n', 'Virat Kohli\\n', 'Mahendra Singh Dhoni\\n', 'Anil Kumble\\n', 'Virender Sehwag\\n', 'Rahul Dravid\\n',\n 'Sourav Ganguly\\n', 'Sachin Tendulkar\\n', 'Mohammad Azharuddin\\n', 'Krishnamachari Srikkanth\\n', 'Ravi Shastri\\n',\n 'Dilip Vengsarkar\\n', 'Kapil Dev\\n', 'Gundappa Viswanath\\n', 'Bishan Singh Bedi\\n', 'Sunil Gavaskar\\n']\n\n\nfile_name = 'indian_cricket_captains.txt'\ndef write_line_to_file():\n try:\n f = open(file_name,'a')\n name = input('Enter Name of the Captains \\t:\\t')\n f.write(name+'\\n')\n except Exception as e:\n print(e)\n finally:\n f.close()\n\n\ndef write_multiple_lines_to_file():\n try:\n f = open(file_name, 'a')\n f.writelines(captain_list)\n except Exception as e:\n print(e)\n finally:\n f.close()\n\n\ndef read_all_line_from_file(number_of_chars = 0, seek_pos=0):\n try:\n with open(file_name, 'r') as read_file:\n if number_of_chars >=1:\n # data = read_file.read(number_of_chars)\n # print(data)\n # print(read_file.tell())\n # read_file.seek(seek_pos)\n data = read_file.read(number_of_chars)\n print(data)\n print(read_file.tell())\n read_file.seek(80)\n print(read_file.tell())\n print(read_file.read(80))\n print(read_file.tell())\n else:\n data = read_file.read()\n print(data)\n print(read_file.tell())\n except Exception as e:\n print(e)\n\n\ndef read_line_from_file():\n try:\n with open(file_name, 'r') as read_file:\n data1 = read_file.readline()\n print(data1, end='')\n data2 = read_file.readline()\n print(data2, end='')\n # for data in read_file:\n # print(data)\n except Exception as e:\n print(e)\n\n\ndef read_lines_from_file():\n try:\n with open(file_name, 'r') as read_file:\n data = read_file.readlines()\n print(data)\n except Exception as e:\n print(e)\n\n\n# write_line_to_file()\n# write_multiple_lines_to_file()\n# read_line_from_file()\n# read_lines_from_file()\n# read_all_line_from_file(40,90)\n\n\nimport os, sys\ndef file_exists():\n try:\n if os.path.isfile(file_name):\n print(True)\n f = open(file_name, 'r')\n else:\n print(False)\n\n if os.path.exists(file_name):\n print(True)\n else:\n print(False)\n\n lcount = wcount = ccount = 0\n for line in f:\n lcount = lcount+1\n ccount = ccount + len(line)\n words = line.split()\n wcount = wcount + len(words)\n print('Line Counts\\t:\\t',lcount)\n print('Word Counts\\t:\\t',wcount)\n print('Char Counts\\t:\\t',ccount)\n\n except Exception as e:\n print(e)\nfile_exists()","sub_path":"files_practise/file_handling.py","file_name":"file_handling.py","file_ext":"py","file_size_in_byte":2974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"111875137","text":"from django.urls import path\nfrom .views import *\n\napp_name = 'blog'\n\nurlpatterns = [\n path('', post_list, name='post_list'),\n path('/', post_detail, name='post_detail'),\n path('category//', show_category, name='category'),\n path('category///', post_detail, name='post_detail'),\n]\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"485733613","text":"\"\"\"\nCreated on 11/13/2019\n@author: Jingchao Yang\n\nhttps://www.kaggle.com/robikscube/tutorial-time-series-forecasting-with-xgboost\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport xgboost as xgb\nfrom xgboost import plot_importance, plot_tree\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error\n\nplt.style.use('fivethirtyeight')\n\n\ndef create_features(df, label=None):\n \"\"\"\n Creates time series features from datetime index\n \"\"\"\n df['date'] = df.index\n df['hour'] = df['date'].dt.hour\n df['dayofweek'] = df['date'].dt.dayofweek\n df['quarter'] = df['date'].dt.quarter\n df['month'] = df['date'].dt.month\n df['year'] = df['date'].dt.year\n df['dayofyear'] = df['date'].dt.dayofyear\n df['dayofmonth'] = df['date'].dt.day\n df['weekofyear'] = df['date'].dt.weekofyear\n\n X = df[['hour', 'dayofweek', 'quarter', 'month', 'year',\n 'dayofyear', 'dayofmonth', 'weekofyear']]\n if label:\n y = df[label]\n return X, y\n return X\n\n\npjme = pd.read_csv('sampleData/PJME_hourly.csv', index_col=[0], parse_dates=[0])\nsplit_date = '01-Jan-2015'\npjme_train = pjme.loc[pjme.index <= split_date].copy()\npjme_test = pjme.loc[pjme.index > split_date].copy()\n\nX_train, y_train = create_features(pjme_train, label='PJME_MW')\nX_test, y_test = create_features(pjme_test, label='PJME_MW')\n\nreg = xgb.XGBRegressor(n_estimators=1000)\nreg.fit(X_train, y_train,\n eval_set=[(X_train, y_train), (X_test, y_test)],\n early_stopping_rounds=50,\n verbose=False) # Change verbose to True if you want to see it train\n\npjme_test['MW_Prediction'] = reg.predict(X_test)\npjme_all = pd.concat([pjme_test, pjme_train], sort=False)\n\npjme_all[['PJME_MW', 'MW_Prediction']].plot(figsize=(15, 5))\nplt.show()\n","sub_path":"Timeseries_Forecasting/XGBoost.py","file_name":"XGBoost.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"257036198","text":"first_name = 'alysson'\nlast_name = \"machado\"\n\n# programmer format \"i like complicated things, love me\"\nidiot_format = first_name.capitalize().__add__(\" \" + last_name.capitalize())\n\n# cool programmer format\ncool_format = first_name + \" \" + last_name\n\nprint(idiot_format)\nprint(cool_format.title())","sub_path":"content_b_variables/ex5_string_concatenation.py","file_name":"ex5_string_concatenation.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"355893430","text":"from django import forms\n#from Customers.autocomplete import CustomersAutocomplete\nfrom Project.models import Project\nfrom Customers.models import Customer\nimport autocomplete_light\n\nclass ProjectForm(autocomplete_light.ModelForm): \n customer = forms.ModelChoiceField(Customer.objects.all(),\n widget=autocomplete_light.ChoiceWidget('CustomersAutocomplete')) \n def __init__(self, *args, **kwargs):\n super(ProjectForm, self).__init__(*args, **kwargs) \n self.fields['description'].widget.attrs = {'cols': 60, 'rows': 15}\n self.fields['project'].widget.attrs = {'size': 80}\n\n class Meta:\n model = Project \n exclude = ( 'invoice', 'first_created', \n 'last_changed', 'last_accessed',\n 'created_by', 'changed_by', 'company_id', 'change_counter',) ","sub_path":"Project/forms/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"163578388","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nget_ipython().system('jupyter nbconvert --to script Sonar.ipynb')\n\n\n# In[49]:\n\n\n# imports\n\nimport numpy as np\nimport random\nimport pickle\nimport os \n\n\n# In[50]:\n\n\n# activation function\n\ndef perceptron(z):\n return -1 if z<=0 else 1\n\n# loss functions\n\ndef ploss(yhat, y):\n return max(0, -yhat*y)\n\n\n# In[51]:\n\n\nclass Sonar_Model:\n \n \n def __init__(self, dimension=None, weights=None, bias=None, activation=(lambda x: x), predict=ppredict):\n \n self._dim = dimension\n self.w = weights or np.random.normal(size=self._dim)\n self.w = np.array(self.w)\n self.b = bias if bias is not None else np.random.normal()\n self._a = activation\n #self.predict = predict.__get__(self)\n \n def __str__(self):\n \n return \"Simple cell neuron\\n \\tInput dimension: %d\\n \\tBias: %f\\n \\tWeights: %s\\n \\tActivation: %s\" % (self._dim, self.b, self.w, self._a.__name__)\n \n #Sonar class should have a predict(v) method that uses internal weights to make prediction on new data \n \n def __call__(self, v):\n\n yhat = self._a(np.dot(self.w, np.array(v)) + self.b)\n return yhat\n \n def ppredict(self, x):\n return self(x)\n\n \n def load_model(self, file_path):\n '''\n open the pickle file and update the model's parameters\n '''\n \n file = pickle.load(open(file_path,'rb'))\n \n self._dim = file._dim\n self.w = file.w\n self.b = file.b\n self._a = file._a\n \n\n\n def save_model(self):\n '''\n save your model as 'sonar_model.pkl' in the local path\n '''\n saved = open('sonar_model.pkl','wb')\n cat_model = pickle.dump(self, saved)\n saved.close\n \n \n \n \n \n \n\n\n# In[52]:\n\n\nclass Sonar_Trainer:\n \n def __init__(self, dataset, model):\n \n self.dataset = dataset\n self.model = model\n self.loss = ploss\n\n def accuracy(self, data):\n '''\n return the accuracy on data given data iterator\n '''\n acc = 100*np.mean([1 if self.model.ppredict(x) == y else 0 for x, y in data])\n return acc\n \n \n \n #Sonar class should have a public method train, which trains the perceptron on loaded data\n def train(self, lr, ne):\n '''\n This method should:\n 1. display initial accuracy on the training data loaded in the constructor\n 2. update parameters of the model instance in a loop for ne epochs using lr learning rate\n 3. display final accuracy\n '''\n \n print(\"training model on data...\")\n accuracy = self.accuracy(self.dataset)\n print(\"initial accuracy: %.3f\" % (accuracy))\n \n for epoch in range(ne+1):\n self.dataset._shuffle()\n for d in self.dataset:\n x, y = d\n x = np.array(x)\n yhat = self.model(x)\n error = y - yhat\n self.model.w += lr*(y-yhat)*x \n self.model.b += lr*(y-yhat)\n accuracy = self.accuracy(self.dataset) \n print('>epoch=%d, learning_rate=%.3f, accuracy=%.3f' % (epoch+1, lr, accuracy))\n \n print(\"training complete\")\n \n #Train method returns a single float representing the mean squarre error on the trained set\n print(\"final accuracy: %.3f\" % (accuracy))\n\n\n# In[55]:\n\n\nclass Sonar_Data:\n\n\n#Sonar Class should have the datafile relative path (string) and name (string) as contrustor arguments\n \n def __init__(self, relative_path='C:/Users/gigi-/OneDrive/Documents/MA2/GitHub/ProjetAI/IntroAI/keio2019aia/data/assignment1', data_file_name='sonar_data.pkl'):\n '''\n initialize self.index; load and preprocess data; shuffle the iterator\n '''\n self.index = -1\n full_path = os.path.join(relative_path,data_file_name)\n self.raw = pickle.load(open(full_path,'rb'))\n self.simple = [(list(d), -1) for d in self.raw['r']]+[(list(d), 1) for d in self.raw['m']]\n \n def __iter__(self):\n '''\n See example code (ngram) in lecture slides\n '''\n return self\n\n def __next__(self):\n '''\n See example code (ngram) in slides\n '''\n self.index += 1\n \n if self.index == len(self.simple):\n self.index = -1\n raise StopIteration\n \n return self.simple[self.index][0], self.simple[self.index][1]\n\n def _shuffle(self):\n '''\n shuffle the data iterator\n '''\n return random.shuffle(self.simple)\n \n \n\n\n# In[94]:\n\n\ndef main():\n\n data = Sonar_Data()\n model = Sonar_Model(dimension=60, activation=perceptron) # specify the necessary arguments\n trainer = Sonar_Trainer(data, model)\n trainer.train(0.01,300) # experiment with learning rate and number of epochs\n model.save_model()\n\n\nif __name__ == '__main__':\n\n main()\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"assignment1/sonar.py","file_name":"sonar.py","file_ext":"py","file_size_in_byte":5049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"240132939","text":"#!/usr/bin/env python3\n\nfrom cgitb import enable\nenable()\nfrom cgi import FieldStorage, escape\nfrom http.cookies import SimpleCookie\nfrom os import environ\nimport os\nfrom PIL import Image\nimport base64\n\n\n#os.environ['http_proxy']=\"http://4c.ucc.ie:80\"\n#os.environ['https_proxy']=\"http://4c.ucc.ie:80\"\n\nresult = \"problem\"\n\ncookie = SimpleCookie()\nhttp_cookie_header = environ.get(\"HTTP_COOKIE\")\nif http_cookie_header:\n cookie.load(http_cookie_header)\n if 'token' in cookie:\n token = cookie['token'].value\n path = \"/var/www/html/tmp_fold/usr_\" + token + \"/profile.png\"\n form_data = FieldStorage()\n if len(form_data) != 0:\n image = escape(form_data.getfirst(\"image\", \"\").strip())\n image = image.split(',')\n image = image[1]\n image = str.encode(photo)\n with open( path , \"wb\") as fh:\n fh.write(base64.decodestring(image))\n im = Image.open(path)\n im.convert(\"RGB\").save(path)\n result = \"good\"\nprint(\"Content-Type: text/plain\")\nprint()\nprint(result)\n","sub_path":"GUI/cam.py","file_name":"cam.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"544924430","text":"p = [\n [17, -7, -11],\n [1, 4, -1],\n [6, -2, -6],\n [19, 11, 9],\n]\n\nv = [\n [0, 0, 0],\n [0, 0, 0],\n [0, 0, 0],\n [0, 0, 0],\n]\n\nfor i in range(1000):\n # gravity\n\n for ai, a in enumerate(p):\n for bi, b in enumerate(p):\n if ai == bi:\n continue\n for d in [0, 1, 2]:\n apos = a[d]\n bpos = b[d]\n if apos < bpos:\n v[ai][d] += 1\n v[bi][d] -= 1\n elif bpos > apos:\n v[ai][d] -= 1\n v[bi][d] += 1\n else:\n pass\n # momentum\n for ai, a in enumerate(p):\n for d in [0, 1, 2]:\n p[ai][d] += v[ai][d]\n\n # print(p)\n\nprint(p)\ns = 0\n\nfor ai, a in enumerate(p):\n vel = v[ai]\n pos = a\n\n s += sum([abs(_pos) for _pos in pos]) * sum([abs(_v) for _v in vel])\nprint(s)\n\n# 40\n# 11423\n","sub_path":"day12/day12.py","file_name":"day12.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"115673921","text":"# coding=utf8\n\n# Copyright 2018 JDCLOUD.COM\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# NOTE: This class is auto generated by the jdcloud code generator program.\n\n\nclass ClusterDetailInfo(object):\n\n def __init__(self, materNum=None, masterCore=None, masterMemory=None, masterDiskType=None, masterDiskVolume=None, masterInstanceType=None, masterInstanceInfo=None, slaveNum=None, slaveCore=None, slaveMemory=None, slaveDiskType=None, slaveDiskVolume=None, slaveInstanceType=None, slaveInstanceInfo=None):\n \"\"\"\n :param materNum: (Optional) Master节点数量\n :param masterCore: (Optional) Master节点CPU\n :param masterMemory: (Optional) Master节点内存(推荐至少8G内存,否则服务可能会部署失败)\n :param masterDiskType: (Optional) \"Master节点云盘类型,可传类型为(以下以“/”分割各类型)\"\n\"NBD/NBD_SATA\"\n\"分别代表:性能型/容量型\"\n\n :param masterDiskVolume: (Optional) Master节点云盘容量,必须是10的整数倍,且大于20小于3000\n :param masterInstanceType: (Optional) Master节点规格,比如:g.n1.xlarge,更多规格请参考[文档](https://www.jdcloud.com/help/detail/296/isCatalog/1)\n :param masterInstanceInfo: (Optional) master节点实例信息\n :param slaveNum: (Optional) Slave节点数量\n :param slaveCore: (Optional) Slave节点CPU\n :param slaveMemory: (Optional) Slave节点内存(推荐至少4G内存,否则服务可能会部署失败)\n :param slaveDiskType: (Optional) \"Slave节点云盘类型,可传类型为(以下以“/”分割各类型)\"\n\"NBD/NBD_SATA\"\n\"分别代表:性能型/容量型\"\n\n :param slaveDiskVolume: (Optional) Slave节点云盘容量,必须是10的整数倍,且大于20小于3000\n :param slaveInstanceType: (Optional) Slave节点规格,比如:g.n1.xlarge,更多规格请参考[文档](https://www.jdcloud.com/help/detail/296/isCatalog/1)\n :param slaveInstanceInfo: (Optional) Slave节点实例信息\n \"\"\"\n\n self.materNum = materNum\n self.masterCore = masterCore\n self.masterMemory = masterMemory\n self.masterDiskType = masterDiskType\n self.masterDiskVolume = masterDiskVolume\n self.masterInstanceType = masterInstanceType\n self.masterInstanceInfo = masterInstanceInfo\n self.slaveNum = slaveNum\n self.slaveCore = slaveCore\n self.slaveMemory = slaveMemory\n self.slaveDiskType = slaveDiskType\n self.slaveDiskVolume = slaveDiskVolume\n self.slaveInstanceType = slaveInstanceType\n self.slaveInstanceInfo = slaveInstanceInfo\n","sub_path":"python_code/vnev/Lib/site-packages/jdcloud_sdk/services/jmr/models/ClusterDetailInfo.py","file_name":"ClusterDetailInfo.py","file_ext":"py","file_size_in_byte":3170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"229513049","text":"#!/usr/global/paper/bin/python\nfrom __future__ import print_function\nimport ddr_compress.dbi as ddbi\nfrom sqlalchemy import func\nimport curses,time,os\nfrom paper.ganglia import dbi as pyg\n\n#setup my output file\nfile_log = []\nfile_status = {}\nfile_time = {}\nfile_pid = {}\nfile_start = {}\nfile_end = {}\n\n#setup my curses stuff following\n# https://docs.python.org/2/howto/curses.html\nstdscr = curses.initscr()\ncurses.noecho()\ncurses.cbreak()\nstdscr.keypad(1)\nstdscr.nodelay(1)\n\n#setup my db connection\ndbi = ddbi.DataBaseInterface()\npyg_dbi = pyg.DataBaseInterface()\n\nstdscr.addstr('PAPER Distiller Status Board')\nstdscr.addstr(1,0,'Press \"q\" to exit')\nstatheight = 50\nstatusscr = curses.newwin(statheight,200,5,0)\nstatusscr.keypad(1)\nstatusscr.nodelay(1)\ncurline = 2\ncolwidth = 50\nobslines = 20\ni=0\nstat = ['\\\\','|','/','-','.']\ntry:\n\ttable = getattr(ddbi, 'Observation')\n\twhile(1):\n\t\ttimestamp = int(time.time())\n\t\tlog_info = []\n\t\t#get the screen dimensions\n\n\t\t#load the currently executing files\n\t\ti += 1\n\t\tcurline = 2\n\t\tstdscr.addstr(0,30,stat[i%len(stat)])\n\t\ts = dbi.Session()\n\t\ttotalobs = s.query(table).count()\n\t\tstdscr.addstr(curline, 0, 'Number of observations currently in the database: {totalobs}'.format(totalobs=totalobs))\n\t\tcurline += 1\n\t\tOBSs = s.query(table).filter(getattr(table, 'status') != 'NEW').filter(getattr(table, 'status') != 'COMPLETE').all()\n\t\t#OBSs = s.query(table).all()\n\t\tobsnums = [OBS.obsnum for OBS in OBSs]\n\t\tstdscr.addstr(curline, 0, 'Number of observations currently being processed {num}'.format(num=len(obsnums)))\n\t\tcurline += 1\n\t\tstatusscr.erase()\n\t\tstatusscr.addstr(0, 0 ,' ---- Still Idle ---- ')\n\t\tfor j, obsnum in enumerate(obsnums):\n\t\t\ttry:\n\t\t\t\thost, path, filename= dbi.get_input_file(obsnum)\n\t\t\t\tstatus = dbi.get_obs_status(obsnum)\n\t\t\t\tstill_host = dbi.get_obs_still_host(obsnum)\n\t\t\t\tcurrent_pid = dbi.get_obs_pid(obsnum)\n\t\t\texcept:\n\t\t\t\thost, path, filename = 'host', '/path/to/', 'zen.2345672.23245.uv'\n\t\t\t\tstatus = 'WTF'\n\t\t\tcol = int(j/statusscr.getmaxyx()[0])\n\t\t\t#print(col*colwidth)\n\t\t\tif j == 0 or col == 0:\n\t\t\t\trow = j\n\t\t\telse:\n\t\t\t\trow = j % statheight\n\t\t\ttry:\n\t\t\t\tstatusscr.addstr(row, col * colwidth,\n\t\t\t\t\t'{filename} {status} {still_host}'.format(col=col, filename=os.path.basename(filename),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstatus=status, still_host=still_host))\n\t\t\texcept:\n\t\t\t\tcontinue\n\t\t\t#check for new filenames\n\t\t\tpath = os.path.dirname(filename)\n\t\t\tfile_name = os.path.basename(filename)\n\t\t\tfull_path = ':'.join(still_host, filename)\n\t\t\tif filename not in file_pid.keys():\n\t\t\t\tfile_pid.update({filename:current_pid})\n\t\t\t\ttime_start = int(time.time())\n\t\t\t\tfile_start.update({filename:time_start})\n\t\t\t\tfile_end.update({filename:-1})\n\t\t\tif file_pid[filename] not in [current_pid]:\n\t\t\t\ttime_end = int(time.time())\n\t\t\t\tfile_end.update({filename:time_end})\n\t\t\t\tdel_time = -1\n\t\t\t\tfull_stats = ''.join((full_path, status))\n\t\t\t\tentry_dict = {'host':still_host,\n\t\t\t\t\t\t\t'path':path,\n\t\t\t\t\t\t\t'filename':file_name,\n\t\t\t\t\t\t\t'full_path':full_path,\n\t\t\t\t\t\t\t'status':status,\n\t\t\t\t\t\t\t'full_stats':full_stats,\n\t\t\t\t\t\t\t'del_time':del_time,\n\t\t\t\t\t\t\t'time_start':file_start[filename],\n\t\t\t\t\t\t\t'time_end':file_end[filename],\n\t\t\t\t\t\t\t'timestamp':timestamp}\n\t\t\t\tfile_log.append(entry_dict)\n\t\t\t\tfile_pid.update({filename:current_pid})\n\t\t\t\ttime_start = int(time.time())\n\t\t\t\tfile_start.update({filename:time_start})\n\t\t\t\tfile_end.update({filename:-1})\n\t\t\tif filename not in file_status.keys():\n\t\t\t\tfile_status.update({filename:status})\n\t\t\t\tdel_time = 0\n\t\t\t\tfull_stats = ''.join((full_path, status))\n\t\t\t\tentry_dict = {'host':still_host,\n\t\t\t\t\t\t\t'path':path,\n\t\t\t\t\t\t\t'filename':file_name,\n\t\t\t\t\t\t\t'full_path':full_path,\n\t\t\t\t\t\t\t'status':status,\n\t\t\t\t\t\t\t'full_stats':full_stats,\n\t\t\t\t\t\t\t'del_time':del_time,\n\t\t\t\t\t\t\t'time_start':file_start[filename],\n\t\t\t\t\t\t\t'time_end':file_end[filename],\n\t\t\t\t\t\t\t'timestamp':timestamp}\n\t\t\t\tfile_log.append(entry_dict)\n\t\t\t\tfile_time.update({filename:time.time()})\n\t\t\t#write output log\n\t\t\tif file_status[filename] not in [status]:\n\t\t\t\tdel_time = time.time() - file_time[filename]\n\t\t\t\tfull_stats = ''.join((full_path, status))\n\t\t\t\tentry_dict = {'host':still_host,\n\t\t\t\t\t\t\t'path':path,\n\t\t\t\t\t\t\t'filename':file_name,\n\t\t\t\t\t\t\t'full_path':full_path,\n\t\t\t\t\t\t\t'status':status,\n\t\t\t\t\t\t\t'full_stats':full_stats,\n\t\t\t\t\t\t\t'del_time':del_time,\n\t\t\t\t\t\t\t'time_start':file_start[filename],\n\t\t\t\t\t\t\t'time_end':file_end[filename],\n\t\t\t\t\t\t\t'timestamp':timestamp}\n\t\t\t\tfile_log.append(entry_dict)\n\t\t\t\tfile_status.update({filename:status})\n\t\t\t\tfile_time.update({filename:time.time()})\n\t\twith pyg_dbi.session_scope as s:\n\t\t\tfor monitor_data in file_log:\n\t\t\t\tpyg_dbi.add_entry_dict(s, 'Monitor', monitor_data)\n\t\tfile_log = []\n\t\ts.close()\n\t\tstatusscr.refresh()\n\t\tc = stdscr.getch()\n\t\tif c == ord('q'):\n\t\t\tbreak\n\t\ttime.sleep(1)\nexcept(KeyboardInterrupt):\n\ts.close()\n\tpass\n#terminate\ncurses.nocbreak(); stdscr.keypad(0); curses.echo()\ncurses.endwin()\n","sub_path":"paper/ganglia/scripts/monitor_folio_still.py","file_name":"monitor_folio_still.py","file_ext":"py","file_size_in_byte":4848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"222776691","text":"#!/usr/bin/env python\nimport sys\nimport time\n\nsys.path.append('../libs')\n\nfrom common import *\nimport thrift_clients\nimport persistent_backends\n\ntask_manager_c = thrift_clients.TaskManagerClient(host='127.0.0.1', port=9090)\nregister_info_backend = persistent_backends.StickyRedis(port=6380, db=REGISTER_INFO_DB)\nhostfile = open('./host_list', 'r')\nlogfile = open('./host_updated.log', 'a+')\n\nupdate_cmd = \"uptime\"\n\nclient_need_updates = []\nfor host in hostfile.readlines():\n client_need_updates.append(host.strip('\\n'))\n\nwhile client_need_updates:\n client_ready_updates = []\n alived_hosts = register_info_backend.keys()\n\n for host in alived_hosts:\n if host in client_need_updates:\n client_ready_updates.append(host)\n client_need_updates.remove(host)\n\n if client_ready_updates:\n task_manager_c.perform_tasks(client_need_updates, cmd=update_cmd)\n logfile.write('\\n'.join(client_ready_updates))\n logfile.write('\\n')\n time.sleep(2)\n\n\n","sub_path":"server/scripts/client_update.py","file_name":"client_update.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"41131621","text":"import socket\nimport time\nimport threading\nfrom time import sleep\n#from mysql_connector import *\nfrom pprint import pprint\nfrom pprint import pformat\nfrom queue import Queue\nimport sys\nfrom threading import Thread, Lock\n\n\nopenPorts = []\nhostnameOpenPorts = {} #storing result for one hostname and list of open ports\nipHostnameOpenPorts = {} #storing result for one ip, its hostname and opened ports\nfinalResults = {} #storing all results\ntargetHosts = {'ec2-18-185-241-122.eu-central-1.compute.amazonaws.com': '35.158.160.236'}\nqueue = Queue()\n\nsocket.setdefaulttimeout(0.25)\nprint_lock = threading.Lock()\n\nprint(\"The scanner is started. Please wait for results\")\n\ndef portscan(port):\n for hostname, ip in targetHosts.items():\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n\n con = s.connect((ip, port))\n with print_lock:\n\n openPorts.append(port)\n hostnameOpenPorts = {\"hostname\": hostname,\n \"openports\": list(set(openPorts))}\n result = {ip: hostnameOpenPorts}\n finalResults.update(result)\n con.close()\n except:\n pass\n\n\ndef threader():\n while True:\n worker = queue.get()\n portscan(worker)\n queue.task_done()\n\n\nstartTime = time.time()\nfor x in range(100):\n t = threading.Thread(target=threader)\n t.daemon = True\n t.start()\n\nfor worker in range(1, 10000):\n queue.put(worker)\n\nqueue.join()\n\nprint('Time taken:', time.time() - startTime)\n\nprint(\"----------------------------------------------\")\npprint(finalResults)\nprint(len(finalResults))\n","sub_path":"ip_scanner.py","file_name":"ip_scanner.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"438813554","text":"from fabric.contrib.files import append, exists, sed, is_link\nfrom fabric.api import env, local, run, sudo, settings\nimport random\n\nREPO_URL = 'https://github.com/exquest/daysheets.git'\n\ndef _create_directory_structure_if_nessecary(site_folder):\n\tfor subfolder in ('database', 'static', 'virtualenv', 'source'):\n\t\trun('mkdir -p %s/%s' % (site_folder, subfolder))\n\t\t\ndef _get_latest_source(source_folder):\n\tif exists(source_folder + '/.git'):\n\t\trun('cd %s && git fetch' % source_folder)\n\telse:\n\t\trun('git clone %s %s' % (REPO_URL, source_folder))\n\tcurrent_commit = local(\"git log -n 1 --format=%H\", capture=True)\n\trun('cd %s && git reset --hard %s' % (source_folder, current_commit))\n\t\ndef _update_settings(source_folder, site_name):\n\tsettings_path = source_folder + '/settings/base.py'\n#\tsed(settings_path, \"DEBUG = True\", \"DEBUG = False\")\n#\tsed(settings_path,\n#\t\t'ALLOWED_HOSTS =.+$',\n#\t\t'ALLOWED_HOSTS = [\"%s\"]' % (site_name,)\n#\t)\n\tsecret_key_file = source_folder + '/settings/secret_key.py'\n\tif not exists(secret_key_file):\n\t\tchars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'\n\t\tkey = ''.join(random.SystemRandom().choice(chars) for _ in range(50))\n\t\tappend(secret_key_file, \"SECRET_KEY = '%s'\" % (key,))\n\tappend(settings_path, '\\nfrom .secret_key import SECRET_KEY')\n\t\ndef _update_wsgi(source_folder, settings):\n\twsgi_path = source_folder + '/daysheets/wsgi.py'\n\tsed(wsgi_path, \"daysheets.settings\", settings)\n\t\ndef _update_virtualenv(source_folder):\n\tvirtualenv_folder = source_folder + '/../virtualenv'\n\tif not exists(virtualenv_folder + '/bin/pip'):\n\t\trun('virtualenv --python=python3 %s' % (virtualenv_folder,))\n\trun('%s/bin/pip install -r %s/requirements.txt' % (\n\t\tvirtualenv_folder, source_folder\n\t))\n\t\ndef _update_static_files(source_folder, settings):\n\trun('cd %s && ../virtualenv/bin/python3 manage.py collectstatic --settings=%s --noinput' % (\n\t\tsource_folder, settings\n\t))\n\t\ndef _update_database(source_folder, settings):\n\trun('cd %s && ../virtualenv/bin/python3 manage.py migrate --settings=%s --noinput' % (\n\t\tsource_folder, settings\n\t))\n\t\ndef _create_nginx_files_and_links_if_nessecary(source_folder, deploy_tools_folder, site_name):\n\tnginx_path = '/etc/nginx'\n\tsites_available_path = nginx_path + '/sites-available/'\n\tsites_enabled_path = nginx_path + '/sites-enabled/'\n\tsites_enabled_link = sites_enabled_path + site_name\n\tnginx_conf_file = sites_available_path + site_name\n\tnginx_conf_template_file = deploy_tools_folder + 'nginx.template.conf'\n\t\n\tif not exists(nginx_conf_file, use_sudo=True, verbose=True):\n\t\tsudo('cp %s %s' % (nginx_conf_template_file, nginx_conf_file))\n\t\tsed(nginx_conf_file, \"SITENAME\", site_name, use_sudo=True, backup='')\n\tif not is_link(sites_enabled_link, verbose=True):\n\t\tsudo('ln -s %s %s' % (nginx_conf_file, sites_enabled_link))\n\t\ndef _create_guincorn_files_if_nessecary(site_name, deploy_tools_folder, gunicorn_init_location):\n\tgunicorn_template_file = deploy_tools_folder + 'gunicorn-upstart.template.conf'\n\tif not exists(gunicorn_init_location):\n\t\tsudo('cp %s %s' % (gunicorn_template_file, gunicorn_init_location))\n\t\tsed(gunicorn_init_location, \"SITENAME\", site_name, use_sudo=True, backup='')\n\ndef _restart_nginx_and_gunicorn(gunicorn_init):\n\tsudo('service nginx reload')\n\twith settings(warn_only=True):\n\t\tresult = sudo('restart %s' % (gunicorn_init))\n\tif result.failed:\n\t\tsudo('start %s' % (gunicorn_init))\n\ndef deploy():\n\tsite_folder = '/home/%s/sites/%s' % (env.user, env.host)\n\tsource_folder = site_folder + '/source'\n\tdeploy_tools_folder = source_folder + '/deploy_tools/'\n\tsettings = 'settings.production'\n\tgunicorn_init = 'gunicorn-%s' % (env.host)\n\tgunicorn_init_location = '/etc/init/' + gunicorn_init + '.conf'\n\t_create_directory_structure_if_nessecary(site_folder)\n\t_get_latest_source(source_folder)\n\t_update_settings(source_folder, env.host)\n\t_update_wsgi(source_folder, settings)\n\t_update_virtualenv(source_folder)\n\t_update_static_files(source_folder, settings)\n\t_update_database(source_folder, settings)\n\t_create_nginx_files_and_links_if_nessecary(source_folder, deploy_tools_folder, env.host)\n\t_create_guincorn_files_if_nessecary(env.host, deploy_tools_folder, gunicorn_init_location)\n\t_restart_nginx_and_gunicorn(gunicorn_init)\n\t\n","sub_path":"deploy_tools/fabfile.py","file_name":"fabfile.py","file_ext":"py","file_size_in_byte":4213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"305065779","text":"#1\ndef anagram_number():\n num = str(input(\"Nhập số nguyên: \")) \n reverse_num = num[::-1]\n if int(num) == int(reverse_num):\n print('True')\n else:\n print('False')\n pass\n# anagram_number()\n\n#2\ndef roman_to_int():\n roman = input(\"Nhập chữ số la mã cần chuyển đổi: \")\n roman_dict = {'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(roman):\n if i + 1 < len(roman) and roman[i:i+2] in roman_dict:\n num += roman_dict[roman[i:i+2]]\n i += 2\n else:\n num += roman_dict[roman[i]]\n i += 1\n print(\"Số la mã \",roman,\" có giá trị bằng \",num)\n# roman_to_int()","sub_path":"hackathon1_midterm/medium.py","file_name":"medium.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"499106528","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n===Description===\nModule for tests\n\nRecommended to run with nosetests as:\nnosetests --exe --with-coverage --cover-erase --cover-html\n\"\"\"\n\nimport unittest\nimport logging\nimport os\nimport json\nimport sqlite3\nfrom PyQt4.QtTest import QTest\nfrom PyQt4 import QtGui, QtCore\nfrom gui_export import MainWindow, ExportDialog, StatisticsDialog,\\\n AboutDialog, NotificationDialog, ExceptionDialog,\\\n Results\nfrom handler import Kindle\nfrom service import Lingualeo\n\nTEST_DB = 'test.db'\nTEST_TXT = 'test.txt'\n\n\ndef leftMouseClick(widget):\n QTest.mouseClick(widget, QtCore.Qt.LeftButton)\n\n\ndef createTxtFile():\n with open(TEST_TXT, 'w') as f:\n f.write('bacon')\n f.write('simple')\n\n\ndef createSqlBase(malformed=False, empty=False, valid=True):\n \"\"\"\n create test SQL base with name test.db\n \"\"\"\n conn = sqlite3.connect('test.db')\n if valid:\n conn.execute(\"\"\"\n CREATE TABLE WORDS\n (id TEXT PRIMARY KEY NOT NULL,\n word TEXT, stem TEXT, lang TEXT,\n category INTEGER DEFAULT 0,\n timestamp INTEGER DEFAULT 0,\n profileid TEXT);\n \"\"\")\n if valid and not empty:\n conn.execute(\"\"\"\n INSERT INTO \"WORDS\"\n VALUES('en:intending',\n 'intending',\n 'intend',\n 'en',\n 0,\n 1450067334997,\n '')\n \"\"\")\n conn.commit()\n if malformed:\n with open(TEST_DB, 'wb') as f:\n f.write(b'tt')\n\n\ndef createLingualeoUser(premium=False):\n \"\"\"return test Lingualeo user\"\"\"\n return {\"premium_type\": +premium,\n \"fullname\": \"Bob Gubko\",\n \"meatballs\": 1500,\n \"avatar_mini\": 'https://d144fqpiyasmrr'\n '.cloudfront.net/uploads'\n '/avatar/0s100.png',\n \"xp_level\": 34}\n\n\nclass BaseTest(unittest.TestCase):\n \"\"\"\n Base class for tests\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Construct QApplication\n \"\"\"\n self.app = QtGui.QApplication([])\n\n def tearDown(self):\n \"\"\"\n Prevent gtk-Critical messages.\n Remove app\n \"\"\"\n self.app.quit()\n self.app.processEvents()\n self.app.sendPostedEvents(self.app, 0)\n self.app.flush()\n self.app.deleteLater()\n\n\nclass TestMainWindow(BaseTest):\n \"\"\"\n Class for testing MainWindow\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Turn off logger\n Set english language\n Set credentials from json file\n \"\"\"\n super(TestMainWindow, self).setUp()\n logging.disable(logging.CRITICAL)\n self.ui = MainWindow()\n self.ui.language = 'en'\n self.ui.loadTranslation()\n self.ui.email_edit.setText('b346059@trbvn.com')\n self.ui.pass_edit.setText('1234567890')\n\n def tearDown(self):\n \"\"\"\n Prevent gtk-Critical messages\n Remove test.db in case if it's present\n \"\"\"\n super(TestMainWindow, self).tearDown()\n if os.path.exists(TEST_DB):\n os.remove(TEST_DB)\n if os.path.exists(TEST_TXT):\n os.remove(TEST_TXT)\n\n def test_only_input_checked(self):\n \"\"\"\n Initial state of GUI: Only input_radio is checked\n \"\"\"\n self.assertEqual(self.ui.input_radio.isChecked(), True)\n self.assertEqual(self.ui.text_radio.isChecked(), False)\n self.assertEqual(self.ui.kindle_radio.isChecked(), False)\n\n def test_kindle_radios_disabled(self):\n \"\"\"\n All_words and new_words should be disabled\n \"\"\"\n self.assertEqual(self.ui.all_words_radio.isEnabled(), False)\n self.assertEqual(self.ui.new_words_radio.isEnabled(), False)\n\n def test_kindle_radio_only_one_checked(self):\n \"\"\"\n Checking new_words should uncheck all_words\n \"\"\"\n self.ui.kindle_radio.setChecked(True)\n self.ui.new_words_radio.setChecked(True)\n self.assertEqual(self.ui.all_words_radio.isChecked(), False)\n\n def test_input_validator(self):\n \"\"\"\n No non-Unicode is allowed in input\n \"\"\"\n\n validator = self.ui.input_word_edit.validator()\n text = \"work раве\"\n state, word, pos = validator.validate(text, 0)\n self.assertEqual(state == QtGui.QValidator.Acceptable, False)\n\n def test_empty_login_pass(self):\n \"\"\"\n No email/password is specified - show an error in statusbar.\n \"\"\"\n self.ui.email_edit.setText(\"\")\n self.ui.pass_edit.setText(\"\")\n self.ui.input_word_edit.setText(\"test\")\n leftMouseClick(self.ui.export_button)\n self.assertEqual(self.ui.status_bar.currentMessage(),\n \"Email or password are incorrect\")\n\n def test_dialog_not_run(self):\n \"\"\"\n Nothing is selected - ExportDialog shouldn't be constructed.\n \"\"\"\n self.ui.email_edit.setText(\"\")\n self.ui.pass_edit.setText(\"\")\n leftMouseClick(self.ui.export_button)\n with self.assertRaises(AttributeError):\n self.ui.dialog\n\n def test_input_not_run(self):\n \"\"\"\n No word in input - show an error in statusbar.\n \"\"\"\n leftMouseClick(self.ui.export_button)\n self.assertEqual(self.ui.status_bar.currentMessage(),\n \"No input\")\n\n def test_text_no_file_not_run(self):\n \"\"\"\n If no text file is selected - show an error in statusbar.\n \"\"\"\n self.ui.text_radio.setChecked(True)\n leftMouseClick(self.ui.export_button)\n self.assertEqual(self.ui.status_bar.currentMessage(),\n \"No txt file\")\n\n def test_kindle_no_base_not_run(self):\n \"\"\"\n No Kindle database is selected - show an error in statusbar.\n \"\"\"\n self.ui.kindle_radio.setChecked(True)\n leftMouseClick(self.ui.export_button)\n self.assertEqual(self.ui.status_bar.currentMessage(),\n \"No Kindle database\")\n\n def test_kindle_wrong_format_not_run(self):\n \"\"\"\n No '.db' in file extension for Kindle - show an error in statusbar.\n \"\"\"\n self.ui.kindle_radio.setChecked(True)\n self.ui.kindle_path.setText(TEST_TXT)\n leftMouseClick(self.ui.export_button)\n self.assertEqual(self.ui.status_bar.currentMessage(),\n \"Not database\")\n\n def test_kindle_not_valid_base_not_run(self):\n \"\"\"\n No WORDS in Kindle table - show an error in statusbar.\n \"\"\"\n createSqlBase(valid=False)\n self.ui.kindle_radio.setChecked(True)\n self.ui.kindle_path.setText(TEST_DB)\n leftMouseClick(self.ui.export_button)\n self.assertEqual(self.ui.status_bar.currentMessage(),\n \"Not valid database\")\n\n def test_kindle_empty_base_not_run(self):\n \"\"\"\n Table WORDS in Kindle database is empty - show an error in statusbar\n \"\"\"\n createSqlBase(empty=True)\n self.ui.kindle_radio.setChecked(True)\n self.ui.kindle_path.setText(TEST_DB)\n leftMouseClick(self.ui.export_button)\n self.assertEqual(self.ui.status_bar.currentMessage(),\n \"Kindle database is empty\")\n\n def test_kindle_malformed_not_run(self):\n \"\"\"\n Kindle database malformed - show 'Repair' and error in statusbar.\n \"\"\"\n createSqlBase(malformed=True)\n self.ui.kindle_radio.setChecked(True)\n self.ui.kindle_path.setText(TEST_DB)\n leftMouseClick(self.ui.export_button)\n self.assertEqual(self.ui.repair_button.isHidden(), False)\n self.assertEqual(self.ui.status_bar.currentMessage(),\n \"Database is malformed. Click 'Repair'\")\n\n def test_run_export(self):\n \"\"\"\n Email/password set, set word in 'Input' - ExportDialog appears\n \"\"\"\n\n\n def test_russian_translation(self):\n \"\"\"\n Selecting RU from Language menu - russian translation is loaded\n \"\"\"\n lang_item = self.ui.language_menu.actions()[1]\n lang_item.trigger()\n self.assertEqual(self.ui.export_button.text(), \"Экспорт\")\n\n\nclass TestExportDialog(BaseTest):\n \"\"\"\n Class for testing ExportDialog\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Set up initial condition:\n -special lingualeo user\n \"\"\"\n super(TestExportDialog, self).setUp()\n self.lingualeo = Lingualeo(\"aaa@mail.com\", \"12345\")\n\n def tearDown(self):\n \"\"\"\n Prevent gtk-Critical messages.\n Remove test.db and test.txt in case if they're present.\n \"\"\"\n super(TestExportDialog, self).tearDown()\n if os.path.exists(TEST_DB):\n os.remove(TEST_DB)\n if os.path.exists(TEST_TXT):\n os.remove(TEST_TXT)\n\n def test_export_kindle_premium(self):\n \"\"\"\n Test for unlimited sign if user is premium\n \"\"\"\n createSqlBase()\n handler = Kindle(TEST_DB)\n array = handler.get()\n duplicates = 0\n total = len(array)\n self.lingualeo.auth_info = createLingualeoUser(premium=True)\n self.lingualeo.initUser()\n dialog = ExportDialog(array, total, duplicates, self.lingualeo)\n self.assertEqual(\"∞\", dialog.meatballs_value_label.text())\n\n\nclass TestStatisticsDialog(BaseTest, Results):\n \"\"\"\n Class for testing StatisticsDialog\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Set up initial condition:\n -prepared list of dictionaries with results\n \"\"\"\n self.array = []\n row = {}\n words = [\"cat\", \"dog\", \"cockatoo\", \"smile\"]\n contexts = [\"I have a cat.\",\n \"I have a dog.\",\n \"\",\n \"Let's smile.\"\n ]\n translations = [\"кот\", \"cобака\", \"какаду\", \"улыбка\"]\n results = sorted(self.RESULTS.values())\n for index, (word, tword, context)\\\n in enumerate(zip(words, translations, contexts)):\n row = {\n \"word\": word,\n \"result\": results[index],\n \"tword\": tword,\n \"context\": context\n }\n self.array.append(row)\n super(TestStatisticsDialog, self).setUp()\n self.stat_dialog = StatisticsDialog(self.array)\n\n def test_correct_counts(self):\n \"\"\"\n Every label has its own count of words\n Total = 4\n Not added = 1\n Added = 1\n No translation = 1\n Exist = 1\n \"\"\"\n self.assertEqual('4', self.stat_dialog.values[0].text())\n self.assertEqual('1', self.stat_dialog.values[1].text())\n self.assertEqual('1', self.stat_dialog.values[2].text())\n self.assertEqual('1', self.stat_dialog.values[3].text())\n self.assertEqual('1', self.stat_dialog.values[4].text())\n\n def test_correct_table_colors(self):\n \"\"\"\n Every row in table has its own color\n 1) added - green.\n 2) exists - red.\n 3) no translation - yellow.\n 4) not added - white.\n \"\"\"\n self.assertEqual(self.stat_dialog.table.item(0, 0).backgroundColor(),\n QtCore.Qt.green)\n self.assertEqual(self.stat_dialog.table.item(1, 0).backgroundColor(),\n QtCore.Qt.red)\n self.assertEqual(self.stat_dialog.table.item(2, 0).backgroundColor(),\n QtCore.Qt.yellow)\n self.assertEqual(self.stat_dialog.table.item(3, 0).backgroundColor(),\n QtCore.Qt.white)\n\n def test_correct_table_row_counts(self):\n \"\"\"\n Table has four rows\n \"\"\"\n self.assertEqual(self.stat_dialog.table.rowCount(), 4)\n\n\nclass TestAboutDialog(BaseTest):\n \"\"\"\n Class for testing 'About' dialog.\n \"\"\"\n JSON_FILE = os.path.join(\"src\", \"data\", \"data.json\")\n\n def setUp(self):\n \"\"\"\n Set up initial condition:\n -prepared json file\n -version, author, idea, email loaded\n \"\"\"\n super(TestAboutDialog, self).setUp()\n with open(self.JSON_FILE) as f:\n data_info = json.loads(f.read())\n self.version = data_info['version']\n self.author = data_info['author']\n self.idea = data_info['idea']\n self.email = data_info['e-mail']\n self.about = AboutDialog()\n\n def tearDown(self):\n\n super(TestAboutDialog, self).tearDown()\n\n def test_version_present(self):\n \"\"\"\n Data in json == data in 'About'\n \"\"\"\n text = self.about.about_label.text()\n version_text = self.about.version_label.text()\n email_text = self.about.email_label.text()\n self.assertIn(self.author, text)\n self.assertIn(self.idea, text)\n self.assertIn(self.email, email_text)\n self.assertIn(self.version, version_text)\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_gui.py","file_name":"test_gui.py","file_ext":"py","file_size_in_byte":13105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"239828066","text":"from typing import List\nfrom collections import OrderedDict\n\nfrom ray.experimental.dag import (\n DAGNode,\n ClassNode,\n ClassMethodNode,\n PARENT_CLASS_NODE_KEY,\n)\nfrom ray.experimental.dag.function_node import FunctionNode\nfrom ray.experimental.dag.input_node import InputNode\nfrom ray.experimental.dag.utils import DAGNodeNameGenerator\nfrom ray.serve.deployment import Deployment\nfrom ray.serve.pipeline.deployment_method_node import DeploymentMethodNode\nfrom ray.serve.pipeline.deployment_node import DeploymentNode\nfrom ray.serve.pipeline.deployment_function_node import DeploymentFunctionNode\n\n\ndef transform_ray_dag_to_serve_dag(\n dag_node: DAGNode, node_name_generator: DAGNodeNameGenerator\n):\n \"\"\"\n Transform a Ray DAG to a Serve DAG. Map ClassNode to DeploymentNode with\n ray decorated body passed in, and ClassMethodNode to DeploymentMethodNode.\n \"\"\"\n if isinstance(dag_node, ClassNode):\n deployment_name = node_name_generator.get_node_name(dag_node)\n return DeploymentNode(\n dag_node._body,\n deployment_name,\n dag_node.get_args(),\n dag_node.get_kwargs(),\n dag_node.get_options(),\n # TODO: (jiaodong) Support .options(metadata=xxx) for deployment\n other_args_to_resolve=dag_node.get_other_args_to_resolve(),\n )\n\n elif isinstance(dag_node, ClassMethodNode):\n other_args_to_resolve = dag_node.get_other_args_to_resolve()\n # TODO: (jiaodong) Need to capture DAGNodes in the parent node\n parent_deployment_node = other_args_to_resolve[PARENT_CLASS_NODE_KEY]\n\n return DeploymentMethodNode(\n parent_deployment_node._deployment,\n dag_node._method_name,\n dag_node.get_args(),\n dag_node.get_kwargs(),\n dag_node.get_options(),\n other_args_to_resolve=dag_node.get_other_args_to_resolve(),\n )\n elif isinstance(\n dag_node,\n FunctionNode\n # TODO (jiaodong): We do not convert ray function to deployment function\n # yet, revisit this later\n ) and dag_node.get_other_args_to_resolve().get(\"is_from_serve_deployment\"):\n deployment_name = node_name_generator.get_node_name(dag_node)\n return DeploymentFunctionNode(\n dag_node._body,\n deployment_name,\n dag_node.get_args(),\n dag_node.get_kwargs(),\n dag_node.get_options(),\n other_args_to_resolve=dag_node.get_other_args_to_resolve(),\n )\n else:\n # TODO: (jiaodong) Support FunctionNode or leave it as ray task\n return dag_node\n\n\ndef extract_deployments_from_serve_dag(\n serve_dag_root: DAGNode,\n) -> List[Deployment]:\n \"\"\"Extract deployment python objects from a transformed serve DAG. Should\n only be called after `transform_ray_dag_to_serve_dag`, otherwise nothing\n to return.\n\n Args:\n serve_dag_root (DAGNode): Transformed serve dag root node.\n Returns:\n deployments (List[Deployment]): List of deployment python objects\n fetched from serve dag.\n \"\"\"\n deployments = OrderedDict()\n\n def extractor(dag_node):\n if isinstance(dag_node, (DeploymentNode, DeploymentFunctionNode)):\n deployment = dag_node._deployment\n # In case same deployment is used in multiple DAGNodes\n deployments[deployment.name] = deployment\n return dag_node\n\n serve_dag_root.apply_recursive(extractor)\n\n return list(deployments.values())\n\n\ndef get_pipeline_input_node(serve_dag_root_node: DAGNode):\n \"\"\"Return the InputNode singleton node from serve dag, and throw\n exceptions if we didn't find any, or found more than one.\n\n Args:\n ray_dag_root_node: DAGNode acting as root of a Ray authored DAG. It\n should be executable via `ray_dag_root_node.execute(user_input)`\n and should have `InputNode` in it.\n Returns\n pipeline_input_node: Singleton input node for the serve pipeline.\n \"\"\"\n\n input_nodes = []\n\n def extractor(dag_node):\n if isinstance(dag_node, InputNode):\n input_nodes.append(dag_node)\n\n serve_dag_root_node.apply_recursive(extractor)\n assert len(input_nodes) == 1, (\n \"There should be one and only one InputNode in the DAG. \"\n f\"Found {len(input_nodes)} InputNode(s) instead.\"\n )\n\n return input_nodes[0]\n\n\ndef process_ingress_deployment_in_serve_dag(\n deployments: List[Deployment],\n) -> List[Deployment]:\n \"\"\"Mark the last fetched deployment in a serve dag as exposed with default\n prefix.\n \"\"\"\n if len(deployments) == 0:\n return deployments\n\n # Last element of the list is the root deployment if it's applicable type\n # that wraps an deployment, given Ray DAG traversal is done bottom-up.\n ingress_deployment = deployments[-1]\n if ingress_deployment.route_prefix in [None, f\"/{ingress_deployment.name}\"]:\n # Override default prefix to \"/\" on the ingress deployment, if user\n # didn't provide anything in particular.\n new_ingress_deployment = ingress_deployment.options(route_prefix=\"/\")\n deployments[-1] = new_ingress_deployment\n\n # Erase all non ingress deployment route prefix\n for i, deployment in enumerate(deployments[:-1]):\n if (\n deployment.route_prefix is not None\n and deployment.route_prefix != f\"/{deployment.name}\"\n ):\n raise ValueError(\n \"Route prefix is only configurable on the ingress deployment. \"\n \"Please do not set non-default route prefix: \"\n f\"{deployment.route_prefix} on non-ingress deployment of the \"\n \"serve DAG. \"\n )\n else:\n # Earse all default prefix to None for non-ingress deployments to\n # disable HTTP\n deployments[i] = deployment.options(route_prefix=None)\n\n return deployments\n","sub_path":"python/ray/serve/pipeline/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":5939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"359257010","text":"\"\"\"Tests for SignalViewer node\"\"\"\nimport pytest\nfrom cognigraph.nodes.outputs import SignalViewer\nfrom cognigraph.nodes.sources import FileSource\n\nfrom cognigraph.nodes.tests.prepare_tests_data import info, data_path # noqa\nimport numpy as np\n\n\n@pytest.fixture # noqa\ndef signal_viewer(info, data_path): # noqa\n signal_viewer = SignalViewer()\n signal_viewer.mne_info = info\n N_SEN = len(info['ch_names'])\n signal_viewer.input = np.random.rand(N_SEN)\n parent = FileSource(data_path)\n parent.output = np.random.rand(info['nchan'], 1)\n parent.mne_info = info\n signal_viewer.parent = parent\n return signal_viewer\n\n\ndef test_change_api_attributes(signal_viewer):\n \"\"\"Check that appropriate method is defined\"\"\"\n signal_viewer._on_critical_attr_change(None, None, None)\n\n\n# Doesn't work in headless mode\n# commenting out signal_viewer.initialize() doesn't help either\n# def test_input_hist_invalidation_resets_statistics(signal_viewer):\n# \"\"\"Check that upstream history change doesn't break the node\"\"\"\n# signal_viewer.parent.initialize()\n# signal_viewer.initialize()\n# signal_viewer.parent.source_name = 'new_name' # triggers reset for source\n","sub_path":"cognigraph/nodes/tests/test_SignalViewer.py","file_name":"test_SignalViewer.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"61586667","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# -----------------\n# Реализуйте функцию best_hand, которая принимает на вход\n# покерную \"руку\" (hand) из 7ми карт и возвращает лучшую\n# (относительно значения, возвращаемого hand_rank)\n# \"руку\" из 5ти карт. У каждой карты есть масть(suit) и\n# ранг(rank)\n# Масти: трефы(clubs, C), пики(spades, S), червы(hearts, H), бубны(diamonds, D)\n# Ранги: 2, 3, 4, 5, 6, 7, 8, 9, 10 (ten, T), валет (jack, J), дама (queen, Q), король (king, K), туз (ace, A)\n# Например: AS - туз пик (ace of spades), TH - дестяка черв (ten of hearts), 3C - тройка треф (three of clubs)\n\n# Задание со *\n# Реализуйте функцию best_wild_hand, которая принимает на вход\n# покерную \"руку\" (hand) из 7ми карт и возвращает лучшую\n# (относительно значения, возвращаемого hand_rank)\n# \"руку\" из 5ти карт. Кроме прочего в данном варианте \"рука\"\n# может включать джокера. Джокеры могут заменить карту любой\n# масти и ранга того же цвета, в колоде два джокерва.\n# Черный джокер '?B' может быть использован в качестве треф\n# или пик любого ранга, красный джокер '?R' - в качестве черв и бубен\n# любого ранга.\n\n# Одна функция уже реализована, сигнатуры и описания других даны.\n# Вам наверняка пригодится itertools\n# Можно свободно определять свои функции и т.п.\n# -----------------\nfrom itertools import combinations, product\n\n\ndef hand_rank(hand):\n \"\"\"Возвращает значение определяющее ранг 'руки'\"\"\"\n ranks = card_ranks(hand)\n if straight(ranks) and flush(hand):\n return 8, max(ranks)\n elif kind(4, ranks):\n return 7, kind(4, ranks), kind(1, ranks)\n elif kind(3, ranks) and kind(2, ranks):\n return 6, kind(3, ranks), kind(2, ranks)\n elif flush(hand):\n return 5, ranks\n elif straight(ranks):\n return 4, max(ranks)\n elif kind(3, ranks):\n return 3, kind(3, ranks), ranks\n elif two_pair(ranks):\n return 2, two_pair(ranks), ranks\n elif kind(2, ranks):\n return 1, kind(2, ranks), ranks\n else:\n return 0, ranks\n\n\ndef card_ranks(hand):\n \"\"\"Возвращает список рангов (его числовой эквивалент),\n отсортированный от большего к меньшему\"\"\"\n ranks = ['0123456789TJQKA'.index(r) for r, s in hand]\n ranks.sort(reverse=True)\n if ranks == [14, 5, 4, 3, 2]:\n ranks = [5, 4, 3, 2, 1]\n return ranks\n\n\ndef flush(hand):\n \"\"\"Возвращает True, если все карты одной масти\"\"\"\n suits = set(s for r, s in hand)\n return len(suits) == 1\n\n\ndef straight(ranks):\n \"\"\"Возвращает True, если отсортированные ранги формируют последовательность 5ти,\n где у 5ти карт ранги идут по порядку (стрит)\"\"\"\n return (max(ranks)-min(ranks) == 4) and len(set(ranks)) == 5\n\n\ndef kind(n, ranks):\n \"\"\"Возвращает первый ранг, который n раз встречается в данной руке.\n Возвращает None, если ничего не найдено\"\"\"\n for r in ranks:\n if ranks.count(r) == n:\n return r\n return None\n\n\ndef two_pair(ranks):\n \"\"\"Если есть две пары, то возврщает два соответствующих ранга,\n иначе возвращает None\"\"\"\n pair = kind(2, ranks)\n pair_2 = kind(2, ranks[::-1])\n if pair and pair_2 != pair:\n return pair, pair_2\n else:\n return None\n\n\ndef best_hand(hand):\n \"\"\"Из \"руки\" в 7 карт возвращает лучшую \"руку\" в 5 карт \"\"\"\n return max(combinations(hand, 5), key=hand_rank)\n\n\ndef with_jokers(card, hand):\n \"\"\"Возвращаем просто карту, если не джокер,\n иначе возврщаем все возможные варианты для замены джокера\"\"\"\n if not card.startswith('?'):\n return [card]\n suits = 'SC' if card[1] == 'B' else 'HD'\n # из получаемого набора для джокера нужно удалить карты, которые уже есть в руке\n return set(r+s for r in '23456789TJQKA' for s in suits) - set(hand)\n\n\ndef best_wild_hand(hand):\n \"\"\"best_hand но с джокерами\"\"\"\n var_hands = (with_jokers(c, hand) for c in hand)\n hands = product(*var_hands)\n best = set(best_hand(h) for h in hands)\n return max(best, key=hand_rank)\n\n\ndef test_best_hand():\n print(\"test_best_hand...\")\n assert (sorted(best_hand(\"6C 7C 8C 9C TC 5C JS\".split()))\n == ['6C', '7C', '8C', '9C', 'TC'])\n assert (sorted(best_hand(\"TD TC TH 7C 7D 8C 8S\".split()))\n == ['8C', '8S', 'TC', 'TD', 'TH'])\n assert (sorted(best_hand(\"JD TC TH 7C 7D 7S 7H\".split()))\n == ['7C', '7D', '7H', '7S', 'JD'])\n print('OK')\n\n\ndef test_best_wild_hand():\n print(\"test_best_wild_hand...\")\n assert (sorted(best_wild_hand(\"6C 7C 8C 9C TC 5C ?B\".split()))\n == ['7C', '8C', '9C', 'JC', 'TC'])\n assert (sorted(best_wild_hand(\"TD TC 5H 5C 7C ?R ?B\".split()))\n == ['7C', 'TC', 'TD', 'TH', 'TS'])\n assert (sorted(best_wild_hand(\"JD TC TH 7C 7D 7S 7H\".split()))\n == ['7C', '7D', '7H', '7S', 'JD'])\n print('OK')\n\nif __name__ == '__main__':\n test_best_hand()\n test_best_wild_hand()\n","sub_path":"homework1/poker.py","file_name":"poker.py","file_ext":"py","file_size_in_byte":6109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"160487214","text":"from typing import Optional\nfrom json import loads\n\nfrom numpy import array\nfrom numpy import uint64\nfrom fastapi import FastAPI\nfrom fastapi import Request\n\nfrom ..utils import get_cg\n\napi = FastAPI()\n\n\n@api.get(\"/table/{graph_id}/manifest/{node_id}:0\")\nasync def manifest(\n request: Request,\n graph_id: str,\n node_id: int,\n verify: Optional[bool] = True,\n return_seg_ids: Optional[bool] = False,\n prepend_seg_ids: Optional[bool] = False,\n bounds: Optional[str] = \"\",\n):\n from json.decoder import JSONDecodeError\n from .utils import manifest_response\n\n try:\n data = loads(await request.body())\n except JSONDecodeError:\n data = {}\n bbox = None\n if bounds:\n bbox = array([b.split(\"-\") for b in bounds.split(\"_\")], dtype=int).T\n\n cg = get_cg(graph_id)\n start_layer = cg.meta.custom_data.get(\"mesh\", {}).get(\"max_layer\", 2)\n if \"start_layer\" in data:\n start_layer = int(data[\"start_layer\"])\n\n flexible_start_layer = None\n if \"flexible_start_layer\" in data:\n flexible_start_layer = int(data[\"flexible_start_layer\"])\n\n args = (\n node_id,\n verify,\n return_seg_ids,\n prepend_seg_ids,\n start_layer,\n flexible_start_layer,\n bbox,\n data,\n )\n return manifest_response(cg, args)\n\n\n@api.post(\"/table/{graph_id}/remesh\")\nasync def remesh(request: Request, graph_id: str):\n from .utils import remesh\n\n data = loads(await request.body())\n return remesh(\n get_cg(graph_id), data[\"operation_id\"], array(data[\"l2ids\"], dtype=uint64)\n )\n","sub_path":"app/meshing/v1.py","file_name":"v1.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"318759","text":"# -*- coding: cp1254 -*-\r\nimport random\r\ndef getModeMedian():\r\n list_1=[]\r\n n=random.randint(3, 10)#dizi uzunluðu\r\n r_min=-4#dizinin içinde yer alabilecek en küçük deðer\r\n r_max=4#dizinin içinde yer alabilecek en büyük deðer\r\n \r\n #Diziye rastgele deðer atanmasý\r\n #karmaþýklýk O(n)\r\n for i in range(n):\r\n list_1.append(random.randint(r_min,r_max))\r\n print (\"liste\", list_1)\r\n \r\n \r\n #Dizinin histogram deðerinin hesaplanmasý\r\n #Karmaþýklýk O(n*n)\r\n histogram_list=[]\r\n for i in range(len(list_1)):\r\n s=False\r\n for j in range(len(histogram_list)):\r\n if (list_1[i]==histogram_list[j][0]):\r\n histogram_list[j][1]=histogram_list[j][1]+1\r\n s=True\r\n if(s==False):\r\n histogram_list.append([list_1[i],1])\r\n \r\n print(\"histogram_list\", histogram_list)\r\n \r\n #Dizinin mod hesabýnýn yapýlmasý\r\n #Karmaþýklýk O(n)\r\n frekans_max = -1\r\n mod = -1\r\n for item, frekans in histogram_list:\r\n print(\"item\", item, \"frekans\", frekans)\r\n if(frekans > frekans_max):\r\n frekans_max = frekans\r\n mod = item\r\n print(\"mod\", mod, \"max_f\", frekans_max)\r\n\r\n #Dizinin buble sort ile sýralanmasý\r\n #Karmaþýklýk O(n*n)\r\n m = len(list_1)\r\n for i in range(m-1, -1, -1):\r\n for j in range(0, i):\r\n if not(list_1[j] < list_1[j+1]):\r\n temp = list_1[j]\r\n list_1[j] = list_1[j+1]\r\n list_1[j+1] = temp\r\n print(list_1)\r\n \r\n \r\n #Dizinin median hesabýnýn yapýlmasý\r\n #Yukarýda sýralanan diziyi kullanacaðýmýz için karmaþýklýkk O(n)\r\n \r\n if(m % 2 == 1):\r\n ortanca = int(m/2) \r\n median = list_1[ortanca]\r\n print(\"Median = \", median)\r\n else:\r\n ort_1 = list_1[int(m/2)]\r\n ort_2 = list_1[int(m/2) - 1]\r\n median = (ort_1 + ort_2) / 2\r\n print(\"Median = \", median)\r\n \r\n return mod, median \r\n","sub_path":"getModeMedian.py","file_name":"getModeMedian.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"169650409","text":"#! /usr/bin/python2\n#\n# Copyright (c) 2020 Intel Corporation\n#\n# SPDX-License-Identifier: Apache-2.0\n\"\"\"\n\"\"\"\n\nimport errno\nimport logging\nimport os\nimport time\nimport werkzeug\n\ntry:\n import functools32\nexcept ImportError as e:\n try:\n import backports.functools_lru_cache as functools32\n except ImportError as e:\n logging.error(\"Can't import neither functools32 nor backports.functools_lru_cache\")\n raise\n\nimport commonl\nimport ttbl\nimport ttbl.config\nimport ttbl.user_control\n\npath = None\n\nclass exception(Exception):\n pass\n\nclass invalid_e(exception):\n def __init__(self, allocationid):\n exception.__init__(\n self, \"%s: non-existing allocation\" % allocationid)\n\nstates = {\n \"invalid\": \"allocation is not valid (might have expired)\",\n \"queued\": \"allocation is queued\",\n \"rejected\": \"allocation of %(targets)s not allowed: %(reason)s\",\n \"active\": \"allocation is being actively used\",\n # one of your targets was kicked out and another one assigned on\n # its place, so go call GET /PREFIX/allocation/ALLOCATIONID to get\n # the new targets and restart your run\n \"restart-needed\": \"allocation has been changed by a higher priority allocator\",\n \"expired\": \"allocation idle timer has expired and has been revoked\",\n}\n\nclass one_c(object):\n\n def __init__(self, allocationid, dirname):\n self.path = dirname\n self.allocationid = allocationid\n if not os.path.isdir(path):\n raise invalid_e(allocationid)\n\n def timestamp(self):\n # Just open the file and truncate it, so if it does not exist,\n # it will be created.\n with open(os.path.join(self.state_dir, \"timestamp\"), \"w\") as f:\n f.write(time.strftime(\"%c\\n\"))\n\n def set(self, field, value):\n if value != None:\n assert isinstance(value, basestring)\n assert len(value) < 1023\n location = os.path.join(self.path, field)\n if value == None:\n try:\n os.unlink(location)\n except OSError as e:\n if e.errno != errno.ENOENT:\n raise\n else:\n # New location, add a unique thing to it so there is no\n # collision if more than one process is trying to modify\n # at the same time; they can override each other, that's\n # ok--the last one wins.\n location_new = location + \"-%s-%s-%s\" \\\n % (os.getpid(), self.uuid_seed, time.time())\n commonl.rm_f(location_new)\n os.symlink(value, location_new)\n os.rename(location_new, location)\n\n def get(self, field, default = None):\n location = os.path.join(self.path, field)\n try:\n return os.readlink(location)\n except OSError as e:\n if e.errno == errno.ENOENT:\n return default\n raise\n\n\ndef target_is_valid(target_name):\n # FIXME: validate with the inventory\n # FIXME: LRU cache this? target's won't change that much\n return True\n\n\n#@functools32.lru_cache(maxsize = 200)\n#def get\n\ndef request(groups, user, obo_user,\n priority = None, preempt = False,\n queue = False, reason = None):\n \"\"\"\n :params list(str) groups: list of groups of targets\n\n \"\"\"\n assert isinstance(groups, dict)\n for group_name, target_list in groups.items():\n assert isinstance(group_name, basestring)\n assert isinstance(target_list, list)\n # FIXME: verify not empty\n for target_name in target_list:\n assert isinstance(target_name, basestring)\n assert target_is_valid(target_name)\n\n user = user._get_current_object()\n obo_user = obo_user._get_current_object()\n assert isinstance(user, ttbl.user_control.User), \\\n \"user is %s (%s)\" % (user, type(user))\n assert isinstance(obo_user, ttbl.user_control.User)\n\n if priority != None:\n assert priority > 0\n # FIXME: verify calling user has this priority\n else:\n priority = 500 # DEFAULT FROM USER\n\n assert isinstance(preempt, bool)\n assert isinstance(queue, bool)\n assert reason == None or isinstance(reason, basestring)\n\n allocationid = commonl.mkid(obo_user.get_id() + str(time.time()))\n\n dirname = os.path.join(path, allocationid)\n commonl.makedirs_p(dirname + \"/guests\")\n commonl.makedirs_p(dirname + \"/groups\")\n alloc = one_c(allocationid, dirname)\n\n alloc.set(\"user\", obo_user.get_id())\n alloc.set(\"creator\", user.get_id())\n alloc.timestamp()\n for group in groups:\n # FIXME: this is severly limited in size, we need a normal file to set this info with one target per file\n alloc.set(\"groups/\" + group, \" \".join(group))\n\n result = {\n # { 'busy', 'queued', 'allocated', 'rejected' },\n \"state\": 'rejected',\n \"allocationid\": allocationid,\n #\"allocationid\": None, # if queued; derived from OWNER's cookie\n # \"not allowed on TARGETNAMEs\"\n # \"targets TARGETNAMEs are busy\"\n \"message\": \"not implemented yet\"\n }\n return result\n\n\ndef query():\n # list all allocations\n return {\n \"result\": {\n \"ALLOCATIONID\": {\n # \"unknown\", \"allocated\", \"queued\", \"rejected\"\n \"state\": \"unknown\",\n # \"groupname\": [ target1, target 2... ]\t# if queued\n # \"guests\": [ \"user1\", \"user2\" ... ]\t# if allocated\n # \"user\":\"user1\"\t\t\t# if allocated, allocation owner\n }\n }\n }\n\n\ndef get(allocationid):\n return {\n # \"unknown\", \"allocated\", \"queued\", \"rejected\"\n \"state\": \"unknown\",\n # \"groupname\": [ target1, target 2... ]\t# if queued\n # \"guests\": [ \"user1\", \"user2\" ... ]\t# if allocated\n # \"user\":\"user1\"\t\t\t# if allocated, allocation owner\n }\n\n\ndef keepalive(allocations):\n # {\n # \"allocationid1\": state,\n # \"allocationid2\": state,\n # \"allocationid3\": state,\n # ...\n # }\n # {\n # \"allocationid4\": new_state,\n # \"allocationid3\": new_state,\n # ...\n # }\n return {}\n\n\ndef delete(allocationid):\n # if pending, remove all queuing of it\n # if allocated, release all targets\n return {\n # \"unknown\", \"allocated\", \"queued\", \"rejected\"\n \"state\": \"unknown\",\n # \"groupname\": [ target1, target 2... ]\t\t# if queued\n }\n\n\ndef guest_add(allocationid, user):\n # verify user is valid\n return { }\n\ndef guest_remove(allocationid, user):\n # verify user is valid\n # verify user in allocation\n return { }\n","sub_path":"ttbd/ttbl/allocation.py","file_name":"allocation.py","file_ext":"py","file_size_in_byte":6590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"349056722","text":"import pika\nimport sys\n\nconnection = pika.BlockingConnection(\n pika.ConnectionParameters(host='localhost'))\n\nchannel = connection.channel()\n\nchannel.exchange_declare(\n exchange='direct_msgs',\n exchange_type='direct'\n)\n\nresult = channel.queue_declare(\n queue='',\n exclusive=True\n)\n\nqueue_name = result.method.queue\n\nroute = sys.argv[1]\n\nchannel.queue_bind(\n exchange='direct_msgs',\n queue=queue_name,\n routing_key=route\n)\n\ndef callback(ch, method, properties, body):\n print(f\" [x] {method.routing_key}: {body}\")\n\n\nchannel.basic_consume(\n queue=queue_name,\n on_message_callback=callback,\n auto_ack=True\n)\n\ntry:\n channel.start_consuming()\nexcept KeyboardInterrupt:\n print('Interrupted')","sub_path":"RabbitMQ/Routing/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"451397025","text":"from django import forms\r\n\r\n\r\nfrom models import Workout_Event\r\n\r\n\r\nclass CreateForm(forms.ModelForm):\r\n\r\n class Meta:\r\n model = Workout_Event\r\n fields = ('event_name', 'event_type', 'location', 'date',\r\n 'time_start', 'time_end', 'workout_description',\r\n 'experience_level', 'number_of_spots',)\r\n","sub_path":"project_code/joinmyworkout/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"376254486","text":"#!/usr/bin/env python\nStr= ['1950 0025',\n'1950 0022',\n'1950 0011',\n'1949 0031', \n'1949 0111',\n'1949 0078',\n'1948 0023',\n'1948 0019']\n(last_key, tot_val, avg_val, ctr, cum_val) = (None, 0, 0, 0, 0)\nfor line in Str:\n (key, val) = line.strip().split(\" \")\n if last_key and last_key != key:\n avg_val = float(cum_val/ctr)\n print(last_key, avg_val)\n (ctr, cum_val) = (1, 0)\n (last_key, tot_val) = (key, int(val))\n cum_val = cum_val + tot_val\n else:\n (last_key,tot_val) = (key,int(val))\n ctr = ctr + 1\n cum_val = cum_val + tot_val\n last_key = key\n #(last_key, tot_val) = (key, sum(int(val)))\nif last_key:\n #ctr = ctr + 1\n avg_val = float(cum_val/ctr)\n print(last_key, avg_val)\n","sub_path":"PycharmProjects/python/venv/Lib/site-packages/Avg_func.py","file_name":"Avg_func.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"482103178","text":"import sys\nimport logging\nimport pymongo\nimport traceback\n\n\n# Requires pymongo==3.6.0\nclass MongoManager:\n def __init__(self, logger=None, uri=None, host=\"localhost\", port=27017, use_uri=True, db=\"test_db\",\n collection=\"test_collection\"):\n if not logger:\n self.logger = logging.getLogger(\"Mongo Logger\")\n self.logger.setLevel(logging.DEBUG)\n logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)\n else:\n self.logger = logger\n\n if use_uri:\n self.client = pymongo.MongoClient(uri)\n else:\n self.client = pymongo.MongoClient(host=host, port=port)\n\n self.db = self.client[db]\n self.collection = self.db[collection]\n\n def insert_one(self, document):\n \"\"\"\n Inserts a document into Mongo\n :param document: (Dict) Mongo Document\n :return: (String) _id of the inserted document\n \"\"\"\n try:\n return self.collection.insert_one(document=document).inserted_id\n except Exception:\n self.logger.error(\"Error inserting one object to mongo. Traceback: %s\" % str(traceback.format_exc(1)))\n return None\n\n def find_one(self):\n \"\"\"\n Returns a random document from a collection\n :return: (Dict)\n \"\"\"\n try:\n return self.collection.find_one()\n except Exception:\n self.logger.error(\"Error finding one object from mongo. Traceback: %s\" % str(traceback.format_exc(1)))\n return None\n\n def find_by_id(self, id):\n \"\"\"\n Returns the document matching that _id\n :param id: (String) _id\n :return: (Dict) if found, None is not Found\n \"\"\"\n try:\n return self.collection.find_one({\"_id\": id})\n except Exception:\n self.logger.error(\"Error finding object from mongo. Traceback: %s\" % str(traceback.format_exc(1)))\n return None\n\n def get_all(self, max_docs=0):\n \"\"\"\n Returns a list of all docs\n :return:\n \"\"\"\n try:\n docs = list()\n result = self.collection.find({}).limit(max_docs)\n for entry in result:\n docs.append(entry)\n\n return docs\n except Exception:\n self.logger.error(\"Error finding object from mongo. Traceback: %s\" % str(traceback.format_exc(1)))\n return None\n\n def query(self, query):\n \"\"\"\n Query using proper query dictionary\n :param query:\n :return: (list) of documents. returns [] if no match\n \"\"\"\n try:\n docs = list()\n result = self.collection.find(query)\n for entry in result:\n docs.append(entry)\n\n return docs\n except Exception:\n self.logger.error(\"Error finding objects from mongo. Traceback: %s\" % str(traceback.format_exc(1)))\n return None\n\n def save(self, document):\n \"\"\"\n Returns _id of the Saved document\n :param document: (Dict) JSON containing the _id field\n :return:\n \"\"\"\n try:\n return self.collection.save(document, manipulate=True)\n except Exception:\n self.logger.error(\"Error saving object to mongo. Traceback: %s\" % str(traceback.format_exc(1)))\n return None","sub_path":"utils/mongo_manager.py","file_name":"mongo_manager.py","file_ext":"py","file_size_in_byte":3368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"420414757","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\n\"\"\"\nThis module contains implementations of the old compound model interfaces that\nare now deprecated.\n\nThe classes exported by this module should be imported from `astropy.modeling`\nrather than from `astropy.modeling.core` or from this module directly.\n\"\"\"\n\nfrom __future__ import (absolute_import, unicode_literals, division,\n print_function)\n\nimport functools\nimport operator\nimport warnings\n\nimport numpy as np\n\nfrom ..utils import deprecated, indent\nfrom ..utils.compat.odict import OrderedDict\nfrom ..utils.exceptions import AstropyDeprecationWarning\nfrom .core import Model\n\n\n__all__ = ['LabeledInput', 'SerialCompositeModel', 'SummedCompositeModel']\n\n\n@deprecated('1.0', alternative=':ref:`compound-models` as described in the '\n 'Astropy documentation')\nclass LabeledInput(OrderedDict):\n \"\"\"\n Used by `SerialCompositeModel` and `SummedCompositeModel` to choose input\n data using labels.\n\n This is a container assigning labels (names) to all input data arrays to a\n composite model.\n\n Parameters\n ----------\n data : list\n List of all input data\n labels : list of strings\n names matching each coordinate in data\n\n Examples\n --------\n >>> y, x = np.mgrid[:5, :5]\n >>> l = np.arange(10)\n >>> labeled_input = LabeledInput([x, y, l], ['x', 'y', 'pixel'])\n >>> labeled_input.x\n array([[0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4]])\n >>> labeled_input['x']\n array([[0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4]])\n \"\"\"\n\n def __init__(self, data, labels):\n if len(labels) != len(data):\n raise TypeError(\"Number of labels and data doesn't match\")\n\n super(LabeledInput, self).__init__(zip(labels, data))\n\n def __getattr__(self, label):\n try:\n return self[label]\n except KeyError:\n raise AttributeError(label)\n\n def __setattr__(self, label, data):\n if label.startswith('_'):\n super(LabeledInput, self).__setattr__(label, data)\n else:\n self[label] = data\n\n def __delattr__(self, label):\n try:\n del self[label]\n except KeyError:\n raise AttributeError(label)\n\n @property\n def labels(self):\n return tuple(self.keys())\n\n def add(self, label=None, value=None, **kw):\n \"\"\"\n Add input data to a LabeledInput object\n\n Parameters\n --------------\n label : str\n coordinate label\n value : numerical type\n coordinate value\n kw : dictionary\n if given this is a dictionary of ``{label: value}`` pairs\n \"\"\"\n\n if ((label is None and value is not None) or\n (label is not None and value is None)):\n raise TypeError(\"Expected label and value to be defined\")\n\n kw[label] = value\n\n self.update(kw)\n\n def copy(self):\n return LabeledInput(self.values(), self.labels)\n\n\nclass _LabeledInputMapping(Model):\n def __init__(self, labeled_input, inmap, outmap):\n self._labeled_input = labeled_input\n self._inmap = tuple(inmap)\n self._outmap = tuple(outmap)\n super(_LabeledInputMapping, self).__init__()\n\n def __repr__(self):\n return '<{0}>'.format(self.name)\n\n @property\n def inputs(self):\n return self._outmap\n\n @property\n def outputs(self):\n return self._inmap\n\n @property\n def name(self):\n return '{0}({1} -> {2})'.format(self.__class__.__name__,\n self._outmap, self._inmap)\n\n def evaluate(self, *inputs):\n for idx, label in enumerate(self._outmap):\n self._labeled_input[label] = inputs[idx]\n\n result = tuple(self._labeled_input[label] for label in self._inmap)\n\n if len(result) == 1:\n return result[0]\n else:\n return result\n\n\nclass _CompositeModel(Model):\n \"\"\"Base class for all composite models.\"\"\"\n\n _operator = None\n fittable = False\n\n def __init__(self, transforms, n_inputs, n_outputs, inmap=None,\n outmap=None):\n self._transforms = transforms\n param_names = []\n for tr in self._transforms:\n param_names.extend(tr.param_names)\n super(_CompositeModel, self).__init__()\n self.param_names = param_names\n self._n_inputs = n_inputs\n self._n_outputs = n_outputs\n self._basic_transform = None\n\n self._inmap = inmap\n self._outmap = outmap\n\n def __repr__(self):\n return '<{0}([\\n{1}\\n])>'.format(\n self.__class__.__name__,\n indent(',\\n'.join(repr(tr) for tr in self._transforms),\n width=4))\n\n def __str__(self):\n parts = ['Model: {0}'.format(self.__class__.__name__)]\n for tr in self._transforms:\n parts.append(indent(str(tr), width=4))\n return '\\n'.join(parts)\n\n @property\n def inputs(self):\n return self._transforms[0].inputs\n\n @property\n def outputs(self):\n return self._transforms[-1].outputs\n\n @property\n def n_inputs(self):\n return self._n_inputs\n\n @n_inputs.setter\n def n_inputs(self, val):\n warnings.warn(\n 'Setting n_inputs on {0} objects is undefined and should not '\n 'be used.'.format(self.__class__.__name__),\n AstropyDeprecationWarning)\n self._n_inputs = val\n\n @property\n def n_outputs(self):\n return self._n_outputs\n\n @n_outputs.setter\n def n_outputs(self, val):\n warnings.warn(\n 'Setting n_outputs on {0} objects is undefined and should not '\n 'be used.'.format(self.__class__.__name__),\n AstropyDeprecationWarning)\n self._n_outputs = val\n\n def invert(self):\n raise NotImplementedError(\"Subclasses should implement this\")\n\n @property\n def parameters(self):\n raise NotImplementedError(\n \"Composite models do not currently support the .parameters \"\n \"array.\")\n\n def evaluate(self, *inputs):\n \"\"\"\n Specialized `Model.evaluate` implementation that allows `LabeledInput`\n inputs to be handled when calling this model.\n\n This ignores any passed in parameter values, as _CompositeModels can't\n be fitted anyways.\n \"\"\"\n\n # Drop parameter arguments\n inputs = inputs[:self.n_inputs]\n\n if len(inputs) == 1 and isinstance(inputs[0], LabeledInput):\n labeled_input = inputs[0].copy()\n transform = self._make_labeled_transform(labeled_input)\n inputs = [labeled_input[label] for label in self._inmap[0]]\n result = transform(*inputs)\n\n if self._transforms[-1].n_outputs == 1:\n labeled_input[self._outmap[-1][0]] = result\n else:\n for label, output in zip(self._outmap[-1], result):\n labeled_input[label] = output\n\n return labeled_input\n else:\n if self._basic_transform is None:\n transform = self._transforms[0]\n for t in self._transforms[1:]:\n transform = self._operator(transform, t)\n\n self._basic_transform = transform\n\n return self._basic_transform(*inputs)\n\n def __call__(self, *inputs):\n \"\"\"\n Specialized `Model.__call__` implementation that allows\n `LabeledInput` inputs to be handled when calling this model.\n \"\"\"\n\n return self.evaluate(*inputs)\n\n def _param_sets(self, raw=False):\n all_params = tuple(m._param_sets(raw=raw) for m in self._transforms)\n return np.vstack(all_params)\n\n def _make_labeled_transform(self, labeled_input):\n \"\"\"\n Build up a transformation graph that incorporates the instructions\n encoded in the `LabeledInput` object.\n\n This requires use of the ``_inmap`` and ``_outmap`` attributes set\n when instantiating this `_CompositeModel`.\n \"\"\"\n\n if self._inmap is None:\n raise TypeError(\"Parameter 'inmap' must be provided when \"\n \"input is a labeled object.\")\n if self._outmap is None:\n raise TypeError(\"Parameter 'outmap' must be provided when \"\n \"input is a labeled object\")\n\n transforms = [self._transforms[0]]\n previous_outmap = self._outmap[0]\n for model, inmap, outmap in zip(self._transforms[1:], self._inmap[1:],\n self._outmap[1:]):\n mapping = _LabeledInputMapping(labeled_input, inmap,\n previous_outmap)\n transforms.append(mapping | model)\n previous_outmap = outmap\n\n return functools.reduce(self._operator, transforms)\n\n\n@deprecated('1.0', alternative=':ref:`compound-models` as described in the '\n 'Astropy documentation')\nclass SerialCompositeModel(_CompositeModel):\n \"\"\"\n Composite model that evaluates models in series.\n\n Parameters\n ----------\n transforms : list\n a list of transforms in the order to be executed\n inmap : list of lists or None\n labels in an input instance of LabeledInput\n if None, the number of input coordinates is exactly what\n the transforms expect\n outmap : list or None\n labels in an input instance of LabeledInput\n if None, the number of output coordinates is exactly what\n the transforms expect\n n_inputs : int\n dimension of input space (e.g. 2 for a spatial model)\n n_outputs : int\n dimension of output\n\n Notes\n -----\n Output values of one model are used as input values of another.\n Obviously the order of the models matters.\n\n Examples\n --------\n Apply a 2D rotation followed by a shift in x and y::\n\n >>> import numpy as np\n >>> from astropy.modeling import models, LabeledInput, SerialCompositeModel\n >>> y, x = np.mgrid[:5, :5]\n >>> rotation = models.Rotation2D(angle=23.5)\n >>> offset_x = models.Shift(-4.23)\n >>> offset_y = models.Shift(2)\n >>> labeled_input = LabeledInput([x, y], [\"x\", \"y\"])\n >>> transform = SerialCompositeModel([rotation, offset_x, offset_y],\n ... inmap=[['x', 'y'], ['x'], ['y']],\n ... outmap=[['x', 'y'], ['x'], ['y']])\n >>> result = transform(labeled_input)\n \"\"\"\n\n _operator = operator.or_\n\n def __init__(self, transforms, inmap=None, outmap=None, n_inputs=None,\n n_outputs=None):\n if n_inputs is None:\n n_inputs = max([tr.n_inputs for tr in transforms])\n # the output dimension is equal to the output dim of the last\n # transform\n n_outputs = transforms[-1].n_outputs\n else:\n if n_outputs is None:\n raise TypeError(\"Expected n_inputs and n_outputs\")\n\n if transforms and inmap and outmap:\n if not (len(transforms) == len(inmap) == len(outmap)):\n raise ValueError(\"Expected sequences of transform, \"\n \"inmap and outmap to have the same length\")\n\n super(SerialCompositeModel, self).__init__(\n transforms, n_inputs, n_outputs, inmap=inmap, outmap=outmap)\n\n def inverse(self):\n try:\n transforms = []\n for transform in self._transforms[::-1]:\n transforms.append(transform.inverse)\n except NotImplementedError:\n raise NotImplementedError(\n \"An analytical inverse has not been implemented for \"\n \"{0} models.\".format(transform.__class__.__name__))\n if self._inmap is not None:\n inmap = self._inmap[::-1]\n outmap = self._outmap[::-1]\n else:\n inmap = None\n outmap = None\n return SerialCompositeModel(transforms, inmap, outmap)\n\n\n@deprecated('1.0', alternative=':ref:`compound-models` as described in the '\n 'Astropy documentation')\nclass SummedCompositeModel(_CompositeModel):\n \"\"\"\n Composite model that evaluates models in parallel.\n\n Parameters\n --------------\n transforms : list\n transforms to be executed in parallel\n inmap : list or None\n labels in an input instance of LabeledInput\n if None, the number of input coordinates is exactly what the\n transforms expect\n outmap : list or None\n\n Notes\n -----\n Evaluate each model separately and add the results to the input_data.\n \"\"\"\n\n _operator = operator.add\n\n def __init__(self, transforms, inmap=None, outmap=None):\n n_inputs = transforms[0].n_inputs\n n_outputs = n_inputs\n for transform in transforms:\n if not (transform.n_inputs == transform.n_outputs == n_inputs):\n raise ValueError(\"A SummedCompositeModel expects n_inputs = \"\n \"n_outputs for all transforms\")\n\n super(SummedCompositeModel, self).__init__(transforms, n_inputs,\n n_outputs, inmap=inmap,\n outmap=outmap)\n","sub_path":"lib/python2.7/site-packages/astropy/modeling/_compound_deprecated.py","file_name":"_compound_deprecated.py","file_ext":"py","file_size_in_byte":13559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"255323951","text":"import time\nimport os\nimport sys\n\nif sys.version_info[0] < 3:\n raise Exception(\"Must be using Python 3\\nRun using python3 instead of python\")\n\nos.system(\"sudo apt-get install -qq python3-pip < /dev/null > /dev/null\")\ntry:\n import requests\nexcept ImportError:\n os.system(\"pip3 install requests\")\n print(\"Installing Dependencies...\\n\")\n time.sleep(3)\n import requests\ntry:\n from bs4 import BeautifulSoup\nexcept ImportError:\n os.system(\"sudo apt-get install python3-bs4\")\n time.sleep(3)\n from bs4 import BeautifulSoup\ntry:\n from mailjet_rest import Client\nexcept ImportError:\n os.system(\"pip3 install mailjet_rest\")\n time.sleep(3)\n from mailjet_rest import Client\n\ntimer = 60 * 60\n\n\ndef smtp_send_email(email, nameam, priceam, namefl, pricefl, URL, j):\n api_key = '9c357ca9d2e695d571117648c47680c8'\n api_secret = '3b51faf454e90309d8b9ec695b25a8c1'\n mailjet = Client(auth=(api_key, api_secret), version='v3.1')\n expectedprice = expected_prompt()\n URL2 = \"https://www.amazon.in/s?k=\" + title2.replace(' ', '+').replace('(', '%28').replace(')', '%29').replace(',',\n '%2C')\n\n if j == 1:\n URL2 = \"https://www.amazon.in/s?k=\" + title2.replace(' ', '+').replace('(', '%28').replace(')', '%29').replace(\n ',', '%2C')\n data = {\n 'Messages': [\n {\n 'From': {\n 'Email': 'dr_pricetracker@mailinator.com',\n 'Name': 'Price Tracker'\n },\n\n 'To': [\n {\n 'Email': email\n }\n ],\n\n 'Subject': 'Price Drop Alert for ' + nameam + ' on Amazon',\n 'TextPart': 'Dear User, the price of ' + nameam + ' has dropped below Rs.' + str(\n expectedprice) + '.\\nCheck it out: ' + URL2\n }\n ]\n }\n\n if j == 2:\n data = {\n 'Messages': [\n {\n 'From': {\n 'Email': 'dr_pricetracker@mailinator.com',\n 'Name': 'Price Tracker'\n },\n\n 'To': [\n {\n 'Email': email\n }\n ],\n\n 'Subject': 'Price Drop Alert for ' + namefl + ' on Flipkart',\n 'TextPart': 'Dear User, the price of ' + namefl + ' has dropped below Rs.' + str(\n expectedprice) + '.\\nCheck it out: ' + URL\n }\n ]\n }\n\n while True:\n if j == 1:\n if priceam < expectedprice:\n result = mailjet.send.create(data=data)\n print(\"Email sent successfully!\\nExitting!\\n\")\n exit(0)\n else:\n print(\n \"\\nThe price right now is above your target price\\nThis program will check every hour for price drop\\nKeep this program running to get notified!\")\n time.sleep(timer)\n (priceam, namefl) = price_amazon_search(URL2, headers)\n continue\n\n if j == 2:\n if pricefl < expectedprice:\n result = mailjet.send.create(data=data)\n print(\"Email sent successfully!\\nExitting!\\n\")\n exit(0)\n else:\n print(\n \"\\nThe price right now is above your target price\\nThis program will check every hour for price drop\\nKeep this program running to get notified!\")\n time.sleep(timer)\n (pricefl, namefl) = price_flipkart_search(namefl, headers)\n continue\n\n if j == 3:\n # if pricefl expectedprice) or (j == 2 and pricefl > expectedprice) or (\n j == 3 and pricefl > expectedprice and priceam > expectedprice):\n print(\n \"\\nThe price right now is above your target price\\nThis program will check every hour for price drop\\nKeep this program running to get notified!\")\n time.sleep(timer)\n (priceam, nameam) = price_amazon_search(URL2, headers)\n (pricefl, namefl) = price_flipkart_search(URL, headers)\n continue\n\n result = str(mailjet.send.create(data=data))\n if result == '':\n print(\"Email sent successfully!\\nExitting!\\n\")\n exit(0)\n else:\n print(\"There was some trouble sending the email\\n\")\n print(\"Error Code: \" + str(result) + '\\n')\n\n\ndef expected_prompt():\n while (1):\n expectedpricein = input(\"\\nEnter the price below which you want to get notified:\\nRs.\")\n\n try:\n expectedprice = int(expectedpricein)\n return expectedprice\n except ValueError:\n print(\"Please enter a valid number!\")\n\n\ndef track_prompt(email, nameam, priceam, namefl, pricefl, URL):\n j = 9\n while True:\n j = int(input(\n \"\\nChoose an option:\\n1. Track on Amazon\\n2. Track on Flipkart\\n3. Track on both\\n0. Go back to previous menu\\n9. Exit\\n\"))\n if j == 0:\n return j, email\n if j == 9:\n exit(0)\n if j == 1 or j == 2 or j == 3:\n if email == '':\n email = str(input(\"Enter your Email ID: \"))\n smtp_send_email(email, nameam, priceam, namefl, pricefl, URL, j)\n else:\n print(\"Invalid option!\\nTry Again\\n\")\n\n\ndef price_amazon(URL, headers):\n page = requests.get(URL.strip(), headers=headers)\n\n soup2 = BeautifulSoup(page.content, 'html.parser')\n soup = BeautifulSoup(soup2.prettify(), 'html.parser')\n\n title = soup.find(id='productTitle').get_text()\n\n price = soup.find(id='priceblock_ourprice').get_text()\n converted_price = float(price.replace(',', '').replace('Rs.', '').strip())\n\n return converted_price, title.strip()\n\n\ndef price_flipkart(URL, headers):\n page = requests.get(URL.strip(), headers=headers)\n\n soup2 = BeautifulSoup(page.content, 'html.parser')\n soup = BeautifulSoup(soup2.prettify(), 'html.parser')\n\n mydivs2 = soup.find(\"div\", {\"class\": \"_1vC4OE\" and \"_3qQ9m1\"}).encode('utf-8')\n\n if mydivs2 == 'None':\n mydivs = soup.find(\"div\", {\"class\": \"_1vC4OE\"}).get_text().encode('utf-8')\n else:\n mydivs = soup.find(\"div\", {\"class\": \"_1vC4OE\" and \"_3qQ9m1\"}).get_text().encode('utf-8')\n\n price = mydivs[3:]\n converted_price = float(price.replace(',', '').replace('Rs.', '').strip())\n title2 = str(soup.find(\"span\", {'class': '_35KyD6'}))\n\n if title2 == 'None':\n title = str(soup.find(\"a\", {'class': '_2cLu-l'})['title'])\n else:\n title = str(soup.find(\"span\", {'class': '_35KyD6'}).get_text())\n\n return converted_price, title.strip()\n\n\n# Search by product:\ndef price_flipkart_search(URL, headers):\n page = requests.get(URL.strip(), headers=headers)\n\n soup2 = BeautifulSoup(page.content, 'html.parser')\n soup = BeautifulSoup(soup2.prettify(), 'html.parser')\n\n mydivs2 = soup.find(\"div\", {\"class\": \"_1vC4OE\"}).encode('utf-8')\n if mydivs2 == 'None':\n mydivs = soup.find(\"div\", {\"class\": \"_1vC4OE\" and \"_2rQ-NK\"}).get_text().strip().encode('utf-8')\n else:\n mydivs = str(soup.find(\"div\", {\"class\": \"_1vC4OE\"}).get_text().strip())\n #print(mydivs)\n price = mydivs[1:]\n converted_price = float(price.replace(',', '').strip())\n __title2 = soup.find('div', {\"class\": \"_3wU53n\"})\n if str(__title2) != 'None':\n __title = str(__title2.get_text().strip())\n else:\n __title2 = soup.find('a', {\"class\": \"_2cLu-l\"})['title']\n __title = str(__title2.strip())\n return converted_price, __title\n\n\ndef price_amazon_search(URL, headers):\n page = requests.get(URL.strip(), headers=headers)\n\n soup2 = BeautifulSoup(page.content, 'html.parser')\n soup = BeautifulSoup(soup2.prettify(), 'html.parser')\n\n allSponsored = soup.find_all(\"a\", {\"class\": \"a-link-normal\" and \"a-text-normal\"})\n\n i = 0\n allprice = soup.find_all(\"span\", {\"class\": \"a-price-whole\"})\n alltitle = soup.find_all(\"span\", {\"class\": \"a-size-medium\" and \"a-color-base\" and \"a-text-normal\"})\n price = str('')\n __title = str('')\n\n i = 0\n\n for element in allSponsored:\n if element['href'][0:11] == '/gp/slredir':\n i += 1\n else:\n break\n\n j = 0\n for element in allprice:\n if j == i:\n price = element.get_text().strip()\n break\n else:\n j += 1\n\n k = 0\n for element in alltitle:\n if k == i / 2:\n __title = element.get_text().strip()\n break\n else:\n k += 1\n\n converted_price = float(price.replace(',', '').replace('Rs.', '').strip())\n # print(converted_price)\n return converted_price, __title\n\n\nemail = ''\nexpectedprice = int(0)\nheaders = {\n \"User-Agent\": 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'}\n\nwhile True:\n i2 = input(\"Choose an option:\\n1. Search by URL\\n2. Search by product name\\n9. Exit\\n\")\n try:\n i = int(i2)\n except ValueError:\n print(\"Please enter a valid number\\n\")\n continue\n if i == 1:\n URL = str(input(\"Enter URL of product:\"))\n\n # headers = {\"User-Agent\": 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'}\n\n if URL.find(\"amazon.in\") < len(URL) and URL.find(\"amazon.in\") > 0:\n (priceam, nameam) = price_amazon(URL, headers)\n print('\\n')\n print(\"Amazon:\\n\" + nameam + ': Rs.' + str(int(priceam)))\n\n flipurl = \"https://www.flipkart.com/search?q=\" + nameam.replace(' ', '%20').replace('(', '%20').replace(')',\n '%20')\n (pricefl, namefl) = price_flipkart_search(flipurl, headers)\n\n print(\"Flipkart:\\n\" + namefl + ': Rs.' + str(int(pricefl)) + '\\n')\n\n if pricefl < priceam:\n print(\"Cheaper on Flipkart by Rs.\" + str(priceam - pricefl) + '\\n')\n if priceam < pricefl:\n print(\"Cheaper on Amazon by Rs.\" + str(pricefl - priceam) + '\\n')\n if priceam == pricefl:\n print(\"Same price on Amazon and Flipkart.\\n\")\n\n track_prompt(email, nameam, priceam, namefl, pricefl, URL)\n\n else:\n if URL.find(\"flipkart.com\") < len(URL) and URL.find(\"flipkart.com\") > 0:\n (pricefl, namefl) = price_flipkart(URL, headers)\n print(\"\\nFlipkart:\\n\" + namefl + ': Rs.' + str(int(pricefl)) + '\\n')\n\n amazurl = \"https://www.amazon.in/s?k=\" + namefl.replace(' ', '+').replace('(', '%28').replace(')',\n '%29').replace(\n ',', '%2C')\n (priceam, nameam) = price_amazon_search(amazurl, headers)\n print(\"Amazon:\\n\" + nameam + ': Rs.' + str(int(priceam)) + '\\n')\n\n if pricefl < priceam:\n print(\"Cheaper on Flipkart by Rs.\" + str(priceam - pricefl) + '\\n')\n if priceam < pricefl:\n print(\"Cheaper on Amazon by Rs.\" + str(pricefl - priceam) + '\\n')\n if priceam == pricefl:\n print(\"Same price on Amazon and Flipkart.\\n\")\n\n track_prompt(email, nameam, priceam, namefl, pricefl, URL)\n\n else:\n print(\"Invalid URL\")\n continue\n\n if i == 2:\n title = str(input(\"Enter name of product: \"))\n title2 = title\n URL = \"https://www.flipkart.com/search?q=\" + title.replace(' ', '%20')\n # headers = {\"User-Agent\": 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'}\n\n (price, namefl) = price_flipkart_search(URL, headers)\n\n URL2 = \"https://www.amazon.in/s?k=\" + title2.replace(' ', '+')\n # print(URL2)\n (price2, nameam) = price_amazon_search(URL2, headers)\n\n print('\\n')\n print(\"Flipkart:\")\n print(namefl + ': Rs.' + str(int(price)))\n print(\"Amazon:\")\n print(nameam + ': Rs.' + str(int(price2)) + '\\n')\n\n if price < price2:\n print(\"Cheaper on Flipkart by Rs.\" + str(price2 - price) + '\\n')\n if price2 < price:\n print(\"Cheaper on Amazon by Rs.\" + str(price - price2) + '\\n')\n if price == price2:\n print(\"Same price on Amazon and Flipkart.\\n\")\n\n track_prompt(email, nameam, price2, namefl, price, URL)\n\n if i == 4:\n # test\n print(\"Sending Email\")\n smtp_send_email()\n\n if i == 9:\n print(\"\\nThank You for using this tool\\nHave a nice day\\n\")\n exit(0)\n\n if i == 404:\n print(\n \"\\nYou've chosen the option to change your user agent\\nTo change your user agent, simply Google 'What's my user agent' and paste the result here: \")\n agentcustom = str(input())\n headers = {\"User-Agent\": agentcustom}\n\n if i != 1 and i != 2 and i != 404 and i != 9:\n print(\"Please Choose a valid option\")\n","sub_path":"price_checker_mail_final_universal.py","file_name":"price_checker_mail_final_universal.py","file_ext":"py","file_size_in_byte":16734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"107391507","text":"# 分片结构\nimport conn_redis\nimport binascii\nimport datetime\nimport math\nimport uuid\n\nSHARD_SIZE = 512\nDAILY_EXPECTED = 1000000\nEXPECTED = {}\n\n\ndef shard_key(base, key, total_elements, shard_size):\n \"\"\"\n 获取分片后的key\n @param base: 基础key\n @param key: 要存的map key\n @param total_elements: 预计的成员总数\n @param shard_size: 每个分片的尺寸\n @return:\n \"\"\"\n\n if isinstance(key, int) or key.isdigit():\n shard_id = int(str(key), 10) // shard_size\n else:\n shards = 2 * total_elements // shard_size\n shard_id = binascii.crc32(key.encode()) % shards\n return \"%s%s\" % (base, shard_id)\n\n\ndef shard_hset(conn, base, key, value, total_elements, shard_size):\n \"\"\" 分片版 hset\n\n @param conn:\n @param base:\n @param key:\n @param value:\n @param total_elements:\n @param shard_size:\n @return:\n \"\"\"\n\n shard = shard_key(base, key, total_elements, shard_size)\n return conn.hset(shard, key, value)\n\n\ndef shard_hget(conn, base, key, total_elements, shard_size):\n \"\"\" 分片版 hget\n\n @param conn:\n @param base:\n @param key:\n @param total_elements:\n @param shard_size:\n @return:\n \"\"\"\n\n shard = shard_key(base, key, total_elements, shard_size)\n return conn.hget(shard, key)\n\n\ndef shard_sadd(conn, base, member, total_elements, shard_size):\n \"\"\" 分片sadd\n\n @param conn:\n @param base:\n @param member:\n @param total_elements:\n @param shard_size:\n @return:\n \"\"\"\n shard_id = shard_key(base, \"X\" + str(member), total_elements, shard_size)\n return conn.sadd(shard_id, member)\n\n\ndef count_visit(conn, uid):\n \"\"\" 计算唯一访客量\n\n @param conn:\n @param str uid:\n @return:\n \"\"\"\n today = datetime.date.today()\n key = \"unique:%s\" % today.isoformat()\n expected = get_expected(conn, key, today)\n member = int(uid.replace(\"-\", \"\")[:15], 16)\n if shard_sadd(conn, key, member, expected, SHARD_SIZE):\n conn.incr(key)\n\n\ndef get_expected(conn, key, today):\n \"\"\" 每天预计的访问量\n\n @param conn:\n @param key:\n @param today:\n @return:\n \"\"\"\n if key in EXPECTED:\n return EXPECTED[key]\n ex_key = key + \":expected\"\n expected = conn.get(ex_key)\n if not expected:\n yesterday = (today - datetime.timedelta(days=1)).isoformat()\n expected = conn.get(\"unique:%s\" % yesterday)\n expected = int(expected or DAILY_EXPECTED)\n expected = 2 ** int(math.ceil(math.log(expected * 1.5, 2)))\n if not conn.setnx(ex_key, expected):\n expected = conn.get(ex_key)\n EXPECTED[key] = expected\n return EXPECTED[key]\n\n\nif __name__ == '__main__':\n for i in range(100000):\n session_id = uuid.uuid4()\n conn1 = conn_redis.conn\n count_visit(conn1, str(session_id))\n","sub_path":"Unit9/FragmentStructure.py","file_name":"FragmentStructure.py","file_ext":"py","file_size_in_byte":2828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"185380160","text":"import cv2\n \ncapture = cv2.VideoCapture(0)\n \nwhile(True):\n \n ret, img = capture.read()\n #Choose what you want boiii\n img =cv2.Canny(img,20,100)\n # img = cv2.Laplacian(img,cv2.CV_8U)\n # img = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)\n # img = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=3) \n cv2.imshow('video', img)\n \n if cv2.waitKey(1) == 27:\n break\n \ncapture.release()\ncv2.destroyAllWindows()","sub_path":"OpenCV/q32.py","file_name":"q32.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"273797210","text":"# -*- coding: utf-8 -*-\n# This file is part of RRMPG.\n#\n# RRMPG is free software with the aim to provide a playground for experiments\n# with hydrological rainfall-runoff-models while achieving competitive\n# performance results.\n#\n# You should have received a copy of the MIT License along with RRMPG. If not,\n# see \n\n\"\"\"Implementation of the educational version of the HBV model.\"\"\"\n\nimport numbers\n\nimport numpy as np\n\nfrom numba import njit\nfrom scipy import optimize\nfrom .basemodel import BaseModel\nfrom ..utils.metrics import mse\nfrom ..utils.array_checks import check_for_negatives, validate_array_input\n\n\nclass HBVEdu(BaseModel):\n \"\"\"Implementation of the educational version of the HBV model.\n\n Original publication:\n Aghakouchak, Amir, and Emad Habib. \"Application of a conceptual\n hydrologic model in teaching hydrologic processes.\" International\n Journal of Engineering Education 26.4 (S1) (2010).\n\n If no model parameters are passed upon initialization, generates random\n parameter set.\n\n Args:\n area: Area of the basin.\n params: (optional) Dictonary containing all model parameters as a\n seperate key/value pairs.\n\n Raises:\n ValueError: If Area isn't a positive numerical value or on model\n parameter is missing in the passed dictonary.\n\n \"\"\"\n\n # List of model parameters\n _param_list = ['T_t', 'DD', 'FC', 'Beta', 'C', 'PWP', 'K_0', 'K_1', 'K_2',\n 'K_p', 'L']\n\n # Dictionary with default parameter bounds\n _default_bounds = {'T_t': (-1, 1),\n 'DD': (3, 7),\n 'FC': (100, 200),\n 'Beta': (1, 7),\n 'C': (0.01, 0.07),\n 'PWP': (90, 180),\n 'K_0': (0.05, 0.2),\n 'K_1': (0.01, 0.1),\n 'K_2': (0.01, 0.05),\n 'K_p': (0.01, 0.05),\n 'L': (2, 5)}\n\n # Custom numpy datatype needed for numba input\n _dtype = np.dtype([('T_t', np.float64),\n ('DD', np.float64),\n ('FC', np.float64),\n ('Beta', np.float64),\n ('C', np.float64),\n ('PWP', np.float64),\n ('K_0', np.float64),\n ('K_1', np.float64),\n ('K_2', np.float64),\n ('K_p', np.float64),\n ('L', np.float64)])\n\n def __init__(self, area, params=None):\n \"\"\"Initialize a HBVEdu model object.\n\n Args:\n area: Area of the basin.\n params: (optional) Dictonary containing all model parameters as a\n seperate key/value pairs.\n\n Raises:\n ValueError: If Area isn't a positive numerical value or on model\n parameter is missing in the passed dictonary.\n\n \"\"\"\n super().__init__(params=params)\n # Parse inputs\n if (isinstance(area, numbers.Number) and (area > 0)):\n self.area = area\n else:\n raise ValueError(\"Area must be a positiv numercial value.\")\n\n def simulate(self, temp, prec, month, PE_m, T_m, snow_init=0, soil_init=0,\n s1_init=0, s2_init=0, return_storage=False):\n \"\"\"Simulate rainfall-runoff process for given input.\n\n This function bundles the model parameters and validates the\n meteorological inputs, then calls the optimized model routine. Due\n to restrictions with the use of numba, this routine is kept outside\n of this model class.\n The meteorological inputs can be either list, numpy array or pandas \n Series.\n\n Args:\n temp: Array of (mean) temperature for each timestep.\n prec: Array of (summed) precipitation for each timestep.\n month: Array of integers indicating for each timestep to which\n month it belongs [1,2, ..., 12]. Used for adjusted\n potential evapotranspiration.\n PE_m: long-term mean monthly potential evapotranspiration.\n T_m: long-term mean monthly temperature.\n snow_init: (optional) Initial state of the snow reservoir.\n soil_init: (optional) Initial state of the soil reservoir.\n s1_init: (optional) Initial state of the near surface flow\n reservoir.\n s2_init: (optional) Initial state of the base flow reservoir.\n return_storage: (optional) Boolean, indicating if the model \n storages should also be returned.\n\n Returns:\n An array with the simulated streamflow and optional one array for\n each of the four reservoirs.\n\n Raises:\n ValueError: If one of the inputs contains invalid values.\n TypeError: If one of the inputs has an incorrect datatype.\n RuntimeErrror: If the monthly arrays are not of size 12 or there \n is a size mismatch between precipitation, temperature and the\n month array.\n\n \"\"\"\n # Validation check of the temperature, precipitation and input\n temp = validate_array_input(temp, np.float64, 'temperature')\n prec = validate_array_input(prec, np.float64, 'precipitation')\n # Check if there exist negative precipitation\n if check_for_negatives(prec):\n raise ValueError(\"In the precipitation array are negative values.\")\n \n month = validate_array_input(month, np.int8, 'month')\n if any(len(arr) != len(temp) for arr in [prec, month]):\n msg = [\"The arrays of the temperature, precipitation and month \",\n \"data must be of equal size.\"]\n raise RuntimeError(\"\".join(msg))\n\n # Validation check for PE_m and T_m\n PE_m = validate_array_input(PE_m, np.float64, 'PE_m')\n T_m = validate_array_input(T_m, np.float64, 'T_m')\n if any(len(arr) != 12 for arr in [PE_m, T_m]):\n msg = [\"The monthly potential evapotranspiration and temperature\",\n \" array must be of length 12.\"]\n raise RuntimeError(\"\".join(msg))\n\n # Check if entires of month array are between 1 and 12\n if (np.min(month) < 1) or (np.max(month) > 12):\n msg = [\"The month array must be between an integer1 (Jan) and \",\n \"12 (Dec).\"]\n raise ValueError(\"\".join(msg))\n\n # For correct python indexing [start with 0] subtract 1 of month array\n month -= 1\n\n # Make sure all initial storage values are floats\n snow_init = float(snow_init)\n soil_init = float(soil_init)\n s1_init = float(s1_init)\n s2_init = float(s2_init)\n\n # bundle model parameters in custom numpy array\n model_params = np.zeros(1, dtype=self._dtype)\n for param in self._param_list:\n model_params[param] = getattr(self, param)\n \n if return_storage:\n # call the actual simulation function\n qsim, snow, soil, s1, s2 = _simulate_hbv_edu(temp, prec, month, \n PE_m, T_m, snow_init,\n soil_init, s1_init, \n s2_init, model_params)\n\n # TODO: conversion from qobs in m³/s for different time resolutions\n # At the moment expects daily input data\n qsim = (qsim * self.area * 1000) / (24 * 60 * 60)\n \n return qsim, snow, soil, s1, s2\n \n else:\n # call the actual simulation function\n qsim, _, _, _, _ = _simulate_hbv_edu(temp, prec, month, PE_m, T_m, \n snow_init, soil_init, s1_init, \n s2_init, model_params)\n\n # TODO: conversion from qobs in m³/s for different time resolutions\n # At the moment expects daily input data\n qsim = (qsim * self.area * 1000) / (24 * 60 * 60)\n \n return qsim\n\n return qsim\n\n def fit(self, qobs, temp, prec, month, PE_m, T_m, snow_init=0.,\n soil_init=0., s1_init=0., s2_init=0.):\n \"\"\"Fit the HBVEdu model to a timeseries of discharge.\n\n This functions uses scipy's global optimizer (differential evolution)\n to find a good set of parameters for the model, so that the observed \n discharge is simulated as good as possible.\n\n Args:\n qobs: Array of observed streamflow discharge.\n temp: Array of (mean) temperature for each timestep.\n prec: Array of (summed) precipitation for each timestep.\n month: Array of integers indicating for each timestep to which\n month it belongs [1,2, ..., 12]. Used for adjusted\n potential evapotranspiration.\n PE_m: long-term mean monthly potential evapotranspiration.\n T_m: long-term mean monthly temperature.\n snow_init: (optional) Initial state of the snow reservoir.\n soil_init: (optional) Initial state of the soil reservoir.\n s1_init: (optional) Initial state of the near surface flow\n reservoir.\n s2_init: (optional) Initial state of the base flow reservoir.\n\n Returns:\n res: A scipy OptimizeResult class object.\n \n Raises:\n ValueError: If one of the inputs contains invalid values.\n TypeError: If one of the inputs has an incorrect datatype.\n RuntimeErrror: If the monthly arrays are not of size 12 or there \n is a size mismatch between precipitation, temperature and the\n month array.\n\n \"\"\"\n # Validation check of the temperature, precipitation and qobs input\n temp = validate_array_input(temp, np.float64, 'temperature')\n prec = validate_array_input(prec, np.float64, 'precipitation')\n qobs = validate_array_input(qobs, np.float64, 'observed discharge')\n # Check if there exist negative precipitation\n if check_for_negatives(prec):\n raise ValueError(\"In the precipitation array are negative values.\")\n \n month = validate_array_input(month, np.int8, 'month')\n if any(len(arr) != len(temp) for arr in [prec, month]):\n msg = [\"The arrays of the temperature, precipitation and month \",\n \"data must be of equal size.\"]\n raise RuntimeError(\"\".join(msg))\n\n # Validation check for PE_m and T_m\n PE_m = validate_array_input(PE_m, np.float64, 'PE_m')\n T_m = validate_array_input(T_m, np.float64, 'T_m')\n if any(len(arr) != 12 for arr in [PE_m, T_m]):\n msg = [\"The monthly potential evapotranspiration and temperature\",\n \" array must be of length 12.\"]\n raise RuntimeError(\"\".join(msg))\n\n # Check if entires of month array are between 1 and 12\n if (np.min(month) < 1) or (np.max(month) > 12):\n msg = [\"The month array must be between an integer1 (Jan) and \",\n \"12 (Dec).\"]\n raise ValueError(\"\".join(msg))\n\n # For correct python indexing [start with 0] subtract 1 of month array\n month -= 1\n\n # Make sure all initial storage values are floats\n snow_init = float(snow_init)\n soil_init = float(soil_init)\n s1_init = float(s1_init)\n s2_init = float(s2_init)\n\n # pack input arguments for scipy optimizer\n args = (qobs, temp, prec, month, PE_m, T_m, snow_init, soil_init,\n s1_init, s2_init, self._dtype, self.area)\n bnds = tuple([self._default_bounds[p] for p in self._param_list])\n \n # call scipy's global optimizer\n res = optimize.differential_evolution(_loss, bounds=bnds, args=args)\n\n return res\n\n\ndef _loss(X, *args):\n \"\"\"Return the loss value for the current parameter set.\"\"\"\n # Unpack static arrays\n qobs = args[0]\n temp = args[1]\n prec = args[2]\n month = args[3]\n PE_m = args[4]\n T_m = args[5]\n snow_init = args[6]\n soil_init = args[7]\n s1_init = args[8]\n s2_init = args[9]\n dtype = args[10]\n area = args[11]\n\n # Create custom numpy array of model parameters\n params = np.zeros(1, dtype=dtype)\n params['T_t'] = X[0]\n params['DD'] = X[1]\n params['FC'] = X[2]\n params['Beta'] = X[3]\n params['C'] = X[4]\n params['PWP'] = X[5]\n params['K_0'] = X[6]\n params['K_1'] = X[7]\n params['K_2'] = X[8]\n params['K_p'] = X[9]\n params['L'] = X[10]\n\n # Calculate simulated streamflow\n qsim,_,_,_,_ = _simulate_hbv_edu(temp, prec, month, PE_m, T_m, snow_init,\n soil_init, s1_init, s2_init, params)\n \n # transform discharge to m³/s\n qsim = (qsim * area * 1000) / (24 * 60 * 60)\n\n # Calculate the Mean-Squared-Error as optimization criterion\n loss_value = mse(qobs, qsim)\n\n return loss_value\n\n\n@njit\ndef _simulate_hbv_edu(temp, prec, month, PE_m, T_m, snow_init, soil_init,\n s1_init, s2_init, model_params):\n \"\"\"Run the educational HBV model for given inputs and model parameters.\"\"\"\n # Unpack the model parameters\n T_t = model_params['T_t'][0]\n DD = model_params['DD'][0]\n FC = model_params['FC'][0]\n Beta = model_params['Beta'][0]\n C = model_params['C'][0]\n PWP = model_params['PWP'][0]\n K_0 = model_params['K_0'][0]\n K_1 = model_params['K_1'][0]\n K_2 = model_params['K_2'][0]\n K_p = model_params['K_p'][0]\n L = model_params['L'][0]\n\n # get number of simulation timesteps\n num_timesteps = len(temp)\n\n # initialize empty arrays for all reservoirs and outflow\n snow = np.zeros(num_timesteps, np.float64)\n soil = np.zeros(num_timesteps, np.float64)\n s1 = np.zeros(num_timesteps, np.float64)\n s2 = np.zeros(num_timesteps, np.float64)\n qsim = np.zeros(num_timesteps, np.float64)\n\n # set initial values\n snow[0] = snow_init\n soil[0] = soil_init\n s1[0] = s1_init\n s2[0] = s2_init\n\n # Start the model simulation as loop over all timesteps\n for t in range(1, num_timesteps):\n\n # Check if temperature is below threshold\n if temp[t] < T_t:\n # accumulate snow\n snow[t] = snow[t-1] + prec[t]\n # no liquid water\n liquid_water = 0\n else:\n # melt snow\n snow[t] = max(0, snow[t-1] - DD * (temp[t] - T_t))\n # add melted snow to available liquid water\n liquid_water = prec[t] + min(snow[t-1], DD * (temp[t] - T_t))\n\n # calculate the effective precipitation\n prec_eff = liquid_water * (soil[t-1] / FC) ** Beta\n\n # Calculate the potential evapotranspiration\n pe = (1 + C * (temp[t] - T_m[month[t]])) * PE_m[month[t]]\n\n # Calculate the actual evapotranspiration\n if soil[t-1] > PWP:\n ea = pe\n else:\n ea = pe * (soil[t-1] / PWP)\n\n # calculate the actual level of the soil reservoir\n soil[t] = soil[t-1] + liquid_water - prec_eff - ea\n\n # calculate the actual level of the near surface flow reservoir\n s1[t] = (s1[t-1]\n + prec_eff\n - max(0, s1[t-1] - L) * K_0\n - s1[t-1] * K_1\n - s1[t-1] * K_p)\n\n # calculate the actual level of the base flow reservoir\n s2[t] = (s2[t-1]\n + s1[t-1] * K_p\n - s2[t-1] * K_2)\n\n qsim[t] = ((max(0, s1[t-1] - L)) * K_0\n + s1[t] * K_1\n + s2[t] * K_2)\n \n return qsim, snow, soil, s1, s2\n","sub_path":"rrmpg/models/hbvedu.py","file_name":"hbvedu.py","file_ext":"py","file_size_in_byte":15837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"473363988","text":"import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n\n\ndf = pd.read_csv(\"https://raw.githubusercontent.com/AC2005/covid-learning/main/output/sc_predicts.csv\")\n\ndef calc_percent_error(data, startdate):\n individual_percent_error = list()\n dates = list()\n predict = list()\n actual = list()\n filtered_data = df.loc[df[\"Date\"] >= startdate]\n filtered_data.reset_index(drop=True, inplace=True)\n for i in range(len(filtered_data)):\n actual_data = int(filtered_data['ActualCases'][i])\n predicts = int(filtered_data[\"Predicts\"][i])\n if predicts == 0 or actual_data == 0:\n continue\n dates.append(filtered_data['Date'][i])\n predict.append(predicts)\n actual.append(actual_data)\n temp_perc_error = np.abs((actual_data - predicts)/(predicts))\n individual_percent_error.append(temp_perc_error)\n\n std = np.std(individual_percent_error)\n avg = np.average(individual_percent_error)\n\n max_list = [predict[i] * (1+2*std) for i in range(len(predict))]\n min_list = [predict[i] * (1-2*std) for i in range(len(predict))]\n adjusted_data_set = pd.DataFrame(\n {'Date': dates,\n 'ActualCases': actual,\n 'Preidcts': predict,\n '+2 STD': max_list,\n '-2 STD': min_list\n })\n return adjusted_data_set\n\nnew_data = calc_percent_error(data=df, startdate=\"2020-10-01\")\n\n# plt.plot(max)\n# plt.plot(min)\n# plt.show()\n\n\nprint(max)\nprint(min)\n","sub_path":"model/output_visualization.py","file_name":"output_visualization.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"62969377","text":"# -*- coding: utf-8 -*-\n\n__all__ = ['ArticleDetails', 'ArticleStaying', 'ArticleComments', 'ArticleCommentDetails', 'ArticleLikes',\n 'ArticleShares', 'ArticleUnlike', 'ArticleReport', 'ArticleRedirect']\n\nfrom corelib.views import BaseAPIView\nfrom corelib.response import STATUS_OK_RESPONSE\nfrom corelib.keys import KEY_COUNT, KEY_READ_TAG, KEY_MODE\nfrom corelib.consts import OFFLINE_MODE, REONLINE_MODE\nfrom corelib.exceptions.base import RequestParamInvalid\nfrom corelib.recommendation.engine import RecommendationEngine\n\nfrom rest_framework.permissions import AllowAny\nfrom rest_framework.response import Response\nfrom django.http.response import HttpResponseRedirect\n\nfrom article.models import Article\nfrom article.keys import KEY_PLATFORM, KEY_REASON, KEY_CONTENT, KEY_DURATION, ARTICLE_RELATE_COUNT\nfrom article.serializers import CommentCompactSerializer, ArticleProfileSerializer, ArticleCompactSerializer\nfrom article.utils import get_article_view_swith_params\nfrom article.exceptions import CommentNoContent\nfrom category.consts import REC_CATE\n\n\nclass ArticleBaseView(BaseAPIView):\n def initial(self, request, article_id, *args, **kwargs):\n self.article_id = article_id\n self.article = Article.get(article_id)\n super(ArticleBaseView, self).initial(request, *args, **kwargs)\n\n\nclass ArticleDetails(ArticleBaseView):\n def update_data(self, data, switch):\n if not switch:\n return\n del data['content']\n del data['related_images']\n del data['top_images']\n data['switch'] = True\n\n def get(self, request, *args, **kwargs):\n user = request.user\n req_mode = request.QUERY_PARAMS.get(KEY_MODE, '')\n req_user = None\n if not req_mode == OFFLINE_MODE:\n if not user.is_anonymous():\n user.add_read_log(self.article)\n user.update_feature(self.article.feature_matrix)\n req_user = user\n if req_mode == REONLINE_MODE:\n return STATUS_OK_RESPONSE\n\n for cate in self.article.category:\n if cate != \"Top Stories\":\n try:\n category = CATE_NAME_MAPPING[cate]\n except:\n category = REC_CATE\n\n article_seq_ids = RecommendationEngine.fetch_n_article(user, category, ARTICLE_RELATE_COUNT * 2)\n import random\n article_seq_ids = random.sample(article_seq_ids, ARTICLE_RELATE_COUNT * 2)\n articles = Article.objects(seq_id__in=article_seq_ids).exclude('text', 'feature')\n usable_articles = (article for article in articles if article.usable)\n indeed_articles = []\n for article in usable_articles:\n if len(indeed_articles) < ARTICLE_RELATE_COUNT:\n indeed_articles.append(ArticleCompactSerializer(article).data)\n\n data = ArticleProfileSerializer(self.article, req_user, indeed_articles).data\n switch = get_article_view_swith_params(request)\n self.update_data(data, switch)\n\n return Response(data)\n\n\nclass ArticleRedirect(ArticleBaseView):\n def get(self, request, *args, **kwargs):\n return HttpResponseRedirect(self.article.source_url)\n\n\nclass ArticleStaying(ArticleBaseView):\n def post(self, request, *args, **kwargs):\n user = request.user\n duration = request.DATA.get(KEY_DURATION, 0)\n try:\n duration = float(duration)\n except ValueError:\n duration = 0\n if not duration:\n raise RequestParamInvalid\n user.add_duration_to_read_log(self.article, duration)\n return STATUS_OK_RESPONSE\n\n\nclass ArticleComments(ArticleBaseView):\n def get(self, request, *args, **kwargs):\n read_tag = request.QUERY_PARAMS.get(KEY_READ_TAG)\n count = request.QUERY_PARAMS.get(KEY_COUNT, 10)\n comments = self.article.get_comments(count, read_tag)\n return Response([CommentCompactSerializer(comment).data for comment in comments])\n\n def post(self, request, *args, **kwargs):\n content = request.DATA.get(KEY_CONTENT)\n if not content:\n raise CommentNoContent\n comment = self.article.add_comment(request.user, content)\n return Response(CommentCompactSerializer(comment).data)\n\nclass NotificationClickReport(ArticleBaseView):\n def post(self, request, *args, **kwargs):\n user = request.user\n push_id = request.DATA.get('push_id', -1)\n user.mark_notifications(self.article, int(push_id))\n\n return STATUS_OK_RESPONSE\n\n\nclass ArticleCommentDetails(ArticleBaseView):\n def get(self, request, comment_id, *args, **kwargs):\n comment = self.article.get_comment(comment_id)\n return Response(CommentCompactSerializer(comment).data)\n\n def delete(self, request, comment_id, *args, **kwargs):\n self.article.delete_comment(request.user, comment_id)\n return STATUS_OK_RESPONSE\n\n\nclass ArticleLikes(ArticleBaseView):\n def post(self, request, *args, **kwargs):\n self.article.add_like(request.user)\n return STATUS_OK_RESPONSE\n\n def delete(self, request, *args, **kwargs):\n self.article.cancel_like(request.user)\n return STATUS_OK_RESPONSE\n\n\nclass ArticleShares(ArticleBaseView):\n permission_classes = (AllowAny,)\n\n def post(self, request, *args, **kwargs):\n platform = request.DATA.get(KEY_PLATFORM)\n self.article.sharing(request.user, platform)\n return STATUS_OK_RESPONSE\n\n\nclass ArticleUnlike(ArticleBaseView):\n def post(self, request, *args, **kwargs):\n reason = request.DATA.get(KEY_REASON)\n self.article.add_unlike(request.user, reason)\n user = request.user\n if self.article.feature_matrix is not None:\n user.update_feature(-1 * self.article.feature_matrix)\n return STATUS_OK_RESPONSE\n\n\nclass ArticleReport(ArticleBaseView):\n def post(self, request, *args, **kwargs):\n reason = request.DATA.get(KEY_REASON)\n self.article.add_report(request.user, reason)\n self.article.frozen()\n return STATUS_OK_RESPONSE\n","sub_path":"prometheus/article/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"402605271","text":"from flask import Flask,jsonify, request\nfrom flaskext.mysql import MySQL \nfrom flask_cors import CORS\n\napp = Flask(__name__)\n\n#Configuracion DB\napp.config['MYSQL_DATABASE_HOST'] = 'localhost'\napp.config['MYSQL_DATABASE_PORT'] = 3306\napp.config['MYSQL_DATABASE_DB'] = 'games_db'\napp.config['MYSQL_DATABASE_USER'] = 'root'\napp.config['MYSQL_DATABASE_PASSWORD'] = ''\n\nmysql = MySQL()\nmysql.init_app(app)\nCORS(app)\n\n#Test que funcione el servidor\n@app.route('/')\ndef ping():\n return 'pong'\n\n\n@app.route('/api/games', methods=['GET'])\ndef get_games():\n cur = mysql.get_db().cursor()\n cur.execute('SELECT * FROM games')\n game_list = cur.fetchall()\n games = []\n for game in game_list:\n new_game = {\"id\":game[0], \"title\":game[1], \"description\":game[2], \"image\":game[3]}\n games.append(new_game)\n return jsonify(games)\n\n@app.route('/api/games/', methods=['GET'])\ndef get_game(id):\n if request.method == 'GET':\n cur = mysql.get_db().cursor()\n cur.execute('SELECT * FROM games WHERE id = %s',(id))\n game_list = cur.fetchall()\n games = []\n for game in game_list:\n new_game = {\"id\":game[0], \"title\":game[1], \"description\":game[2], \"image\":game[3]}\n games.append(new_game)\n return jsonify(games)\n\n\n@app.route('/api/games', methods=['POST'])\ndef add_game():\n if request.method == 'POST':\n title = request.json['title']\n description = request.json['description']\n image = request.json['image']\n cur = mysql.get_db().cursor()\n cur.execute('INSERT INTO games (title,description,image) VALUES (%s,%s,%s)',(title,description,image))\n mysql.get_db().commit()\n return jsonify({'message':'game added successfully'})\n\n@app.route('/api/games/', methods=['PUT'])\ndef edit_game(id):\n if request.method == 'PUT':\n title = request.json['title']\n description = request.json['description']\n image = request.json['image']\n cur = mysql.get_db().cursor()\n cur.execute('UPDATE games SET title=%s, description=%s, image=%s WHERE id=%s',(title,description,image,id))\n mysql.get_db().commit()\n games = [{'id':id,'title':title,'description':description,'image':image}]\n return jsonify(games)\n\n@app.route('/api/games/', methods=['DELETE'])\ndef delete_game(id):\n if request.method == 'DELETE':\n cur = mysql.get_db().cursor()\n cur.execute('DELETE FROM games WHERE id=%s',id)\n mysql.get_db().commit()\n return jsonify({\"message\":\"game deleted successfully\"})\n\n\n#Arranco el servidor en modo prueba en el puerto 3000\nif __name__ == \"__main__\":\n app.run(debug=True,port=3000)\n\n ","sub_path":"server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"179158287","text":"from django.core.urlresolvers import reverse\nfrom django_webtest import WebTest\nimport webtest\n\nfrom django.contrib.auth.models import User\nfrom evap.evaluation.models import Semester, Questionnaire\n\nimport os.path\n\n\ndef lastform(page):\n return page.forms[max(page.forms.keys())]\n\n\nclass UsecaseTests(WebTest):\n fixtures = ['usecase-tests']\n \n extra_environ = {'HTTP_ACCEPT_LANGUAGE': 'en'}\n \n def test_import(self):\n page = self.app.get(reverse(\"fsr_root\"), user=\"fsr.user\")\n \n # create a new semester\n page = page.click(\"[Ss]emesters\")\n page = page.click(\"[Nn]ew [Ss]emester\")\n semester_form = lastform(page)\n semester_form['name_de'] = \"Testsemester\"\n semester_form['name_en'] = \"test semester\"\n page = semester_form.submit().follow()\n \n # retrieve new semester\n semester = Semester.objects.get(name_de=\"Testsemester\",\n name_en=\"test semester\")\n \n self.assertEqual(semester.course_set.count(), 0, \"New semester is not empty.\")\n \n # safe original user count\n original_user_count = User.objects.all().count()\n \n # import excel file\n page = page.click(\"[Ii]mport\")\n upload_form = lastform(page)\n upload_form['vote_start_date'] = \"02/29/2000\"\n upload_form['vote_end_date'] = \"02/29/2012\"\n upload_form['excel_file'] = (os.path.join(os.path.dirname(__file__), \"fixtures\", \"samples.xls\"),)\n page = upload_form.submit().follow()\n \n self.assertEqual(semester.course_set.count(), 23, \"Wrong number of courses after Excel import.\")\n self.assertEqual(User.objects.count(), original_user_count + 24, \"Wrong number of users after Excel import.\")\n \n check_student = User.objects.get(username=\"Diam.Synephebos\")\n self.assertEqual(check_student.first_name, \"Diam\")\n self.assertEqual(check_student.email, \"Diam.Synephebos@student.hpi.uni-potsdam.de\")\n \n check_lecturer = User.objects.get(username=\"Sanctus.Aliquyam\")\n self.assertEqual(check_lecturer.first_name, \"Sanctus\")\n self.assertEqual(check_lecturer.last_name, \"Aliquyam\")\n self.assertEqual(check_lecturer.email, \"567@web.de\")\n \n def test_logon_key(self):\n with self.assertRaises(webtest.app.AppError):\n self.app.get(reverse(\"evap.results.views.index\"))\n \n user = User.objects.all()[0]\n userprofile = user.get_profile()\n userprofile.generate_logon_key()\n userprofile.save()\n \n url_with_key = reverse(\"evap.results.views.index\") + \"?userkey=%s\" % userprofile.logon_key\n self.app.get(url_with_key)\n \n def test_create_questionnaire(self):\n page = self.app.get(reverse(\"fsr_root\"), user=\"fsr.user\")\n \n # create a new questionnaire\n page = page.click(\"[Qq]uestionnaires\")\n page = page.click(\"[Nn]ew [Qq]uestionnaire\")\n questionnaire_form = lastform(page)\n questionnaire_form['name_de'] = \"Test Fragebogen\"\n questionnaire_form['name_en'] = \"test questionnaire\"\n questionnaire_form['public_name_de'] = \"Oeffentlicher Test Fragebogen\"\n questionnaire_form['public_name_en'] = \"Public Test Questionnaire\"\n questionnaire_form['question_set-0-text_de'] = \"Frage 1\"\n questionnaire_form['question_set-0-text_en'] = \"Question 1\"\n questionnaire_form['question_set-0-kind'] = \"T\"\n page = questionnaire_form.submit().follow()\n \n # retrieve new questionnaire\n questionnaire = Questionnaire.objects.get(name_de=\"Test Fragebogen\", name_en=\"test questionnaire\")\n self.assertEqual(questionnaire.question_set.count(), 1, \"New questionnaire is empty.\")\n \n def test_create_empty_questionnaire(self):\n page = self.app.get(reverse(\"fsr_root\"), user=\"fsr.user\")\n \n # create a new questionnaire\n page = page.click(\"[Qq]uestionnaires\")\n page = page.click(\"[Nn]ew [Qq]uestionnaire\")\n questionnaire_form = lastform(page)\n questionnaire_form['name_de'] = \"Test Fragebogen\"\n questionnaire_form['name_en'] = \"test questionnaire\"\n questionnaire_form['public_name_de'] = \"Oeffentlicher Test Fragebogen\"\n questionnaire_form['public_name_en'] = \"Public Test Questionnaire\"\n page = questionnaire_form.submit()\n \n assert \"You must have at least one of these\" in page\n \n # retrieve new questionnaire\n with self.assertRaises(Questionnaire.DoesNotExist):\n Questionnaire.objects.get(name_de=\"Test Fragebogen\", name_en=\"test questionnaire\")\n \n def test_copy_questionnaire(self):\n page = self.app.get(reverse(\"fsr_root\"), user=\"fsr.user\")\n \n # create a new questionnaire\n page = page.click(\"[Qq]uestionnaires\")\n page = page.click(\"Copy\")\n questionnaire_form = lastform(page)\n questionnaire_form['name_de'] = \"Test Fragebogen (kopiert)\"\n questionnaire_form['name_en'] = \"test questionnaire (copied)\"\n questionnaire_form['public_name_de'] = \"Oeffentlicher Test Fragebogen (kopiert)\"\n questionnaire_form['public_name_en'] = \"Public Test Questionnaire (copied)\"\n page = questionnaire_form.submit().follow()\n \n # retrieve new questionnaire\n questionnaire = Questionnaire.objects.get(name_de=\"Test Fragebogen (kopiert)\", name_en=\"test questionnaire (copied)\")\n self.assertEqual(questionnaire.question_set.count(), 2, \"New questionnaire is empty.\")\n \n def test_assign_questionnaires(self):\n page = self.app.get(reverse(\"fsr_root\"), user=\"fsr.user\")\n \n # assign questionnaire to courses\n page = page.click(\"Semester 1 \\(en\\)\", index=0)\n page = page.click(\"Assign Questionnaires\")\n assign_form = lastform(page)\n assign_form['Seminar'] = [1]\n assign_form['Vorlesung'] = [1]\n page = assign_form.submit().follow()\n \n # get semester and check\n semester = Semester.objects.get(pk=1)\n questionnaire = Questionnaire.objects.get(pk=1)\n for course in semester.course_set.all():\n self.assertEqual(course.general_assignment.questionnaires.count(), 1)\n self.assertEqual(course.general_assignment.questionnaires.get(), questionnaire)\n","sub_path":"evap/fsr/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":6403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}